我有一个线性回归问题,(Ax=b)。我最初帮助解决一些问题的方法是使用、SVD、和获取我感兴趣的卡方值和其他一些值,但在某些情况下,例如,如果我的回归问题如下:
>>> coff=
array([[ 1., 0., 0., 0.],
[ 0., 0., -1., 0.],
[ 1., 0., 0., 0.],
[ 0., 0., 0., -1.],
[ 1., 0., -1., 0.],
[ 0., 0., 1., -1.],
[ 0., 0., -1., 0.],
[ 0., 0., 1., -1.]])coff矩阵实际上是A矩阵,回归问题中的b是这样的:
>>> b
array([-0.56168673, 0.8943901 , -0.56168673, 1.20952994, 0.33270337,
0.31513984, 0.8943901 , 0.31513984])使用奇异值分解法:
print "==============================SVD calculation============================"
U, s, Vh = linalg.svd(coff, full_matrices=False)
print U.shape, Vh.shape, s.shape
print s
S = scipy.linalg.diagsvd(s, 4, 4)
print allclose(coff, dot(U, dot(S, Vh)))
Sh=scipy.linalg.inv(S)
for i in range(Sh.shape[0]):
if Sh[i,i]>1.0e+04 :
Sh[i,i]=0
Uh = scipy.transpose(U)
V= scipy.transpose(Vh)
aa=dot(V, dot(Sh, Uh))
aah= scipy.transpose(aa)
S_sq=dot(Sh,Sh)
V_sq=dot(V,Vh)
covar=dot(S_sq,V_sq)
#The least square problem results
res=dot(aa,b)
wt=zeros(s.shape[0],float)
for i in range(s.shape[0]):
wt[i]=0
if math.fabs(s[i])>1.0e-04:
wt[i]=1./(s[i]*s[i])
cvm=zeros((s.shape[0],s.shape[0]),float)
for i in range(s.shape[0]):
j=0
while j<=i:
cum=0.0
for k in range(s.shape[0]):
cum=cum+Vh[i,k]*Vh[j,k]*wt[k]
cvm[i,j]=cum
cvm[j,i]=cum
j+=1
print "SVD results for seventeen filters:\n",res
print "SVD's covariance matrix:\n",cvm
sig=zeros(cvm.shape[0],float)
for i in range(cvm.shape[0]):
for j in range(cvm.shape[1]):
if i==j:
sig[i]=math.sqrt(cvm[i,j])
print 'Variance:\n',sig
chi_square=0
v=dot(coff,res)
for i in range(b.shape[0]):
chi_square += (b[i]-v[i])**2
print "chi_square:\n",chi_square
reduce_chi=chi_square/(coff.shape[0]-coff.shape[1]-1)
print "Reduced-Chisquare:\n",reduce_chi好吧,我的方法不是优化方法,但我需要看到,例如,Reduced-Chisquare或covariance的值是多少,但是当我试图逆S矩阵时,它会引起奇异矩阵误差,但是如果我使用以下步骤:
Least_squares,residuals,rank,Singular_values=np.linalg.lstsq(coff, b)它没有给我任何错误和计算回归问题。我的问题
首先:为什么使用SVD会出现这个问题?
第二个(非常编程的问题):如果在第一个方法中出现一个错误,我如何保留第一个方法并使用第二个方法?
发布于 2014-09-05 14:37:50
我可以回答第二个问题,一种方法是使用try,除了:) Use:
try:
first_option blabla
except:
second_option您甚至可以限制奇异矩阵误差(https://docs.python.org/2/tutorial/errors.html;这是误差numpy.linalg.linalg.LinAlgError)的例外?
我现在看一下代码,看看是否能回答第一个:)
https://stackoverflow.com/questions/25688139
复制相似问题