Gre*_*ssy 5 python numpy matrix linear-algebra least-squares
我正在使用 numpy linalg 例程 lstsq 来求解方程组。我的 A 矩阵的大小为 (11046, 504),而我的 B 矩阵的大小为 (11046, 1),确定的秩为 249,因此解决的 x 数组的大约一半并不是特别有用。我想使用奇异值的 s 数组将与奇异值对应的参数的求解结果归零,但似乎 s 数组是按统计显着性递减的顺序排序的。有没有办法可以找出我的哪个 x 对应于每个奇异值 s?
Mb = x要获得给定方程的最小二乘解numpy.linalg.lstsq,您还可以使用numpy.linalg.svd来计算奇异值分解M= U S V*。最佳解x给出为x = V Sp U* b,其中Sp是 的伪逆S。给定矩阵U和V*(包含矩阵 的左奇异向量和右奇异M向量)和奇异值s,您可以计算向量z=V*x。现在, withz_i的所有分量都可以任意选择,而无需改变解,因此for中未包含的所有分量也可以选择。zi > rank(M)x_jz_ii <= rank(M)
下面的示例演示了如何使用维基百科奇异值分解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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1962 次 |
| 最近记录: |