Python机器学习应用-降维之NMF

非负矩阵分解(NMF)

非负矩阵分解(Non-negative Matrix Factorization,NMF)是在矩阵中所有元素均为非负数约束条件之下的矩阵分解方法。

基本思想:

给定一个非负矩阵 V V ,NMF能够找到一个非负矩阵W和一个非负矩阵 H H ,使得矩阵W H H 的乘积近似等于矩阵V中的值。

Vnm=WnkHkm V n ∗ m = W n ∗ k ∗ H k ∗ m

  • W W 矩阵:基础图像矩阵,相当于从原矩阵中抽取出来的特征。
  • H矩阵:系数矩阵。
    这里写图片描述
  • NMF能够广泛应用于图像分析、文本挖掘和语音处理等领域。
    这里写图片描述

N优化目标:

最小化 W W 矩阵H矩阵的乘积和原始矩阵之间的差别。

argmin12||XWH||2=12i,j(XijWHij)2 a r g min 1 2 | | X − W H | | 2 = 1 2 ∑ i , j ( X i j − W H i j ) 2

基于KL散度的优化目标,损失函数如下:
argminJ(W,H)=i,j(XijlnXijWHijXij+WHij) a r g min J ( W , H ) = ∑ i , j ( X i j ln ⁡ X i j W H i j − X i j + W H i j )

sklearn中NMF:

在sklearn库中,可以使用sklearn.decomposition.NMF加载NMF算法,主要参数有:

  • n_components:用于指定分解后矩阵的单个维度k;
  • init: W W 矩阵和H矩阵的初始化方式,默认为‘nndsvdar’。

实例:NMF人脸数据特征提取

目标:

已知Olivetti人脸数据共400个,每个数据是64*64大小。由于NMF分解得到的 W W <script type="math/tex" id="MathJax-Element-16">W</script>矩阵相当于从原始矩阵中提取的特征,那么就可以使用NMF对400个人脸数据进行特征提取。
通过设置k的大小,设置提取的特征的数目。在本实验中设置k=6,随后将提取的特征以图像的形式展示出来。
这里写图片描述

实例程序编写:

1 建立工程。导入sklearn相关工具包:

from numpy.random import RandomState
import matplotlib.pyplot as plt
from sklearn.datasets import fetch_olivetti_faces
from sklearn import decomposition

2 设置基本参数并加载数据

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 #加载数据并打乱顺序

3 设置图像的展示方式:

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.)

4 创建特征提取的对象NMF,使用PCA作为对比:

estimators = [
    ('Eigenfaces - PCA using randomized SVD',
         decomposition.PCA(n_components=6,whiten=True)),

    ('Non-negative components - NMF',
         decomposition.NMF(n_components=6, init='nndsvda', tol=5e-3))

5 降维后数据点的可视化:

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()

这里写图片描述

附件

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 = 2, 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=6,whiten=True)),

    ('Non-negative components - NMF',
         decomposition.NMF(n_components=6, 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()
  • 3
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值