如何在PCA之后从Python中的第一个组件重建图像?

问题描述 投票:1回答:1

如何在PCA之后从Python中的第一个组件重构图像?

我的尝试:

from sklearn.datasets import load_sample_image
from sklearn.feature_extraction import image
from sklearn.decomposition import PCA
# Create patches of size 25 by 25 and create a matrix from all patches
patches = image.extract_patches_2d(grayscale_image, (25, 25), random_state = 42)
#reshape patches
patches_reshaped = patches.reshape(patches.shape[0],-1)
# PCA
pca = PCA(n_components = 3,random_state = 42)
pca.fit(patches_reshaped)
first_component = pca.components_[0] #first component
# attempt to reconstruct image from first component
plt.imshow(pca.components_[0].reshape(25, 25),"gray")
python pca
1个回答
0
投票

您已将n_components = 3传递给PCA,这意味着您将具有三个主要组成部分。因此,当您这样做时,

projected = pca.fit_transform(patches_reshaped.data)

您将在三个3个主轴上投影数据,这意味着您的输出将为(patches.shape[0], 3)形状。

现在要使用第一个主成分进行重构,您要做的是获取数据在该轴上的投影,并从该轴进行逆变换到原始域。为此,请首先获取第一个主成分:

# First get your first component
first_component = pca.components_[0]
# Make sure your first component is a row vector
first_component = first_component.reshape(1,-1) 

然后,逆变换不过是projected_data * principal_components。有关更多详细信息,请查看文档here和源代码here

# get the first projection 
first_proj = projected[:,0]
# Make sure your first component is a column vector
first_proj = first_proj.reshape(-1,1)
# do inverse transform (No you have to add the mean as thse algorithm 
# works on zero mean data) 
recon_using_first_comp = np.dot(proj, first_component) + pca.mean_

然后重建补丁以获得最终图像

final_img = image.reconstruct_from_patches_2d(recon_using_first_comp.reshape(-1,25,25), grayscale_image.shape)
© www.soinside.com 2019 - 2024. All rights reserved.