初試主題模型LDA-基於python的gensim包


http://blog.csdn.net/a_step_further/article/details/51176959

LDA是文本挖掘中常用的主題模型,用來從大量文檔中提取出最能表達各個主題的一些關鍵詞,具體算法原理可參閱KM上相關文章。筆者因業務需求,需對騰訊微博上若干賬號的消息進行主題提取,故而嘗試了一下該算法,基於python的gensim包實現一個簡單的分析。

准備工作

  • 安裝python的中文分詞模塊, jieba
  • 安裝python的文本主題建模的模塊, gensim (官網 https://radimrehurek.com/gensim/)。 這個模塊安裝時依賴了一大堆其它包,需要耐心地一個一個安裝。
  • 到網絡上下載中文停用詞表

上代碼

[python]
    1. #!/usr/bin/python  
    2. #coding:utf-8  
    3. import sys  
    4. reload(sys)  
    5. sys.setdefaultencoding("utf8")  
    6. import jieba  
    7. from gensim import corpora, models  
    8.   
    9.   
    10. def get_stop_words_set(file_name):  
    11.     with open(file_name,'r') as file:  
    12.         return set([line.strip() for line in file])  
    13.   
    14. def get_words_list(file_name,stop_word_file):  
    15.     stop_words_set = get_stop_words_set(stop_word_file)  
    16.     print "共計導入 %d 個停用詞" % len(stop_words_set)  
    17.     word_list = []  
    18.     with open(file_name,'r') as file:  
    19.         for line in file:  
    20.             tmp_list = list(jieba.cut(line.strip(),cut_all=False))  
    21.             word_list.append([term for term in tmp_list if str(term) not in stop_words_set]) #注意這里term是unicode類型,如果不轉成str,判斷會為假  
    22.     return word_list  
    23.   
    24.   
    25. if __name__ == '__main__':  
    26.     if len(sys.argv) < 3:  
    27.         print "Usage: %s <raw_msg_file> <stop_word_file>" % sys.argv[0]  
    28.         sys.exit(1)  
    29.   
    30.     raw_msg_file = sys.argv[1]  
    31.     stop_word_file = sys.argv[2]  
    32.     word_list = get_words_list(raw_msg_file,stop_word_file) #列表,其中每個元素也是一個列表,即每行文字分詞后形成的詞語列表  
    33.     word_dict = corpora.Dictionary(word_list)  #生成文檔的詞典,每個詞與一個整型索引值對應  
    34.     corpus_list = [word_dict.doc2bow(text) for text in word_list] #詞頻統計,轉化成空間向量格式  
    35.     lda = models.ldamodel.LdaModel(corpus=corpus_list,id2word=word_dict,num_topics=10,alpha='auto')  
    36.   
    37.     output_file = './lda_output.txt'  
    38.     with open(output_file,'w') as f:  
    39.         for pattern in lda.show_topics():  
    40.             print >> f, "%s" % str(pattern) 

另外還有一些學習資料:https://yq.aliyun.com/articles/26029 [python] LDA處理文檔主題分布代碼入門筆記


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM