numpy -- 实现线性代数

Python 实现线性代数

类型 说明
diag 以一维数组的形式返回方阵的对角线(或非对角线元素),获将一维数组转换为方阵(非对角线元素为0)。
dot 矩阵乘法
trace 计算对角线元素的和
det 计算矩阵行列式
eig 计算方阵的特征值和特征向量
inv 计算方阵的逆
pinv 计算矩阵的Moore-Penrose伪逆
qr 计算QR分解
svd 计算奇异值分解
solve 解线性方程Ax = b,其中A为一个方阵。
lstsq 计算Ax = b的最小二乘解
import numpy as np
from numpy.linalg import qr,inv

m_n 与 n_k 这样的矩阵才能相乘

x = np.array([[1., 2., 3.], [4., 5., 6.]])
y = np.array([[6., 23.], [-1, 7], [8, 9]])
print (x.dot(y))  #m*n 与 n*k 这样的矩阵才能相乘
[[  28.   64.]
 [  67.  181.]]

矩阵求逆

x = np.random.randn(5,5)
mat = x.T.dot(x)

print(x)
print(inv(x))
[[ 0.7790666  -0.78752423 -0.18878797  0.5581075  -1.61546829]
 [ 0.75483935 -0.5364182   0.6048796  -1.42387141 -0.32631365]
 [ 0.80629782  0.37388657  0.18614589 -1.75530901  0.2837992 ]
 [ 0.95656129  1.13613929  1.94612447 -0.36595968 -1.62149476]
 [-0.01910138  0.16987845 -1.42035673  0.07531867 -0.38779195]]
[[ 1.48095724 -1.97148302  2.09712765 -0.39883112 -1.30805173]
 [-0.18088834 -0.60292082  0.37731223  0.30987641  0.24131137]
 [-0.1244768   0.18891431 -0.24237096  0.14789152 -0.4361798 ]
 [ 0.69962158 -1.19023758  0.62133934 -0.1692852  -0.75038957]
 [ 0.43961374 -1.09011555  1.07039579 -0.4191668  -0.95671982]]

矩阵和矩阵的逆相乘结果为单位矩阵

print(x.dot(inv(x)))
[[  1.00000000e+00   4.41462237e-16  -3.15803378e-17  -1.22015842e-16
    1.11654339e-16]
 [  1.09981782e-16   1.00000000e+00   1.08005572e-16  -7.93525777e-17
   -3.55449359e-16]
 [  1.03225438e-16   1.51104378e-16   1.00000000e+00   2.27484325e-17
    1.61648960e-16]
 [  1.69815771e-17   1.49462996e-16  -8.15455852e-17   1.00000000e+00
   -2.76105720e-16]
 [  3.86987981e-18   1.66074574e-17  -1.13230713e-18   3.33384685e-17
    1.00000000e+00]]

qr分解

print(mat)

q,r = qr(mat)
print(r)
[[ 2.74221776  0.36656248  2.34831565 -2.40679464 -2.81969686]
 [ 0.36656248  2.36740124  1.8635846  -0.73500526 -0.35475169]
 [ 2.34831565  1.8635846   6.2409842  -2.11256078 -2.44439918]
 [-2.40679464 -0.73500526 -2.11256078  5.55960288 -0.37093785]
 [-2.81969686 -0.35475169 -2.44439918 -0.37093785  5.57638823]]
[[-5.18768383 -1.73845955 -6.50684963  4.65819252  5.48094996]
 [ 0.         -2.6183476  -3.05966333  0.92267964 -0.53241157]
 [ 0.          0.         -2.58356078 -0.8085167   0.52279694]
 [ 0.          0.          0.         -4.31726658  3.83043936]
 [ 0.          0.          0.          0.          0.12437921]]

你可能感兴趣的:(numpy -- 实现线性代数)