使用sklearn提取PCA组件

2024-05-12 18:29:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用sklearn's PCA对一组大图像进行降维。一旦PCA安装好,我想看看组件是什么样子的。

可以通过查看components_属性来实现。没有意识到这一点,我做了别的事情:

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空间中创建了一个图像,该图像的所有特征都设置为0,只有1个。通过对它们进行逆变换,我就可以得到原始空间中的图像,一旦变换,就可以用主成分分析的成分来表示。

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

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

left: calculated component, right: real component


Tags: 方法图像空间components组件sklearnarraycomponent
2条回答

分量和逆变换是两个不同的东西。逆变换将组件映射回原始图像空间

#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

因此,您是对原始数据而不是组件进行反向转换,因此它们完全不同。你几乎从不反变换原始数据。pca.components是表示用于将数据投影到pca空间的基础轴的实际向量。

抓取components_和对恒等矩阵执行inverse_transform之间的区别在于后者添加了每个特征的经验平均值。一、 e.:

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

其中self.mean_是根据训练集估计的。

相关问题 更多 >