当第一种方法产生线性回归的错误信息时,在不同方法之间进行选择

2024-05-16 06:18:48 发布

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

我有一个线性回归问题(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-Chisquarecovariance的值是多少,但是当我试图求逆S矩阵时,它会产生奇异矩阵错误,但是如果我使用以下过程:

Least_squares,residuals,rank,Singular_values=np.linalg.lstsq(coff, b)

它不会给我任何误差,也不会计算回归问题。 我的问题:

首先:为什么使用SVD会出现此问题?你知道吗

Second(非常编程的问题):我怎样才能保留第一种方法并使用第二种方法,以防第一种方法中出现一个错误?你知道吗


Tags: 方法inforshrangescipydotsvd
1条回答
网友
1楼 · 发布于 2024-05-16 06:18:48

我可以回答第二个问题,一种方法是使用try and except:)使用:

try:
     first_option blabla
except:
     second_option

您甚至可以限制,除了那个奇异矩阵错误(https://docs.python.org/2/tutorial/errors.html;是这个错误吗numpy.linalg.linalg公司(错误?)你知道吗

我现在看一下代码,看看能否回答第一个问题:)

相关问题 更多 >