关于python:使用sklearn提取PCA组件

Extracting PCA components with sklearn

我正在使用sklearn的PCA来减少大量图像的尺寸。安装PCA后,我想看看这些组件的外观。

可以通过查看components_属性来实现。没有意识到那是可用的,我做了其他事情:

1
2
3
4
5
6
each_component = np.eye(total_components)
component_im_array = pca.inverse_transform(each_component)

for i in range(num_components):
   component_im = component_im_array[i, :].reshape(height, width)
   # do something with component_im

换句话说,我在PCA空间中创建了一个图像,该图像除了1设置为0以外,还具有所有功能。通过逆变换它们,我应该在原始空间中获得图像,一旦转换,就可以用该PCA组件单独表达该图像。 。

下图显示了结果。左边是使用我的方法计算的分量。右边是直接pca.components_[i]。另外,使用我的方法,大多数图像非常相似(但是它们是不同的),而通过访问components_,图像则与我期望的非常不同

我的方法有概念上的问题吗?显然,pca.components_[i]中的组件比我得到的组件正确(或至少更正确)。谢谢!

left: calculated component, right: real component


分量和逆变换是两件事。 逆变换将分量映射回原始图像空间

1
2
3
4
5
6
7
8
9
#Create a PCA model with two principal components
pca = PCA(2)
pca.fit(data)
#Get the components from transforming the original data.
scores = pca.transform(data)
# Reconstruct from the 2 dimensional scores
reconstruct = pca.inverse_transform(scores )
#The residual is the amount not explained by the first two components
residual=data-reconstruct

因此,您要对原始数据而非组件进行逆变换,因此它们是完全不同的。 您几乎永远不会对原始数据进行inverse_transform转换。 pca.components_是代表用于将数据投影到pca空间的基础轴的实际矢量。


在单位矩阵上获取components_和执行inverse_transform之间的区别在于,后者将每个特征的经验均值相加。 即:

1
2
def inverse_transform(self, X):
    return np.dot(X, self.components_) + self.mean_

其中self.mean_是从训练集中估算的。