矩阵分解系列三:非负矩阵分解及Python实现
生活随笔
收集整理的這篇文章主要介紹了
矩阵分解系列三:非负矩阵分解及Python实现
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
非負(fù)矩陣分解的定義及理解
「摘自《遷移學(xué)習(xí)》K-Means算法&非負(fù)矩陣三因子分解(NMTF)」
下圖可幫助理解:
舉個(gè)簡(jiǎn)單的人臉重構(gòu)例子:
Python實(shí)例:用非負(fù)矩陣分解提取人臉特征
「摘自Python機(jī)器學(xué)習(xí)應(yīng)用」
在sklearn庫(kù)中,可以使用sklearn.decomposition.NMF加載NMF算法,主要參數(shù)有:
n_components:指定分解后基向量矩陣W的基向量個(gè)數(shù)k
init:W矩陣和Z矩陣的初始化方式,默認(rèn)為‘nndsvdar’
目標(biāo):已知Olivetti人臉數(shù)據(jù)共400個(gè),每個(gè)數(shù)據(jù)是64*64大小。由于NMF分解得到的W矩陣相當(dāng)于從原始矩陣中提取的特征,那么就可以使用NMF對(duì)400個(gè)人臉數(shù)據(jù)進(jìn)行特征提取。
程序如下:
from numpy.random import RandomState
import matplotlib.pyplot as plt
from sklearn.datasets import fetch_olivetti_faces #加載Olivetti人臉數(shù)據(jù)集導(dǎo)入函數(shù)
from sklearn import decomposition
n_row, n_col = 2, 3
n_components = n_row * n_col #設(shè)置提取的特征的數(shù)目
image_shape = (64, 64) #設(shè)置展示時(shí)人臉數(shù)據(jù)圖片的大小
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) #調(diào)用PCA或NMF提取特征
components_ = estimator.components_ #獲取提取的特征
plot_gallery(name, components_[:n_components])
plt.show()
運(yùn)行結(jié)果:
Extracting the top 6 Eigenfaces - PCA using randomized SVD...
(400, 4096)
Extracting the top 6 Non-negative components - NMF...
(400, 4096)
總結(jié)
以上是生活随笔為你收集整理的矩阵分解系列三:非负矩阵分解及Python实现的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 中国四大传统节日是什么时候?
- 下一篇: 二维矩阵的算法