解决SVD分解的Python程序

2024-09-26 22:49:27 发布

您现在位置: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
>>>

Tags: 代码infromimportnumpy利用line矩阵
1条回答
网友
1楼 · 发布于 2024-09-26 22:49:27

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

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

当你的U.T*b矩阵是3x1时:

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

你不能把它们相乘。你知道吗

相关问题 更多 >

    热门问题