如何在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")
您已经将
n_components = 3
传递给PCA
,这意味着您将有三个主成分。所以当你这么做的时候您将得到投影在3个主轴上的数据,这意味着您的输出将是形状
(patches.shape[0], 3)
。你知道吗现在要用第一个主分量来重建,你要做的是得到数据在这个主轴上的投影,然后做一个到原始域的逆变换。为此,首先得到第一个主成分:
那么,逆变换就是
projected_data * principal_components
。有关更多详细信息,您可以查看文档here和源代码here。你知道吗然后重建补丁得到你的最终图像
相关问题 更多 >
编程相关推荐