我一直在用 scikit-learn 做 PCA。 然而,我刚刚知道以下两种方法给出了不同的结果:
from sklearn.decomposition import PCA
pca = PCA(n_components=0.95)
X_proj = pca.fit_transform(X) # << THIS AND
np.dot(X, pca.components_.T) # << THIS GIVE DIFFERENT RESULTS
这是为什么?
sklearn PCA 模块对输入数据进行了标准化。
我们以 MNIST 数据集为例。加载模块和数据集。
from sklearn.decomposition import PCA
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_digits
digits = load_digits()
加载第一个数据
X = digits.data[0].reshape(8,8)
plt.imshow(X)
plt.show()
使用主成分分析。
print(pca.fit_transform(X))
X -= np.mean(X, axis=0) # normalize
print(np.dot(X, pca.components_.T))
两个输出是相同的。
[[12.35977044 -4.83699252 -0.46662515]
[ 5.86229378 10.53312359 -3.75283451]
[-8.32285024 1.25214592 -1.06726234]
[-8.14946302 -3.13767167 -0.24623081]
[-7.7867473 -4.40094175 -1.06614822]
[-8.41834525 -0.27216078 0.35837631]
[ 1.49545914 5.65672511 6.04353692]
[12.95988243 -4.79422791 0.1971878 ]]
[[12.35977044 -4.83699252 -0.46662515]
[ 5.86229378 10.53312359 -3.75283451]
[-8.32285024 1.25214592 -1.06726234]
[-8.14946302 -3.13767167 -0.24623081]
[-7.7867473 -4.40094175 -1.06614822]
[-8.41834525 -0.27216078 0.35837631]
[ 1.49545914 5.65672511 6.04353692]
[12.95988243 -4.79422791 0.1971878 ]]