import numpy as np
M = np.array([[1,0,0,0,2],[0,0,3,0,0],[0,0,0,0,0],[0,4,0,0,0]])
#We perform singular-value decomposition of M
U, s, V = np.linalg.svd(M)
S = np.zeros(M.shape,dtype = np.float64)
b = np.array([1,2,3,4])
m = min(M.shape)
#We generate the matrix S (Sigma) from the singular values s
S[:m,:m] = np.diag(s)
#We calculate the pseudo-inverse of S
Sp = S.copy()
for m in range(0,m):
Sp[m,m] = 1.0/Sp[m,m] if Sp[m,m] != 0 else 0
Sp = np.transpose(Sp)
Us = np.matrix(U).getH()
Vs = np.matrix(V).getH()
print "U:\n",U
print "V:\n",V
print "S:\n",S
print "U*:\n",Us
print "V*:\n",Vs
print "Sp:\n",Sp
#We obtain the solution to M*x = b using the singular-value decomposition of the matrix
print "numpy.linalg.svd solution:",np.dot(np.dot(np.dot(Vs,Sp),Us),b)
#This will print:
#numpy.linalg.svd solution: [[ 0.2 1. 0.66666667 0. 0.4 ]]
#We compare the solution to np.linalg.lstsq
x,residuals,rank,s = np.linalg.lstsq(M,b)
print "numpy.linalg.lstsq solution:",x
#This will print:
#numpy.linalg.lstsq solution: [ 0.2 1. 0.66666667 0. 0.4 ]
#We determine the significant (i.e. non-arbitrary) components of x
Vs_significant = Vs[np.nonzero(s)]
print "Significant variables:",np.nonzero(np.sum(np.abs(Vs_significant),axis = 0))[1]
#This will print:
#Significant variables: [[0 1 2 4]]
#(i.e. x_3 can be chosen arbitrarily without altering the result)
为了得到由} ,它计算奇异值分解{}。最佳解}的伪逆。给定矩阵},可以计算向量{}。现在,带有
numpy.linalg.lstsq
给出的方程Mb = x
的最小二乘解,还可以使用^{x
给出为x = V Sp U* b
,其中Sp
是{U
和V*
(包含矩阵M
的左右奇异向量)和奇异值{i > rank(M)
的z
的所有组分z_i
可以在不改变解的情况下任意选择,因此,z_i
中不包含的x_j
也可以。在下面是一个示例,演示如何使用singluar value decomposition上的Wikipedia条目中的示例数据获取
x
的重要组件:相关问题 更多 >
编程相关推荐