Data Analysis Study Notes (4) - numpy: Linear Algebra

Common linalg functions

function illustrate
diag Returns the diagonal (or off-diagonal) elements of a square matrix as a 1D array, or converts a 1D array to a square matrix (off-diagonal elements are 0)
dot Standard Matrix Multiplication
trace Calculate the sum of the diagonal elements
the compute matrix determinant
own Calculate the eigenvalues ​​of a matrix
own Calculate the eigenvalues ​​and eigenvectors of a square matrix
inv Compute the inverse of a square matrix
pinv Compute Moore-Penrose pseudoinverse of a matrix
qr Calculate the QR decomposition
svd Compute Singular Value Decomposition (SVD)
solve Solve a system of linear equations Ax=b, where A is a square matrix
lstsq Compute the least squares solution for Ax=b
  • diag
# diag
x = np.arange(9).reshape((3,3))
print(x)
'''
[[0 1 2]
 [3 4 5]
 [6 7 8]]'''
# 取对角线上的数据
print(np.diag(x))
'''[0 4 8]'''
# k>0,主对角线之上
print(np.diag(x, k=1))
'''[1 5]'''
# k<0,主对角线之下
print(np.diag(x, k=-1))
'''[3 7]'''
# 通过对角线上的数据数组创建矩阵
print(np.diag(np.diag(x)))
'''[[0 0 0]
 [0 4 0]
 [0 0 8]]
 '''
  • dot : matrix multiplication
# dot
A = np.arange(9).reshape((3,3))
print(A)
'''[[0 1 2]
 [3 4 5]
 [6 7 8]]
 '''
B = np.arange(6).reshape((3,2))
print(B)
'''[[0 1]
 [2 3]
 [4 5]]
 '''
print(A.dot(B))
print(np.dot(A,B))
'''[[10 13]
 [28 40]
 [46 67]]
 '''
  • trace : sum on the diagonal
A = np.arange(9).reshape((3,3))
print(A)
'''[[0 1 2]
 [3 4 5]
 [6 7 8]]
 '''
print(A.trace())
print(np.trace(A))
'''12'''
  • det : determinant
x = np.mat('3 4;2 2')
print(x)
'''[[3 4]
 [2 2]]
 '''
print(np.linalg.det(x))
'''-2'''
  • eigvals, eig : compute eigenvalues ​​and eigenvectors

Note: The eigenvalue is the root of the equation Ax = ax, which is a scalar. where A is a two-dimensional matrix and x is a one-dimensional vector. An eigenvector is a vector of eigenvalues

The function eigvals can calculate the eigenvalues ​​of a matrix, and the eig function can return a tuple containing the eigenvalues ​​and the corresponding eigenvectors

C = np.mat('3 -2;1 0')
# 调用eigvals函数求解特征值
e0 = np.linalg.eigvals(C)
print(e0)
'''[2. 1.]'''
# 使用 eig 函数求解特征值和特征向量,第一列为特征值,第二列为特征向量
e1,e2 = np.linalg.eig(C)
print(e1)
'''[2. 1.]'''
print(e2)
'''[[0.89442719 0.70710678]
 [0.4472136  0.70710678]]
 '''
# 检查结果
for i in range(len(e1)):
    print("left:", np.dot(C, e2[:, i]))
    print("right:", e1[i] * e2[:, i])
'''
left: [[1.78885438]
 [0.89442719]]
right: [[1.78885438]
 [0.89442719]]
left: [[0.70710678]
 [0.70710678]]
right: [[0.70710678]
 [0.70710678]]
 '''
  • inv : the inverse of a square matrix
A = np.mat('0 1 2;1 0 3;4 -3 8')
print(A)
'''
[[ 0  1  2]
 [ 1  0  3]
 [ 4 -3  8]]
 '''
