【问题标题】:Extracting PCA components with sklearn使用 sklearn 提取 PCA 组件
【发布时间】:2014-04-03 07:37:45
【问题描述】:

我正在使用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 空间中创建了一个图像,其中除了 1 之外的所有特征都设置为 0。通过对它们进行逆变换,我应该得到原始空间中的图像,一旦变换,就可以单独用那个 PCA 组件。

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

我的方法是否存在概念问题?显然来自pca.components_[i] 的组件比我得到的组件正确(或至少更正确)。谢谢!

【问题讨论】:

    标签: python scikit-learn pca


    【解决方案1】:

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

    #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 空间的基础轴的实际向量。

    【讨论】:

    • 感谢您的回答。也许我们有一个误解:我不是在对原始数据进行逆变换,而是一个除一个位置外全为零的向量。在这样做时,我希望我正在对图像 [0,0,...,0,1,0,...,0] 进行逆变换,该图像必须来自看起来像组件的原始图像
    【解决方案2】:

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

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

    self.mean_ 是从训练集中估计出来的。

    【讨论】:

    • 宾果游戏。不知道为什么不早点自己看源码。谢谢!但是,平均值在 PCA._fit(X) 中计算为 self.mean_ = np.mean(X, axis=0),其中 X 是 n_samples 行和 n_features 列的数组,因此平均值是每个特征的特征平均值,所以这是当然可能会主导组件实际具有的任何贡献,这就是所有图像看起来几乎相同的原因。全部解释清楚,谢谢!
    猜你喜欢
    • 2020-12-22
    • 2019-04-03
    • 2018-01-25
    • 2021-03-24
    • 2017-07-19
    • 2021-05-08
    • 2015-09-27
    • 1970-01-01
    • 2020-12-29
    相关资源
    最近更新 更多