Python 主成分分析中的负特征值
我有一个矩阵Python 主成分分析中的负特征值,python,machine-learning,pca,eigenvalue,dimensionality-reduction,Python,Machine Learning,Pca,Eigenvalue,Dimensionality Reduction,我有一个矩阵x(1000*25),它包含区间(-5,5)中的随机浮点数nFeatures=25和nPoints=1000。我用这个代码来求协方差矩阵的特征值,但得到的是负特征值 #centering the data for i in range(0,nFeatures): sum=0 for j in range(0,nPoints): sum+=x[j][i] for j in range(0,nPoints): x[j][i]-=su
x(1000*25)
,它包含区间(-5,5)
中的随机浮点数<代码>nFeatures=25和nPoints=1000
。我用这个代码来求协方差矩阵的特征值,但得到的是负特征值
#centering the data
for i in range(0,nFeatures):
sum=0
for j in range(0,nPoints):
sum+=x[j][i]
for j in range(0,nPoints):
x[j][i]-=sum/nPoints
#covariance matrix and its eigenvalues & eigenvectors
c=np.dot(x.T,x)
eValue,eVector=np.linalg.eig(c)
print(eValue)
我得到的输出是:
[ 1.47374029e+02 8.84275505e-13 -8.01150077e-13 -6.77987718e-13
5.19228948e-13 -4.01775609e-13 -3.55055652e-13 3.55433578e-13
-2.54817200e-13 2.51137659e-13 2.23836773e-13 1.77611044e-13
1.57643867e-13 -1.34409360e-13 1.04358065e-13 -9.31186264e-14
-8.05736392e-14 -5.69664362e-14 4.39721071e-14 3.59268864e-14
-2.84466680e-14 2.42670536e-14 2.30979465e-15 -7.18313504e-15
-9.35335475e-15]
因为协方差矩阵是半正定矩阵,所以特征值不应该是负的。请帮我找出我做错了什么
另外,我读了一篇博文,没有,我的数据集中没有缺失值。这绝对不是你正在计算的协方差矩阵,因为你的运算中没有乘积,只有和。怎么样:
sum+=x[j][i]*x[i][j]
?@ma3oun我没有用sum
来计算协方差矩阵。我用它来集中关于原点的数据。我用点积,dot(x.T,x)
来计算cov矩阵。你的特征值非常接近于0(除了第一个)。我认为这是由于数值不精确(这可能来自循环中使用的累积)。应该考虑使用它们的绝对值裁剪值。尝试使用np用numpy操作替换定心环。average@ma3oun我一小时后试试,然后告诉你。谢谢哦,非常感谢@ma3oun,它真的很有帮助!:D