NMF方法及實例

非負矩陣分解(Non-negative Matrix Factorization ,NMF)是在矩陣中所有元素均為非負數約束條件下的矩陣分解方法。
基本思想:給定一個非負矩陣V,NMF能夠找到一個非負矩陣W和一個非負矩陣H,使得矩陣W和H的乘積近似等于矩陣V中的值。


image.png

? W矩陣:基礎圖像矩陣,相當于從原矩陣V中抽取出來的特征
? H矩陣:系數矩陣。
? NMF 能夠廣泛應用于圖像分析、文本挖掘和語音處理等領域

image.png
image.png
image.png
image.png

在sklearn庫中,可以使用sklearn.decomposition.NMF加載NMF算法,主要參數有:
n_components:用于指定分解后矩陣的單個維度k;
init:W矩陣和H矩陣的初始化方式,默認為'nndsvdar'

NMF人臉數據特征提取
目標:已知Olivetti人臉數據共400個,每個數據是64*64大小。由于NMF分解得到的W矩陣相當于從原始矩陣中提取的特征,那么就可以使用NMF對400個人臉數據進行特征提取

image.png

通過設置 k的 大小,設置提取特征的數目。在本實驗中設置 k=6,隨后將提取的特征以圖像的形式展示出來。

image.png
image.png
image.png
image.png
image.png

image.png

runfile('C:/Users/Sean Chang/.spyder/nmf.py', wdir='C:/Users/Sean Chang/.spyder')
Extracting the top 9 Eigenfaces - PCA using randomized SVD...
(400L, 4096L)
Extracting the top 9 Non-negative components - NMF...
(400L, 4096L)

# -*- coding: utf-8 -*-
"""
Created on Tue May 23 18:03:38 2017

@author: Sean Chang
"""

from numpy.random import RandomState
import matplotlib.pyplot as plt
from sklearn.datasets import fetch_olivetti_faces
from sklearn import decomposition
 
 
n_row, n_col = 3, 3
n_components = n_row * n_col
image_shape = (64, 64)
 
 
###############################################################################
# Load faces data
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=9,whiten=True)),
 
    ('Non-negative components - NMF',
         decomposition.NMF(n_components=9, 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)
    components_ = estimator.components_
    plot_gallery(name, components_[:n_components])
 
plt.show()
image.png
image.png
image.png

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容