1.介紹
2.代碼
import matplotlib.pyplot as plt
from numpy.random import RandomState
from sklearn.datasets import fetch_olivetti_faces
from sklearn import decomposition
#全局變量
n_row,n_col=2,3
n_components= n_row*n_col
image_shae=(64,64)
#######################################
#擷取資料并打亂順序
dataset=fetch_olivetti_faces(shuffle= True,random_state=RandomState(0))
# re=RandomState(0)
# print(re.rand(1,2))
faces=dataset.data
#######################################
#确定圖檔大小以及name
def plot_gallery(title,images,n_col=n_col,n_row=n_row):
plt.figure(figsize=(2.*n_col,2.26*n_row))
plt.suptitle(title,size=16)
for i, comp in enumerate(images):
plt.subplot(n_row,n_col,i+1) #六組特征資料以i+1的方式選擇子圖
vmax=max(comp.max(),-comp.min()) #資料波動絕對值,再max
plt.imshow(comp.reshape(image_shae),cmap=plt.cm.gray,
interpolation='nearest',vmin=-vmax,vmax=vmax)
#數值歸一化,double類型,(uint8 0-255) 以灰階顯示
plt.xticks(())#指定坐标軸刻度,旋轉角度rotation=0等操作
plt.yticks(())
plt.subplots_adjust(0.01, 0.05, 0.99, 0.94, 0.04, 0.)
#兩種方法對比
estimators=[
('Eigenfaces - PCA using randomized SVD',
decomposition.PCA(n_components=6,whiten=True)),
('Non-negative components - NMF',
decomposition.NMF(n_components=6,init='nndsvda',tol=5e-3))
]
#
for name, estimator in estimators:
print("Extracting the top %d %s..." % (n_components, name))
print(faces.shape)
estimator.fit(faces)#導資料fit
# print(faces)
components_ = estimator.components_ #投影方向向量
# print(estimator)
print(components_[:n_components]) #前六維資料
plot_gallery(name, components_[:n_components])
plt.show()
有幸有機會我能了解學習到其中些微知識原理,也很是開心;好比遊覽河山,越過曲水蜿蜒,感悟得到的不少,分享給你們~