非負(fù)矩陣分解(Non-negative Matrix Factorization ,NMF)是在矩陣中所有元素均為非負(fù)數(shù)約束條件下的矩陣分解方法。
基本思想:給定一個(gè)非負(fù)矩陣V,NMF能夠找到一個(gè)非負(fù)矩陣W和一個(gè)非負(fù)矩陣H,使得矩陣W和H的乘積近似等于矩陣V中的值。
? W矩陣:基礎(chǔ)圖像矩陣,相當(dāng)于從原矩陣V中抽取出來的特征
? H矩陣:系數(shù)矩陣。
? NMF 能夠廣泛應(yīng)用于圖像分析、文本挖掘和語音處理等領(lǐng)域
在sklearn庫中,可以使用sklearn.decomposition.NMF加載NMF算法,主要參數(shù)有:
n_components:用于指定分解后矩陣的單個(gè)維度k;
init:W矩陣和H矩陣的初始化方式,默認(rèn)為'nndsvdar'
NMF人臉數(shù)據(jù)特征提取
目標(biāo):已知Olivetti人臉數(shù)據(jù)共400個(gè),每個(gè)數(shù)據(jù)是64*64大小。由于NMF分解得到的W矩陣相當(dāng)于從原始矩陣中提取的特征,那么就可以使用NMF對(duì)400個(gè)人臉數(shù)據(jù)進(jìn)行特征提取
通過設(shè)置 k的 大小,設(shè)置提取特征的數(shù)目。在本實(shí)驗(yàn)中設(shè)置 k=6,隨后將提取的特征以圖像的形式展示出來。
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()