matplotlib
import matplotlib.pyplot as plt
# 绘制数据散点图
plt.scatter(dataMat[0],dataMat[1],c = ‘red‘,marker = ‘o‘)
numpy
import numpy as np
生成向量、矩阵
vec = np.linspace(-2,2,100) # 产生直线数据 myZero = np.zeros([3,5]) # 3*5的全0矩阵 myZero = np.ones([3,5]) # 3*5的全1矩阵 myRand = np.random.rand(3,4) # 3行4列的0~1之间的随机数矩阵 myEye = np.eye(3) # 3*3的矩阵
四则运算
newMat = myOnes + myEye # 元素的加和减(条件是矩阵的行数和列数必须相同) newMat = a*matrix # 矩阵乘常数 newMat = matrix.sum() # 矩阵全部元素求和 ‘‘‘ 矩阵各元素的积:矩阵的点乘同维对应元素的相乘。 当矩阵的维度不同时,会根据一定的广播将维数扩 充到一致的形式 ‘‘‘ matrix1 = mat([[1,2,3],[4,5,6],[7,8,9]]) matrix2 = 1.5*ones([3,3]) newMat = multiply(matrix1, matrix2) 输出结果: [[ 1.5 3. 4.5] [ 6. 7.5 9. ] [ 10.5 12. 13.5]] # 矩阵乘矩阵 matrix1 = mat([[1,2,3],[4,5,6],[7,8,9]]) matrix2 = mat([[1],[2],[3]]) newMat =matrix1 * matrix2 输出结果: [[14] [32] [50]] newMat = power(matrix1, 2) # 矩阵各元素的n次幂:n=2
矩阵的变换
# 矩阵的转置 newMat = matrix1.T matrix1.transpose() # 转置(改写原矩阵) from numpy import linalg A = mat([[1,2,3],[4,5,6],[7,8,9]]) invA = linalg.inv(A) # 矩阵的逆 n = linalg.det(A) # 矩阵的行列式运算 n = linalg.matrix_rank(A) # 矩阵的秩
矩阵其它操作
mymatrix = mymatrix1[0] # 按行切片 print u"按行切片:",mymatrix mymatrix = mymatrix1.T[0] # 按列切片 print u"按列切片:",mymatrix mymatrix = mymatrix1.copy() # 矩阵的复制 print u"复制矩阵:",mymatrix print u"矩阵元素的比较:\n",mymatrix<mymatrix1.T ‘‘‘ 输出结果 ‘‘‘ 矩阵的行数和列数: 3 3 按行切片: [[1 2 3]] 按列切片: [[1 4 7]] 复制矩阵: [[1 2 3] [4 5 6] [7 8 9]] 矩阵元素的比较: [[False True True] [False False True] [False False False]]
可逆矩阵求解
A = np.mat([[1,2,4,5,7],[9,12,11,8,2],[6,4,3,2,1],[9,1,3,4,5],[0,2,3,4,1]]) b = np.mat([1, 0, 1, 0, 1]) S = linalg.solve(A, b.T) # 输出结果: matrix([[-0.0270936 ], [ 1.77093596], [-3.18472906], [ 1.68965517], [ 0.25369458]])
原文地址:https://www.cnblogs.com/brt3/p/10301853.html
时间: 2024-11-13 18:55:42