目录
1 概念
2 矩阵分解优化目标
3 案例
4 代码实现(Python)
4.1 代码
#====1. 建立工程,导入sklearn相关工具包:=====
from numpy.random import RandomState  #加载RandomState用于创建随机种子
import matplotlib.pyplot as plt
from sklearn.datasets import fetch_olivetti_faces   #加载Olivetti人脸数据集导入函数
from sklearn import decomposition #加载PCA算法包
from pylab import *
import matplotlib; matplotlib.use('TkAgg')
mpl.rcParams['font.sans-serif'] = ['SimHei']
mpl.rcParams['axes.unicode_minus'] = False
#======2. 设置基本参数并加载数据:=====
n_row, n_col = 2, 3      #设置图像展示时的排列情况,如右图
n_components = n_row * n_col  #设置提取的特征的数目
image_shape = (64, 64)           #设置人脸数据图片的大小
#=====3.下载人脸数据:================
dataset = fetch_olivetti_faces(shuffle=True, random_state=RandomState(0)) #加载数据,并打乱顺序
faces = dataset.data      #加载数据,并打乱顺序
#=====4. 设置图像的展示方式:==========
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)
        plt.xticks(())    #去除子图的坐标轴标签
        plt.yticks(())
    plt.subplots_adjust(0.01, 0.05, 0.99, 0.94, 0.04, 0.)  #对子图位置及间隔调整
plot_gallery("首先是奥利维蒂的脸", faces[:n_components])
#=======5.创建特征提取的对象NMF,使用PCA作为对比:====
estimators = [
    ('基于随机奇异值分解的特征脸PCA',  #提取方法名称
     decomposition.PCA(n_components=6, whiten=True)),   #PCA实例
    ('非负性成分-NMF',         #提取方法名称
     decomposition.NMF(n_components=6, init='nndsvda', tol=5e-3))  #NMF实例
]
#=======6.降维后数据点的可视化:=================
for name, estimator in estimators:         #分别调用PCA和NMF
    print("Extracting the top %d %s..." % (n_components, name))
    print(faces.shape)
    estimator.fit(faces)                   #调用PCA或NMF提取特征(数据训练)
    components_ = estimator.components_         #获取提取的特征
    plot_gallery(name, components_[:n_components])   #按照固定格式进行排列
plt.show()
 
4.2 结果展示
Extracting the top 6 基于随机奇异值分解的特征脸PCA...
(400, 4096)
Extracting the top 6 非负性成分-NMF...
(400, 4096)
 
        
     
      










