如何在Python中使用SVD求矩阵的一般逆?

问题描述 投票:0回答:1

所以我试图使用 svd 找到矩阵 A 的广义逆 A+

这是我的 svd 代码

A4 = np.array([[3, 1,2,3,4],
               [5,2,3,4,5],
               [7,4,5,6,7]])
print(A4)
U4, s4, V4 = np.linalg.svd(A4)
D4 = sp.linalg.diagsvd(s4, 3, 5)

print('UDVt =\n', U4@D4@V4 )

它工作得很好并且给了我正确的矩阵

这是我试图用来获得广义逆的代码

D4p = np.array([[D4[0,0]**-1,0,0],
                [0,D4[1,1]**-1,0],
                [0,0,D4[2,2]**-1],
                [0,0,0],
                [0,0,0]])
A4plus = np.transpose(V4) @ D4p @ np.transpose(U4) 
print(np.round(A4plus @ A4,2))
print(np.round(A4 @ A4plus,2))

我尝试过更改转置矩阵。

python numpy scipy svd
1个回答
0
投票

假设行不是线性相关的(否则 S 矩阵的元素值为 0,我无法反转它们),你可以说

   U * S * Vt = A
=> A * (Vt.T * 1/S * U.T) = I

代码中:

from numpy import array, round
from numpy.linalg import svd
from scipy.linalg import diagsvd

A = array([[3, 1, 2, 3, 4],
           [5, 2, 3, 4, 5],
           [7, 4, 5, 6, 7]])

U, S, Vt = svd(A)

S_inv = diagsvd(1/S, A.shape[1], A.shape[0])
A_inv = Vt.T @ S_inv @ U.T

print(round(A @ A_inv, 5))

这给出了 A 的伪逆

[[ 1.  0. -0.]  [ 0.  1.  0.]  [-0. -0.  1.]]

这是关于此的相关段落: https://inst.eecs.berkeley.edu/~ee127/sp21/livebook/def_pseudo_inv.html

© www.soinside.com 2019 - 2024. All rights reserved.