用numpy的eigh和svd计算的特征向量不匹配

2024-09-27 07:26:13 发布

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

考虑奇异值分解M=USV*。然后M*M的特征值分解得到M*M=V(S*S)V*=VS*U*USV*。我希望通过展示eigh函数返回的特征向量与svd函数返回的特征向量相同,来验证这个等式:

import numpy as np
np.random.seed(42)
# create mean centered data
A=np.random.randn(50,20)
M= A-np.array(A.mean(0),ndmin=2)

# svd
U1,S1,V1=np.linalg.svd(M) 
S1=np.square(S1)
V1=V1.T  

# eig
S2,V2=np.linalg.eigh(np.dot(M.T,M))
indx=np.argsort(S2)[::-1]
S2=S2[indx]
V2=V2[:,indx]

# both Vs are in orthonormal form
assert np.all(np.isclose(np.linalg.norm(V1,axis=1), np.ones(V1.shape[0])))
assert np.all(np.isclose(np.linalg.norm(V1,axis=0), np.ones(V1.shape[1])))
assert np.all(np.isclose(np.linalg.norm(V2,axis=1), np.ones(V2.shape[0])))
assert np.all(np.isclose(np.linalg.norm(V2,axis=0), np.ones(V2.shape[1])))

assert np.all(np.isclose(S1,S2))
assert np.all(np.isclose(V1,V2))

最后一个断言失败。为什么?在


Tags: normnponesassertallv2svdv1
1条回答
网友
1楼 · 发布于 2024-09-27 07:26:13

用小数字来调试你的问题。在

A=np.random.randn(3,2)开始,而不是更大的矩阵(50,20)

在我的随机案例中,我发现

v1 = array([[-0.33872745,  0.94088454],
   [-0.94088454, -0.33872745]])

对于v2

^{pr2}$

它们只对符号不同,很明显,即使规范化为有单位模,向量对于符号也可能不同。在

现在如果你试试这个把戏

assert np.all(np.isclose(V1,-1*V2))

对于你最初的大矩阵,它失败了。。。再说一遍,这没关系。结果是有些向量被-1相乘,有些则没有

检查矢量之间是否相等的正确方法是:

assert allclose(abs((V1*V2).sum(0)),1.)

实际上,要想了解它是如何工作的,你可以打印这个数量:

(V1*V2).sum(0)

这实际上是+1或{},取决于载体:

array([ 1., -1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,
    1., -1.,  1.,  1.,  1., -1., -1.])

编辑:这在大多数情况下都会发生,尤其是从随机矩阵开始。但是请注意,如果一个或多个特征值的本征空间的维数大于1,正如@Sven Marnach在下面的评论中指出的那样,这个测试可能会失败:

There might be other differences than just vectors multiplied by -1. If any of the eigenvalues has a multi-dimensional eigenspace, you might get an arbitrary orthonormal basis of that eigenspace, and to such bases might be rotated against each other by an arbitraty unitarian matrix

相关问题 更多 >

    热门问题