如何关联哪个单数值对应哪个条目?

2024-06-16 09:49:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我用numpy-linalg程序lstsq来解方程组。我的A矩阵的大小是(11046504),而我的B矩阵是大小(11046,1),并且确定的秩是249,所以大约一半的x数组的解算不是特别有用。我想用奇异值的s数组来归零对应于奇异值的参数的解,但是s数组似乎是按统计显著性递减的顺序排序的。有没有一种方法可以计算出x中的哪个对应于每个单数s?在


Tags: 方法程序numpy参数排序顺序矩阵数组
1条回答
网友
1楼 · 发布于 2024-06-16 09:49:31

为了得到由numpy.linalg.lstsq给出的方程Mb = x的最小二乘解,还可以使用^{},它计算奇异值分解{}。最佳解x给出为x = V Sp U* b,其中Sp是{}的伪逆。给定矩阵UV*(包含矩阵M的左右奇异向量)和奇异值{},可以计算向量{}。现在,带有i > rank(M)z的所有组分z_i可以在不改变解的情况下任意选择,因此,z_i中不包含的x_j也可以。在

下面是一个示例,演示如何使用singluar value decomposition上的Wikipedia条目中的示例数据获取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)

相关问题 更多 >