代码
# 1。导入相关包
import matplotlib.pyplot as plt
from sklearn import decomposition
from sklearn.datasets import fetch_olivetti_faces
from numpy.random import RandomState
# 加载RandomState用于创建随机种子
# 全局取消证书验证 (解决报错
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
# 2。设置基本参数并加载数据
n_row, n_col = 2, 3
# 设置图像展示时的排列情况,2行3列
n_components = n_col * n_row
# 设置提取的特征数目的大小
image_shape = (64, 64)
# 设置人脸数据图片的大小
dataset = fetch_olivetti_faces(shuffle=True, random_state=RandomState(0))
faces = dataset.data
# 加载数据,并打乱顺序
# 3。设置图像的展示方式
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)#确定数据的子图位置
vmax=max(comp.max(),-comp.min())#找到绝对值最大的数
plt.imshow(comp.reshape(image_shape),cmap=plt.cm.gray,interpolation='nearest',vmin=-vmax,vmax=vmax)
# 颜色图谱设置成灰度,插值运算选择nearest,即把某块显示成一种颜色,利用vmin和vmax来缩放参数
#进行坐标轴变换
plt.xticks(())
plt.yticks(())
plt.subplots_adjust(0.01,0.05,0.99,0.94,0.04,0.)#调整子图的间距
# 4。创建特征提取的对象NMF,使用PCA作为对比
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))]
#调用PCA算法,使得有六个主成分,并对特征进行白化,即使得每个特征具有相同的方差
# 5。 降维后数据点的可视化
for name, estimator in estimators:#迭代运行两种算法
print("Extracting the top %d %s..."%(n_components,name))#输出方法名称
print(faces.shape)
estimator.fit(faces)#运行模型
components_=estimator.components_#提取运算出来的主成分
plot_gallery(name,components_[:n_components])#调用绘图函数,选取数据中的前六个进行绘图
plt.show()
结果