【机器学习】NMF(非负矩阵分解)
寫在篇前
??本篇文章主要介紹NMF算法原理以及使用sklearn中的封裝方法實現該算法,最重要的是理解要NMF矩陣分解的實際意義,將其運用到自己的數據分析中!
理論概述
??NMF(Non-negative matrix factorization),即對于任意給定的一個非負矩陣V,其能夠尋找到一個非負矩陣W和一個非負矩陣H,滿足條件V=W*H,從而將一個非負的矩陣分解為左右兩個非負矩陣的乘積。**其中,V矩陣中每一列代表一個觀測(observation),每一行代表一個特征(feature);W矩陣稱為基矩陣,H矩陣稱為系數矩陣或權重矩陣。這時用系數矩陣H代替原始矩陣,就可以實現對原始矩陣進行降維,得到數據特征的降維矩陣,從而減少存儲空間。**過程如下圖所示:
??nmf更詳盡的原理可以參考Non-negative matrix factorization - Wikipedia,這里我主要列出我很關注的損失函數(lossFunction or objective function):
-
squared frobenius norm
arg  min?W,H12∣∣A?WH∣∣Fro2+αρ∣∣W∣∣1+αρ∣∣H∣∣1+α(1?ρ)2∣∣W∣∣Fro2+α(1?ρ)2∣∣H∣∣Fro2\underbrace{arg\;min}_{W,H}\frac{1}{2}||A-WH||_{Fro}^2 +\alpha\rho|| W||_1+\alpha\rho|| H||_1+\frac{\alpha(1-\rho)}{2}|| W||_{Fro}^2 + \frac{\alpha(1-\rho)}{2}|| H||_{Fro}^2 W,Hargmin??21?∣∣A?WH∣∣Fro2?+αρ∣∣W∣∣1?+αρ∣∣H∣∣1?+2α(1?ρ)?∣∣W∣∣Fro2?+2α(1?ρ)?∣∣H∣∣Fro2?
? 其中:
12∣∣A?WH∣∣Fro2=12∑i,j(Aij?WHij)2\frac{1}{2} ||A - WH||_{\mathrm{Fro}}^2 = \frac{1}{2} \sum_{i,j} (A_{ij} - {WH}_{ij})^2 21?∣∣A?WH∣∣Fro2?=21?i,j∑?(Aij??WHij?)2
? α\alphaα為L1&L2正則化參數,而\rho為L1正則化占總正則化項的比例。||*||_1為L1范數。 -
Kullback-Leibler (KL)
dKL(X,Y)=∑i,j(Xijlog?(XijYij)?Xij+Yij)d_{KL}(X, Y) = \sum_{i,j} (X_{ij} \log(\frac{X_{ij}}{Y_{ij}}) - X_{ij} + Y_{ij}) dKL?(X,Y)=i,j∑?(Xij?log(Yij?Xij??)?Xij?+Yij?) -
Itakura-Saito (IS)
dIS(X,Y)=∑i,j(XijYij?log?(XijYij)?1)d_{IS}(X, Y) = \sum_{i,j} (\frac{X_{ij}}{Y_{ij}} - \log(\frac{X_{ij}}{Y_{ij}}) - 1) dIS?(X,Y)=i,j∑?(Yij?Xij???log(Yij?Xij??)?1)
? 實際上,上面三個公式是beta-divergence family中的三個特殊情況(分別是當β=2,1,0\beta = 2, 1, 0β=2,1,0),其原型是:
dβ(X,Y)=∑i,j1β(β?1)(Xijβ+(β?1)Yijβ?βXijYijβ?1)d_{\beta}(X, Y) = \sum_{i,j} \frac{1}{\beta(\beta - 1)}(X_{ij}^\beta + (\beta-1)Y_{ij}^\beta - \beta X_{ij} Y_{ij}^{\beta - 1}) dβ?(X,Y)=i,j∑?β(β?1)1?(Xijβ?+(β?1)Yijβ??βXij?Yijβ?1?)
代碼實現
代碼解讀
???在sklearn封裝了NMF的實現,可以非常方便我們的使用,其實現基本和前面理論部分的實現是一致的,但是注意sklearn中輸入數據的格式是(samples, features):
from sklearn.decomposition import NMF from sklearn.datasets import load_irisX, _ = load_iris(True)# can be used for example for dimensionality reduction, source separation or topic extraction # 個人認為最重要的參數是n_components、alpha、l1_ratio、solver nmf = NMF(n_components=2, # k value,默認會保留全部特征init=None, # W H 的初始化方法,包括'random' | 'nndsvd'(默認) | 'nndsvda' | 'nndsvdar' | 'custom'.solver='cd', # 'cd' | 'mu'beta_loss='frobenius', # {'frobenius', 'kullback-leibler', 'itakura-saito'},一般默認就好tol=1e-4, # 停止迭代的極限條件max_iter=200, # 最大迭代次數random_state=None,alpha=0., # 正則化參數l1_ratio=0., # 正則化參數verbose=0, # 冗長模式shuffle=False # 針對"cd solver")# -----------------函數------------------------ print('params:', nmf.get_params()) # 獲取構造函數參數的值,也可以nmf.attr得到,所以下面我會省略這些屬性# 下面四個函數很簡單,也最核心,例子中見 nmf.fit(X) W = nmf.fit_transform(X) W = nmf.transform(X) nmf.inverse_transform(W) # -----------------屬性------------------------ H = nmf.components_ # H矩陣 print('reconstruction_err_', nmf.reconstruction_err_) # 損失函數值 print('n_iter_', nmf.n_iter_) # 實際迭代次數注意點:
- init參數中,nndsvd(默認)更適用于sparse factorization,其變體則適用于dense factorization.
- solver參數中,如果初始化中產生很多零值,Multiplicative Update (mu) 不能很好更新。所以mu一般不和nndsvd使用,而和其變體nndsvda、nndsvdar使用。
- solver參數中,cd只能優化Frobenius norm函數;而mu可以更新所有損失函數
案例1
??第一個案例很簡單,目的是理解分解出來的這兩個矩陣能用來干嘛,分別是什么意思,但是其實我在文章第一部分已經解釋了,直接看例子:
>>> import numpy as np >>> X = np.array([[1, 1], [2, 1], [3, 1.2], [4, 1], [5, 0.8], [6, 1]]) >>> from sklearn.decomposition import NMF >>> model = NMF(n_components=2, init='random', random_state=0) >>> W = model.fit_transform(X) >>> H = model.components_ >>> X_new = np.array([[1, 0], [1, 6.1], [1, 0], [1, 4], [3.2, 1], [0, 4]]) >>> W_new = model.transform(X_new) >>> W_new # 輸出 W_newarray([[0.35919303],
? [0.86264547],
? [0.35919303],
? [0.68932578],
? [1.23195088],
? [0.33013275]])
??ok,這個小例子就說明了我們通過NMF獲得系數矩陣H,并用系數矩陣H獲得新矩陣W_new的基矩陣,實現W_new的數據降維(or 特征提取)。實際上,這時W_new = model.transform(X_new)做的工作相當于:
np.mat(X_new)*(np.mat(H).I)matrix([[0.35919303],
? [0.86264547],
? [0.35919303],
? [0.68932578],
? [1.23195088],
? [0.33013275]])
案例2
??這里再舉一個NMF在圖像特征提取的應用,來自官方示例,根據我的需要改動了一些:
from time import time from numpy.random import RandomState import matplotlib.pyplot as plt from sklearn.datasets import fetch_olivetti_faces from sklearn import decompositionn_row, n_col = 2, 3 n_components = n_row * n_col image_shape = (64, 64) rng = RandomState(0)# ############################################################################# # Load faces data dataset = fetch_olivetti_faces('./', True,random_state=rng) faces = dataset.datan_samples, n_features = faces.shapeprint("Dataset consists of %d faces, features is %s" % (n_samples, n_features))def plot_gallery(title, images, n_col=n_col, n_row=n_row, cmap=plt.cm.gray):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=cmap,interpolation='nearest',vmin=-vmax, vmax=vmax)plt.xticks(())plt.yticks(())plt.subplots_adjust(0.01, 0.05, 0.99, 0.93, 0.04, 0.)# ############################################################################# estimators = [('Non-negative components - NMF',decomposition.NMF(n_components=n_components, init='nndsvda', tol=5e-3)) ]# ############################################################################# # Plot a sample of the input dataplot_gallery("First centered Olivetti faces", faces[:n_components])# ############################################################################# # Do the estimation and plot itfor name, estimator in estimators:print("Extracting the top %d %s..." % (n_components, name))t0 = time()data = facesestimator.fit(data)train_time = (time() - t0)print("done in %0.3fs" % train_time)components_ = estimator.components_print('components_:', components_.shape, '\n**\n', components_)plot_gallery('%s - Train time %.1fs' % (name, train_time),components_) plt.show()#---------------------------其他注釋--------------------------- V矩陣:400*4096 W矩陣:400*6 H矩陣:6*4096??下面是script運行結果:
寫在篇后
??NMF最早由科學家D.D.Lee和H.S.Seung提出的一種非負矩陣分解方法,并在Nature發表文章《Learning the parts of objects by non-negative matrix factorization》。隨后也有了很多NMF變體,應用也越發廣泛,包括文本降維、話題提取、圖像處理等。這里必須指出,我看到一份NMF非常完整的資料,但是精力有限,不能全面cover,有興趣的同學可以參考nimfa。
總結
以上是生活随笔為你收集整理的【机器学习】NMF(非负矩阵分解)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【机器学习】层次聚类
- 下一篇: matplotlib(六)三维作图