简体   繁体   English

numpy 和 sklearn PCA 返回不同的协方差向量

[英]numpy and sklearn PCA return different covariance vector

Trying to learn PCA through and through but interestingly enough when I use numpy and sklearn I get different covariance matrix results.试图彻底学习 PCA 但有趣的是,当我使用 numpy 和 sklearn 时,我得到了不同的协方差矩阵结果。

The numpy results match this explanatory text here but the sklearn results different from both. numpy 结果与此处的解释性文本相匹配但 sklearn 的结果与两者不同。

Is there any reason why this is so?有什么原因吗?

d = pd.read_csv("example.txt", header=None, sep = " ")
print(d)
      0     1
0  0.69  0.49
1 -1.31 -1.21
2  0.39  0.99
3  0.09  0.29
4  1.29  1.09
5  0.49  0.79
6  0.19 -0.31
7 -0.81 -0.81
8 -0.31 -0.31
9 -0.71 -1.01

Numpy Results Numpy 结果

print(np.cov(d, rowvar = 0))
[[ 0.61655556  0.61544444]
 [ 0.61544444  0.71655556]]

sklearn Results sklearn 结果

from sklearn.decomposition import PCA
clf = PCA()
clf.fit(d.values)
print(clf.get_covariance())

[[ 0.5549  0.5539]
 [ 0.5539  0.6449]]

Because for np.cov , 因为对于np.cov

Default normalization is by (N - 1), where N is the number of observations given (unbiased estimate). 默认归一化为(N-1),其中N是给出的观察数(无偏估计)。 If bias is 1, then normalization is by N. 如果偏差为1,则归一化为N。

Set bias=1 , the result is the same as PCA : 设置bias=1 ,结果与PCA相同:

In [9]: np.cov(df, rowvar=0, bias=1)
Out[9]:
array([[ 0.5549,  0.5539],
       [ 0.5539,  0.6449]])

So I've encountered the same issue, and I think that it returns different values because the covariance is calculated in a different way.所以我遇到了同样的问题,我认为它返回不同的值,因为协方差的计算方式不同。 According to the sklearn documentation , the get_covariance() method, uses the noise variances to obtain the covariance matrix.根据sklearn 文档get_covariance()方法使用噪声方差来获得协方差矩阵。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM