线性代数(如矩阵乘法、矩阵分解、行列式以及其他方阵数学等)是任何数组库的重要组成部分,NumPy提供了一个用于矩阵乘法的dot函数(既是一个数组方法也是numpy命名空间中的一个函数).
x = np.array([[1., 2., 3.], [4., 5., 6.]])
y = np.array([[6., 23.], [-1, 7], [8, 9]])
np.dot(x, y)
Out:
array([[ 28., 64.],
[ 67., 181.]])
x = np.array([[1., 2., 3.], [11., 3., 6.], [7., 8., 7.]])
np.cov(x)
Out:
array([[ 1. , -2.5 , 0. ],
[-2.5 , 16.33333333, -1.83333333],
[ 0. , -1.83333333, 0.33333333]])
x = np.array([[1., 2., 3.], [11., 3., 6.], [7., 8., 7.]])
np.corrcoef(x)
Out:
array([[ 1. , -0.61858957, 0. ],
[-0.61858957, 1. , -0.78571429],
[ 0. , -0.78571429, 1. ]])
x = np.array([[1., 2., 3.], [11., 3., 6.], [7., 8., 7.]])
x
Out:
array([[ 1., 2., 3.],
[11., 3., 6.],
[ 7., 8., 7.]])
np.diag(x,1)
Out:
array([2., 6.])
x = np.array([[1., 2., 3.], [11., 3., 6.], [7., 8., 7.]])
np.trace(x)
Out:
11.0
x = np.array([[1., 2., 3.], [11., 3., 6.], [7., 8., 7.]])
x
Out:
array([[ 1., 2., 3.],
[11., 3., 6.],
[ 7., 8., 7.]])
np.hstack(x)
Out:
array([ 1., 2., 3., 11., 3., 6., 7., 8., 7.])
numpy.linalg中有一组标准的矩阵分解运算以及诸如求逆和行列式之类的东西。它们跟MATLAB和R等语言所使用的是相同的行业标准线性代数库,如BLAS、LAPACK、Intel MKL(Math Kernel Library,可能有,取决于你的NumPy版本)等:
numpy.linalg.det(x) :计算矩阵行列式
numpy.linalg.eig(x) :计算方阵特征值和特征向量
numpy.linalg.inv(x) :计算方阵的逆
numpy.linalg.pinv(x) :计算矩阵的Moore-Penrose伪逆
numpy.linalg.qr(x) : 计算QR分解
numpy.linalg.svd(x) :计算奇异值分解(SVD)
numpy.linalg.slove():解线性方程组Ax=b,其中A为一个方阵
numpy.linalg.lstsq() :计算Ax=b的最小二乘解
参考资料:https://github.com/iamseancheney/python_for_data_analysis_2nd_chinese_version