矩阵分解系列三:非负矩阵分解及Python实现
非负矩阵分解的定义及理解
「摘自《迁移学习》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个人脸数据进行特征提取。
程序如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | 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)



【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 单元测试从入门到精通