#特征降维
from time import time
from numpy.random import RandomState
import matplotlib.pyplot as plt
from sklearn.datasets import fetch_olivetti_faces
from sklearn import decomposition
from sklearn.cluster import MiniBatchKMeans
n_row, n_col = 2, 3
n_components = n_row * n_col
image_shape= (64, 64)
rng = RandomState(0)
#########################################################
faces,_= fetch_olivetti_faces(return_X_y=True,shuffle=True,random_state=rng)#获取数据fetch_olivetti_faces()
n_samples, n_features = faces.shape
faces_centered = faces - faces.mean(axis=0)
print(len(faces_centered))
#加载centering
faces_centered -= faces_centered.mean(axis=1).reshape(n_samples,-1)
def plot_gallery(titles,images,n_row=n_row, n_col=n_col,cmap=plt.cm.gray):#显示图片画廊
"""Helper function to plot a gallery of portraits"""
plt.figure(figsize=(2.4 * n_col, 2.6 * n_row))
plt.suptitle(titles,size=18)
for i,comp in enumerate(images):
plt.subplot(n_row, n_col, i + 1)
"""Helper function to plot a gallery of portraits"""
vmax = max(comp.max(),-comp.min())
plt.imshow(comp.reshape(image_shape),cmap=cmap,interpolation='nearest',vmin=-vmax,vmax=vmax)#显示图片显示图片
plt.xticks(())
plt.yticks(())
plt.subplots_adjust(0.01,0.05,0.99,0.93,0.04,0.)#调整图片显示位置显示图片
#不同的估计器列表
estimators = [
('Principal Components',decomposition.PCA(n_components=n_components,svd_solver="randomized",whiten=True),True),
('NMF',decomposition.NMF(n_components=n_components,init='nndsvda',tol=5e-3),False),
('FastICA',decomposition.FastICA(n_components=n_components,whiten='arbitrary-variance',tol=0.01, max_iter=1000),True),
# ('MinBatchSparsePCA',decomposition.MiniBatchSparsePCA(n_components=n_components,alpha=0.8,batch_size=3,random_state=rng),True),
]
####################################################################################################################
#绘制输入数据样本
plot_gallery('Original data',faces_centered[:n_components])
#绘制不同的估计器
for name,estimators,center in estimators:
print("Extracting the top %s %s..." % (n_components,name))
t0 = time()
data =faces
if center:
data = faces_centered
estimators.fit(data)
train_time = (time() - t0)
print("done in %0.3fs" % train_time)
if hasattr(estimators,'cluster_centers_'):
components = estimators.cluster_centers_
else:
components_ = estimators.components_
#绘制由估计器提供的像素方差图像,如果是标量则被跳过
if (hasattr(estimators,'noise_variance_') and estimators.noise_variance_ > 0):
pass
plot_gallery("%s-Train time %.1fs" % (name,train_time),components_[:n_components])
plt.show()
人脸特征降维
最新推荐文章于 2024-06-28 09:48:33 发布