Как восстановить изображение из первого компонента в Python после PCA? - PullRequest
2 голосов
/ 26 октября 2019

Как восстановить изображение из первого компонента в Python после PCA?

Моя попытка:

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")

1 Ответ

1 голос
/ 26 октября 2019

Вы передали n_components = 3 в PCA, что означает, что у вас будет три основных компонента. Поэтому, когда вы это сделаете,

projected = pca.fit_transform(patches_reshaped.data)

Ваши данные будут проецироваться по трем основным осям, что означает, что ваш вывод будет иметь форму (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. Для более подробной информации вы можете посмотреть документацию здесь и исходный код здесь .

# 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)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...