Python 實現(xiàn)線性代數(shù)
類型 |
說明 |
diag |
以一維數(shù)組的形式返回方陣的對角線(或非對角線元素)舰攒,獲將一維數(shù)組轉(zhuǎn)換為方陣(非對角線元素為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]]
最后編輯于 :
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者