np.linalg.inv
np.linalg.inv(a)
计算一个矩阵的逆
Compute the (multiplicative) inverse of a matrix.
Given a square matrix a, return the matrix ainv satisfying
dot(a, ainv) = dot(ainv, a) = eye(a.shape[0])
.
import numpy as np
from numpy.linalg import inv
a = np.array([[1., 2.], [3., 4.]])
ainv = inv(a)
np.allclose(np.dot(a, ainv), np.eye(2))
np.allclose(np.dot(ainv, a), np.eye(2))
'''
[[-2. 1. ]
[ 1.5 -0.5]]
True
True
'''
# 可以同时求多个方阵的逆
x1 = np.array([[1., 2.], [3., 4.]])
x2 = np.array([[1, 3], [3, 5]])
a = np.array([[[1., 2.], [3., 4.]], [[1, 3], [3, 5]]])
print(inv(a))
print(inv(x1))
print(inv(x2))
'''
[[[-2. 1. ]
[ 1.5 -0.5 ]]
[[-1.25 0.75]
[ 0.75 -0.25]]]
[[-2. 1. ]
[ 1.5 -0.5]]
[[-1.25 0.75]
[ 0.75 -0.25]]
'''
np.linalg.norm
np.linalg.norm
计算矩阵或者向量的逆
Matrix or vector norm.
This function is able to return one of eight different matrix norms, or one of an infinite number of vector norms (described below), depending on the value of the
ord
parameter.
import numpy as np
import numpy.linalg as LA
a = np.arange(9)
print(a)
print(LA.norm(a, np.inf)) # 无穷范数
print(LA.norm(a, -np.inf))
print(LA.norm(a, 1)) # 1范数
print(LA.norm(a, 2))
'''
[0 1 2 3 4 5 6 7 8]
8.0
0.0
36.0
14.2828568570857
'''
ord | norm for matrices | norm for vectors |
---|---|---|
None | Frobenius norm | 2-norm |
‘fro’ | Frobenius norm | – |
‘nuc’ | nuclear norm | – |
inf | max(sum(abs(x), axis=1)) | max(abs(x)) |
-inf | min(sum(abs(x), axis=1)) | min(abs(x)) |
0 | – | sum(x != 0) |
1 | max(sum(abs(x), axis=0)) | as below |
-1 | min(sum(abs(x), axis=0)) | as below |
2 | 2-norm (largest sing. value) | as below |
-2 | smallest singular value | as below |
other | – | sum(abs(x)ord)(1./ord) |