解决SVD Decompostion的Python程序

时间:2015-11-12 16:42:37

标签: python

使用python通过SVD分解求解矩阵。我的代码不起作用,它说矩阵没有对齐

>>> from numpy import*
>>> from numpy.linalg import qr
>>> A = mat([[1.,2.],[4.,5.],[7.,8.]])
>>> U,s,V =linalg.svd(A)
>>> S = diag(s)
>>> print U
[[-0.17259857  0.89640564  0.40824829]
 [-0.50818671  0.27400657 -0.81649658]
 [-0.84377485 -0.3483925   0.40824829]]
>>> print S
[[ 12.59601718   0.        ]
 [  0.           0.58339625]]
>>> print V
[[-0.64399479 -0.76502988]
 [-0.76502988  0.64399479]]
>>> b = mat([3.,6.,10.]).reshape(3,1)
>>> x = V.T*(diag(1/s)*(U.T*b))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/dist-packages/numpy/matrixlib/defmatrix.py", line 347, in __rmul__
    return N.dot(other, self)
ValueError: matrices are not aligned
>>>

1 个答案:

答案 0 :(得分:0)

您的diag(1/s)矩阵是2x2:

array([[ 0.07939017,  0.        ],
       [ 0.        ,  1.71410083]])

虽然您的U.T*b矩阵是3x1:

matrix([[-12.00466449],
        [  0.84933136],
        [  0.40824829]])

你不能将这两者相乘。