NMF在文件聚類中的應用

2021-06-06 13:16:37 字數 2534 閱讀 1169

(1)給定乙個文件語料庫,首先構造乙個詞-文件矩陣v,其中v的i列代表文件di的加權詞頻向量。

(2)使用nmf方法分解矩陣v,得到分解矩陣w,h

(3)歸一化w,h。

(4)使用矩陣h來決定每個文件的歸類。那個文件di的類標為:x,當:

當然,如果想對單詞進行聚類,我們可以通過w矩陣來確定。對於單詞ti,分配的類標x,當:

上面,我們對nmf在文字聚類上的應用只是做了簡要的介紹。對了,如何構造單詞-文件矩陣,我們這裡沒詳細介紹(做文字聚類的人,這個是常識哦)。

下面貼出自己編寫的**,依然採用python指令碼撰寫的(為啥? 主流,方便唄):

# !/usr/bin/python

# file name : nmf

from numpy import *

from math import log

from math import sqrt

def difcost(a,b):

dif=0

for i in range(shape(a)[0]):

for j in range(shape(a)[1]):

# euclidean distance

dif+=pow(a[i,j]-b[i,j],2)

return dif

def difcost_kl(a,b):

dif=0

for i in range(shape(a)[0]):

for j in range(shape(a)[1]):

dif+=a[i,j]*log(a[i,j]/b[i,j])-a[i,j]+b[i,j]

return dif

# nmf 

def factorize(v,pc=10,iter=50):

ic=shape(v)[0]

fc=shape(v)[1]

# initialize the weight and feature matrices with random values

w=matrix([[random.random() for j in range(pc)] for i in range(ic)])

h=matrix([[random.random() for i in range(fc)] for i in range(pc)])

# perform operation a maximum of iter times

for i in range(iter):

wh=w*h

# calculate the current difference

cost=difcost_kl(v,wh)

if i==0: print cost

# terminate if the matrix has been fully factorized

if cost==0: break

# update feature matrix

hn=(transpose(w)*v)

hd=(transpose(w)*w*h)

h=matrix(array(h)*array(hn)/array(hd))

# update weights matrix

wn=(v*transpose(h))

wd=(w*h*transpose(h))

w=matrix(array(w)*array(wn)/array(wd))

# normalize w,h

for j in range(pc):

sum = 0.0

for k in range(ic):

sum  = sum + w[k,j]* w[k,j]

sum = sqrt(sum)

for k in range(ic):

w[k,j] /= sum

for k in range(fc):

h[j,k] /= sum  

return w,h

# using nmf for clustering ;

# v is original matrix;

# k is the cluster number;

def nmf_cluster(v,k):

w,h = factorize(v,k)

cluster = [ for i in range(k)]

ht = transpose(h)

for i in range(shape(ht)[0]):

bestlabel = 0

max_eig = 0

for j in range(shape(ht)[1]):

if ht[i,j] > max_eig:

max_eig = ht[i,j]

bestlabel = j

return cluster

資料聚類的簡單應用

資料聚類的簡單應用 資料聚類data 1.聚類時常被用於資料量很大 data intensive 的應用中。2.聚類是無監督學習 unsupervised learning 的乙個例子。無監督學習演算法並不利用帶有正確答案的樣本資料 進行 訓練 它們的目的是要在一組資料中找尋某種結構,而這些資料本身...

trayicon類在單文件中的使用

新建乙個基於單文件的工程 將trayicon類引入工程,並引入圖示作為動態顯示用 在工程中新建乙個選單id為idr traypopup,新增兩個命令id id showwindow 和 id hidewindow 並利用類嚮導在cmainframe類中為它們新增命令處理函式 void cmainfr...

聚類中的效能度量

在無監督學習中,訓練樣本的標記是沒有指定的,通過對無標記樣本的訓練來探索資料之間的規律。其中應用最廣的便是聚類,聚類試圖把一群未標記資料劃分為一堆不相交的子集,每個子集叫做 簇 每個簇可能對應於乙個類別標籤,但值得注意的是,這個標籤僅僅是我們人為指定強加的,並不是資料本身就存在這樣的標籤。例如 軟體...