非負矩陣分解的定義及理解
「摘自《遷移學習》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)


