Skip to content

Instantly share code, notes, and snippets.

@3100
Last active Aug 29, 2015
Embed
What would you like to do?
主成分分析でn次元に縮小させた結果から画像を復元してみる
from sklearn.decomposition import PCA
from PIL import Image
import numpy as np
import scipy as sp
if __name__ == '__main__':
# 画像ファイル名に変えてください
filePath = 'gs.jpg'
# 試行するnの組(画像ピクセルサイズの最大数を超えないこと)
ns = [1,2,5,10,50,100,250]
imgAry = np.asarray(Image.open(filePath).convert('L'))
for n in ns:
pca = PCA(n_components=n)
pca.fit(imgAry)
pca_res = pca.transform(imgAry)
restored = pca.inverse_transform(pca_res)
print sum(pca.explained_variance_ratio_)
sp.misc.imsave('result' + str(n) + '.png', restored)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment