zoukankan      html  css  js  c++  java
  • 矩阵分解系列三:非负矩阵分解及Python实现

    非负矩阵分解的定义及理解

    摘自《迁移学习》K-Means算法&非负矩阵三因子分解(NMTF)

    下图可帮助理解:

     

    举个简单的人脸重构例子: 

    Python实例:用非负矩阵分解提取人脸特征

    「摘自Python机器学习应用

    在sklearn库中,可以使用sklearn.decomposition.NMF加载NMF算法,主要参数有:
    • n_components:指定分解后基向量矩阵W的基向量个数k
    • init:W矩阵和Z矩阵的初始化方式,默认为‘nndsvdar’

    目标:已知Olivetti人脸数据共400个,每个数据是64*64大小。由于NMF分解得到的W矩阵相当于从原始矩阵中提取的特征,那么就可以使用NMF对400个人脸数据进行特征提取。
    程序如下:
    from numpy.random import RandomState
    import matplotlib.pyplot as plt
    from sklearn.datasets import fetch_olivetti_faces   #加载Olivetti人脸数据集导入函数
    from sklearn import decomposition
    
    n_row, n_col = 2, 3
    n_components = n_row * n_col   #设置提取的特征的数目
    image_shape = (64, 64)   #设置展示时人脸数据图片的大小
    
    dataset = fetch_olivetti_faces(shuffle=True, random_state=RandomState(0))
    faces = dataset.data
    
    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("First centered Olivetti faces", faces[:n_components])
    
    estimators = [('Eigenfaces - PCA using randomized SVD', decomposition.PCA(n_components=n_components, whiten=True)),
                  ('Non-negative components - NMF', decomposition.NMF(n_components=n_components, 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)   #调用PCA或NMF提取特征
        components_ = estimator.components_   #获取提取的特征
        plot_gallery(name, components_[:n_components])
    
    plt.show()  
    运行结果:

    Extracting the top 6 Eigenfaces - PCA using randomized SVD...
    (400, 4096)
    Extracting the top 6 Non-negative components - NMF...
    (400, 4096)

       
     
  • 相关阅读:
    OCP-1Z0-053-V12.02-315题
    OCP-1Z0-053-V12.02-272题
    OCP-1Z0-053-V12.02-152题
    OCP-1Z0-053-V12.02-78题
    OCP-1Z0-053-V12.02-593题
    OCP-1Z0-053-V12.02-505题
    JavaScript中字符串和数字
    OCP-1Z0-053-V12.02-360题
    OCP-1Z0-053-V12.02-213题
    OCP-1Z0-053-V12.02-598题
  • 原文地址:https://www.cnblogs.com/picassooo/p/12917090.html
Copyright © 2011-2022 走看看