如何将哪个奇异值与哪个条目相对应?

时间:2013-08-26 20:39:20

标签: python numpy matrix linear-algebra least-squares

我正在使用numpy linalg例程lstsq来解决方程组。我的A矩阵的大小为(11046,504),而我的B矩阵是大小(11046,1),并且确定的等级是249,因此对于x阵列求解的大约一半并不特别有用。我想使用s奇异值数组将求解的参数与奇异值相对应,但似乎s数组按统计显着性递减的顺序排序。有没有办法可以弄清楚我的哪个x对应于每个奇异值s?

1 个答案:

答案 0 :(得分:2)

要获得Mb = x给出的等式numpy.linalg.lstsq的最小二乘解,您还可以使用numpy.linalg.svd来计算奇异值分解M= U S V*。然后,最佳解决方案x将以x = V Sp U* b的形式给出,其中SpS的伪逆。给定矩阵UV*(包含矩阵M的左右奇异向量)和奇异值s,您可以计算向量{{ 1}}。现在,可以在不更改解决方案的情况下任意选择z=V*x z_i z的所有组件i > rank(M),因此x_j中不包含所有组件z_i i <= rank(M)

以下是一个示例,演示如何使用singluar value decomposition上维基百科条目中的示例数据获取x的重要组件:

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)