1. 程式人生 > >使用gensim中的lda模型訓練主題分佈

使用gensim中的lda模型訓練主題分佈

一直在尋找各種大神的LDA演算法,不過除錯一直沒有成功,最後還是選擇使用gensim的LDA工具來訓練自己的文字資料吧。

#coding=utf-8
import codecs
from gensim import corpora
from gensim.models import LdaModel
from gensim.corpora import Dictionary
fr=open('cleanChiSegments.txt','r')
train=[]
for line in fr.readlines():
    line=line.split(' ')
    train.append(line)

print len(train)
print ' '.join(train[2])

dictionary = corpora.Dictionary(train)
corpus = [ dictionary.doc2bow(text) for text in train ]
lda = LdaModel(corpus=corpus, id2word=dictionary, num_topics=100)

topic_list=lda.print_topics(20)
print type(lda.print_topics(20))
print len(lda.print_topics(20))

for topic in topic_list:
    print topic
print "第一主題"
print lda.print_topic(1)


print '給定一個新文件,輸出其主題分佈'

#test_doc = list(new_doc) #新文件進行分詞
test_doc=train[2]#檢視訓練集中第三個樣本的主題分佈
doc_bow = dictionary.doc2bow(test_doc)      #文件轉換成bow
doc_lda = lda[doc_bow]                   #得到新文件的主題分佈
#輸出新文件的主題分佈
print doc_lda
for topic in doc_lda:
    print "%s\t%f\n"%(lda.print_topic(topic[0]), topic[1])

----------------------------------------------------------下面輸出上面工具程式碼的執行結果---------------------------------------------------

下面輸出的是前20個topic-word分佈


對訓練集中第三個樣本測試,基於訓練集得到的主題模型,輸出其主題分佈。

即表示新文字的doc-topic分佈,以及每個主題下的topic-word分佈