python矩阵对角化_矩阵分解系列三:非负矩阵分解及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)

  

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值