# 使用inv函数计算逆矩阵
inv = np.linalg.inv(A)
print(inv)
'''
[[-4.5  7.  -1.5]
 [-2.   4.  -1. ]
 [ 1.5 -2.   0.5]]
 '''
# 检查结果
print(inv * A)
'''
[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]
 '''
  • pinv : generalized inverse matrix
A = np.mat('1 2;4 3')
print(A)
'''
[[1 2]
 [4 3]]
 '''
pseudoinv = np.linalg.pinv(A)
print(pseudoinv)
'''
[[-0.6  0.4]
 [ 0.8 -0.2]]
 '''
  • svd : singular decomposition

SVD (Singular Value Decomposition, Singular Value Decomposition) is a factorization operation that decomposes a matrix into the product of 3 matrices. The
function svd can perform singular value decomposition on a matrix. The function returns 3 matrices – U, Sigma and V, where U and V are orthogonal matrices and Sigma contains the singular values ​​of the input matrix

A = np.mat('4 11 14;8 7 -2')
print(A)
'''
[[ 4 11 14]
 [ 8  7 -2]]
 '''
# 调用svd函数分解矩阵
U,Sigma,V = np.linalg.svd(A, full_matrices=False)
print('U:{}{}Sigma:{}{}V:{}{}'.format(U,'\n',Sigma,'\n',V,'\n'))
'''
U:[[-0.9486833  -0.31622777]
 [-0.31622777  0.9486833 ]]
Sigma:[18.97366596  9.48683298]
V:[[-0.33333333 -0.66666667 -0.66666667]
 [ 0.66666667  0.33333333 -0.66666667]]
 '''
# 检查结果
print(U * np.diag(Sigma) * V)
'''
[[ 4. 11. 14.]
 [ 8.  7. -2.]]
 '''
  • solve : solve a system of linear equations

solve can solve linear equations of the form Ax = b, where A is a matrix, b is a one- or two-dimensional array, and x is an unknown variable

B = np.mat('1 -2 1;0 2 -8;-4 5 9')
print(B)
'''
[[ 1 -2  1]
 [ 0  2 -8]
 [-4  5  9]]
 '''
b = np.array([0, 2, 2])
x = np.linalg.solve(B, b)
print(x)
'''[37. 21.  5.]'''
# 检查结果
print(B.dot(x))
'''[[0. 2. 2.]]'''
'''和b相等'''
  • QR Decomposition
    For an m×n column full rank matrix A, there must be:

               Am*n= Qm*n·Rn*n
    

    Among them, QT·Q=I (that is, Q is an orthogonal matrix), and R is a non-singular upper triangular matrix (that is, the elements below the diagonal of matrix R are all 0).

    This process of decomposing A into such matrices Q and R is QR decomposition.

    where the decomposition is unique when the diagonal elements of R are required to be positive.

    QR decomposition can be used to solve problems such as the eigenvalues ​​of matrix A and the inverse of A.

# QR分解
A = np.array([[1,2,3,4,0],[-1,3,np.sqrt(2),3,0],[-2,2,np.e,np.pi,0],[-np.sqrt(10),2,-3,7,0],[0,2,7,5/2,0]],dtype=float)
print(A)
'''
[[ 1.          2.          3.          4.          0.        ]
 [-1.          3.          1.41421356  3.          0.        ]
 [-2.          2.          2.71828183  3.14159265  0.        ]
 [-3.16227766  2.         -3.          7.          0.        ]
 [ 0.          2.          7.          2.5         0.        ]]
 '''
A = np.matrix(A,dtype=float)
Q,R = np.linalg.qr(A)
# 验证
print(Q*R)
'''
[[ 1.          2.          3.          4.          0.        ]
 [-1.          3.          1.41421356  3.          0.        ]
 [-2.          2.          2.71828183  3.14159265  0.        ]
 [-3.16227766  2.         -3.          7.          0.        ]
 [ 0.          2.          7.          2.5         0.        ]]
 '''

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325697869&siteId=291194637