人脸特征降维

#特征降维
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()
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值