我正在尝试使用n_components = 5
从sklearn
进行PCA
。我使用fit_transform(data)
对数据进行缩小。
最初,我尝试在pca.components_
值和我的x_features
数据之间进行经典的矩阵乘法,但结果是不同的。因此,我不正确地进行乘法或不了解fit_transform
的工作方式。
以下是比较经典矩阵乘法和fit_transform
的模型:
import numpy as np
from sklearn import decomposition
np.random.seed(0)
my_matrix = np.random.randn(100, 5)`
mdl = decomposition.PCA(n_components=5)
mdl_FitTrans = mdl.fit_transform(my_matrix)
pca_components = mdl.components_
mdl_FitTrans_manual = np.dot(pca_components, my_matrix.transpose())
mdl_FitTrans_manualT = mdl_FitTrans_manual.transpose()
我期望mdl_FitTrans == mdl_FitTrans_manual
,但结果是False
。
查看,如何在Sklearn中实现transform()
方法:https://github.com/scikit-learn/scikit-learn/scikit-learn/scikit-learn/blob/a5ab948/sklearn/sklearn/sklearn/decomposition/baseosition.pypy.pypy.pypy.py#l101
根据它,手动减少如下:
import numpy as np
from sklearn import decomposition
np.random.seed(0)
data = np.random.randn(100, 100)
mdl = decomposition.PCA(n_components=5)
mdl_fit = mdl.fit(data)
data_transformed = mdl_fit.transform(data)
data_transformed_manual = np.dot(data - mdl_fit.mean_, mdl.components_.T)
np.all(data_transformed == data_transformed_manual)
True