天天看點

自然語言處理LDA入門實戰(python代碼)

這是LDA的入門學習,由五個句子組成,訓練的過程也較為簡單。

代碼的網頁來源https://aiteam.blog.csdn.net/article/details/88392606

另外,在b站上找到一個視訊教程,講的很清楚,建議先看視訊。網頁來源https://www.bilibili.com/video/BV1rJ411g7Mz?p=171

LDA模組化的步驟

1.預處理,将文檔轉為list to list形式,形成dictionary字典。即[[1word1,1word2,1word3],[2word1,2word2,2word3],[3word1,3word2,3word3]]的清單中有清單的格式。其中,大清單下每個小清單代表一個文檔,每個文檔又包含詞。是以,要先進行去停用詞、去标點符号、标準化、詞幹化等步驟。

2.形成詞-文檔矩陣DT/語料庫,裡面包含的是詞和詞頻。也就是dictionary.doc2bow

3.使用gensim來LDA模組化,需要dictionary、corpus語料庫和topic數量k。

代碼是自己修改過運作的,原代碼沒什麼問題,隻是在安裝包時以及stopwords那裡每個人的情況不同,我這裡報錯了,具體解決也都是百度來的。

#從nltk中import停用詞
import nltk
#nltk.download()
from nltk.corpus import stopwords
from nltk.stem.wordnet import  WordNetLemmatizer
import string
import gensim
from gensim import models
#如果顯示 'No module named gensim',那麼打開prompt,輸入pip install gensim


doc1='Sugar is bad to consume. My sister likes to have sugar, but not my father.'
doc2='My father spends a lot of time driving my sister around to dance practice.'
doc3='Doctors suggest that driving may cause increased stress and blood pressure.'
doc4='Sometimes I feel pressure to perform well at school, but my father never seems to drive my sister to do better.'
doc5='Health experts say that Sugar is not good for your lifestyle.'
#整合文檔
doc_complete=[doc1,doc2,doc3,doc4,doc5]



stop=set(stopwords.words('english'))
exclude=set(string.punctuation)#punctuation是标點符号,string.punctuation是所有的标點符号
lemma=WordNetLemmatizer()#詞幹

def clean(doc):
    stop_free=' '.join ([i for i in doc.lower().split() if i not in stop])  #去除停用詞,doc.lower是将所有字元小寫,split()以空格為分隔符,包含 \n
    punc_free=''.join(ch for ch in stop_free if ch not in exclude)
    normalized=' '.join(lemma.lemmatize(word) for word in punc_free.split())#注意是有空格的' ',不是'',沒有空格的化後面出現的不是單個單詞,而是一串沒有空格的整個句子字元。
    return normalized

doc_clean=[clean(doc).split() for doc in doc_complete]

from gensim import corpora
#建立語料的詞語詞典,每個單獨的詞都會被賦予一個索引
print(doc_clean)
#每個句子都被詞幹化,出現的結果是五個不同詞構成的【】
dictionary=corpora.Dictionary(doc_clean)
print(dictionary)


#使用上面的詞典,将文檔轉換為文檔清單(語料)變成DT矩陣
#dictionary.doc2bow輸出:[(詞ID,詞頻)..],對該文本進行詞袋格式的轉換,查找詞典在文檔出現的詞和次數進行輸出
doc_term_matrix=[dictionary.doc2bow(doc) for doc in doc_clean]

#使用gensim來建立LDA模型對象
Lda=models.ldamodel.LdaModel

#在DT矩陣上運作和訓練LDA模型
ldamodel=Lda(doc_term_matrix,num_topics=3,id2word=dictionary,passes=50)

#輸出結果
print(ldamodel.print_topics(num_topics=3,num_words=3))