<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          獨(dú)家 | 使用Python的LDA主題建模(附鏈接)

          共 9381字,需瀏覽 19分鐘

           ·

          2021-03-26 13:36


          作者:Kamil Polak

          翻譯:劉思婧

          校對(duì):孫韜淳


          本文約2700字,建議閱讀5分鐘

          本文為大家介紹了主題建模的概念、LDA算法的原理,示例了如何使用Python建立一個(gè)基礎(chǔ)的LDA主題模型,并使用pyLDAvis對(duì)主題進(jìn)行可視化。


          圖片來(lái)源:Kamil Polak

          引言


          主題建模包括從文檔術(shù)語(yǔ)中提取特征,并使用數(shù)學(xué)結(jié)構(gòu)和框架(如矩陣分解和奇異值分解)來(lái)生成彼此可區(qū)分的術(shù)語(yǔ)聚類(lèi)(cluster)或組,這些單詞聚類(lèi)繼而形成主題或概念。

          主題建模是一種對(duì)文檔進(jìn)行無(wú)監(jiān)督分類(lèi)的方法,類(lèi)似于對(duì)數(shù)值數(shù)據(jù)進(jìn)行聚類(lèi)。

          這些概念可以用來(lái)解釋語(yǔ)料庫(kù)的主題,也可以在各種文檔中一同頻繁出現(xiàn)的單詞之間建立語(yǔ)義聯(lián)系。

          主題建模可以應(yīng)用于以下方面:

          • 發(fā)現(xiàn)數(shù)據(jù)集中隱藏的主題;

          • 將文檔分類(lèi)到已經(jīng)發(fā)現(xiàn)的主題中;

          • 使用分類(lèi)來(lái)組織/總結(jié)/搜索文檔。


          有各種框架和算法可以用以建立主題模型:

          • 潛在語(yǔ)義索引(Latent semantic indexing)

          • 潛在狄利克雷分配(Latent Dirichlet Allocation,LDA)

          • 非負(fù)矩陣分解(Non-negative matrix factorization,NMF)


          在本文中,我們將重點(diǎn)討論如何使用Python進(jìn)行LDA主題建模。具體來(lái)說(shuō),我們將討論:

          • 什么是潛在狄利克雷分配(LDA, Latent Dirichlet allocation);

          • LDA算法如何工作;

          • 如何使用Python建立LDA主題模型。


          什么是潛在狄利克雷分配(LDA, Latent Dirichlet allocation)?


          潛在狄利克雷分配(LDA, Latent Dirichlet allocation)是一種生成概率模型(generative probabilistic model),該模型假設(shè)每個(gè)文檔具有類(lèi)似于概率潛在語(yǔ)義索引模型的主題的組合。

          簡(jiǎn)而言之,LDA背后的思想是,每個(gè)文檔可以通過(guò)主題的分布來(lái)描述,每個(gè)主題可以通過(guò)單詞的分布來(lái)描述。

          LDA算法如何工作?


          LDA由兩部分組成:

          • 我們已知的屬于文件的單詞;

          • 需要計(jì)算的屬于一個(gè)主題的單詞或?qū)儆谝粋€(gè)主題的單詞的概率。

           
          注意:LDA不關(guān)心文檔中單詞的順序。通常,LDA使用詞袋特征(bag-of-word feature)表示來(lái)代表文檔。

          以下步驟非常簡(jiǎn)單地解釋了LDA算法的工作原理:

          1. 對(duì)于每個(gè)文檔,隨機(jī)將每個(gè)單詞初始化為K個(gè)主題中的一個(gè)(事先選擇K個(gè)主題);
          2. 對(duì)于每個(gè)文檔D,瀏覽每個(gè)單詞w并計(jì)算:
          • P(T | D):文檔D中,指定給主題T的單詞的比例;

          • P(W | T):所有包含單詞W的文檔中,指定給主題T的比例。

          3. 考慮所有其他單詞及其主題分配,以概率P(T | D)′ P(W | T) 將單詞W與主題T重新分配。

          LDA主題模型的圖示如下。


          圖片來(lái)源:Wiki


          下圖直觀地展示了每個(gè)參數(shù)如何連接回文本文檔和術(shù)語(yǔ)。假設(shè)我們有M個(gè)文檔,文檔中有N個(gè)單詞,我們要生成的主題總數(shù)為K。
           
          圖中的黑盒代表核心算法,它利用前面提到的參數(shù)從文檔中提取K個(gè)主題。

          圖片來(lái)源:Christine Doig

          如何使用Python建立LDA主題模型


          我們將使用Gensim包中的潛在狄利克雷分配(LDA)。

          首先,我們需要導(dǎo)入包。核心包是re、gensim、spacy和pyLDAvis。此外,我們需要使用matplotlib、numpy和panases以進(jìn)行數(shù)據(jù)處理和可視化。

          1. import re2. import numpy as np3. import pandas as pd4. from pprint import pprint5. 6. # Gensim7. import gensim8. import gensim.corpora as corpora9. from gensim.utils import simple_preprocess10. from gensim.models import CoherenceModel11. 12. # spacy for lemmatization13. import spacy14. 15. # Plotting tools16. import pyLDAvis17. import pyLDAvis.gensim  # don't skip this18. import matplotlib.pyplot as plt19. %matplotlib inline20. 21. # Enable logging for gensim - optional22. import logging23. logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.ERROR)24. 25. import warnings26. warnings.filterwarnings("ignore",category=DeprecationWarning)

          像am/is/are/of/a/the/but/…這樣的詞不包含任何關(guān)于“主題”的信息。因此,作為預(yù)處理步驟,我們可以將它們從文檔中移除。

          要做到這一點(diǎn),我們需要從NLT導(dǎo)入停用詞。還可以通過(guò)添加一些額外的單詞來(lái)擴(kuò)展原始的停用詞列表。

          1. # NLTK Stop words2. from nltk.corpus import stopwords3. stop_words = stopwords.words('english')4. stop_words.extend(['from', 'subject', 're', 'edu', 'use'])

          在本教程中,我們將使用20個(gè)新聞組數(shù)據(jù)集,其中包含來(lái)自20個(gè)不同主題的大約11k個(gè)新聞組帖子。這可以作為newsgroups.json獲得。

          1. # Import Dataset2. df = pd.read_json('https://raw.githubusercontent.com/selva86/datasets/master/newsgroups.json')3. print(df.target_names.unique())4. df.head()


          刪除電子郵件鏈接和換行符

          在我們開(kāi)始主題建模之前,需要清理數(shù)據(jù)集。首先,刪除電子郵件鏈接、多余的空格和換行符。

          1. # Convert to list2. data = df.content.values.tolist()3. 4. # Remove Emails5. data = [re.sub('\S*@\S*\s?', '', sent) for sent in data]6. 7. # Remove new line characters8. data = [re.sub('\s+', ' ', sent) for sent in data]9. 10. # Remove distracting single quotes11. data = [re.sub("\'", "", sent) for sent in data]12. 13. pprint(data[:1])


          標(biāo)記(tokenize)單詞和清理文本

          讓我們把每個(gè)句子標(biāo)記成一個(gè)單詞列表,去掉標(biāo)點(diǎn)符號(hào)和不必要的字符。

          1. def sent_to_words(sentences):2.     for sentence in sentences:3.         yield(gensim.utils.simple_preprocess(str(sentence), deacc=True))  # deacc=True removes punctuations4. 5. data_words = list(sent_to_words(data))6. 7. print(data_words[:1])


          創(chuàng)建二元(Bigram)模型和三元(Trigram)模型

          1. # Build the bigram and trigram models2. bigram = gensim.models.Phrases(data_words, min_count=5, threshold=100) # higher threshold fewer phrases.3. trigram = gensim.models.Phrases(bigram[data_words], threshold=100)  4. 5. # Faster way to get a sentence clubbed as a trigram/bigram6. bigram_mod = gensim.models.phrases.Phraser(bigram)7. trigram_mod = gensim.models.phrases.Phraser(trigram)8. 9. # See trigram example10. print(trigram_mod[bigram_mod[data_words[0]]])


          刪除停用詞(stopword),建立二元模型和詞形還原(Lemmatize)
           
          在這一步中,我們分別定義了函數(shù)以刪除停止詞、建立二元模型和詞形還原,并且依次調(diào)用了這些函數(shù)。



          1. # Define functions for stopwords, bigrams, trigrams and lemmatization2. def remove_stopwords(texts):3. return [[word for word in simple_preprocess(str(doc)) if word not in stop_words] for doc in texts]4. 5. def make_bigrams(texts):6. return [bigram_mod[doc] for doc in texts]7. 8. def make_trigrams(texts):9. return [trigram_mod[bigram_mod[doc]] for doc in texts]10. 11. def lemmatization(texts, allowed_postags=['NOUN', 'ADJ', 'VERB', 'ADV']):12. """https://spacy.io/api/annotation"""13. texts_out = []14. for sent in texts:15. doc = nlp(" ".join(sent)) 16. texts_out.append([token.lemma_ for token in doc if token.pos_ in allowed_postags])17. return texts_out
          1. # Remove Stop Words2. data_words_nostops = remove_stopwords(data_words)3. 4. # Form Bigrams5. data_words_bigrams = make_bigrams(data_words_nostops)6. 7. # Initialize spacy 'en' model, keeping only tagger component (for efficiency)8. # python3 -m spacy download en9. nlp = spacy.load('en', disable=['parser', 'ner'])10. 11. # Do lemmatization keeping only noun, adj, vb, adv12. data_lemmatized = lemmatization(data_words_bigrams, allowed_postags=['NOUN', 'ADJ', 'VERB', 'ADV'])13. 14. print(data_lemmatized[:1])


          創(chuàng)建主題建模所需的詞典和語(yǔ)料庫(kù)(corpus)

          Gensim為文檔中的每個(gè)單詞創(chuàng)建一個(gè)唯一的id,但是在此之前,我們需要?jiǎng)?chuàng)建一個(gè)字典和語(yǔ)料庫(kù)作為模型的輸入。

          1. # Create Dictionary2. id2word = corpora.Dictionary(data_lemmatized)3. 4. # Create Corpus5. texts = data_lemmatized6. 7. # Term Document Frequency8. corpus = [id2word.doc2bow(text) for text in texts]9. 10. # View11. print(corpus[:1])


          建立主題模型

          現(xiàn)在我們準(zhǔn)備進(jìn)入核心步驟,使用LDA進(jìn)行主題建模。讓我們開(kāi)始建立模型。我們將建立20個(gè)不同主題的LDA模型,其中每個(gè)主題都是關(guān)鍵字的組合,每個(gè)關(guān)鍵字在主題中都具有一定的權(quán)重(weightage)。

          一些參數(shù)的解釋如下:

          • num_topics —需要預(yù)先定義的主題數(shù)量;

          • chunksize — 每個(gè)訓(xùn)練塊(training chunk)中要使用的文檔數(shù)量;

          • alpha — 影響主題稀疏性的超參數(shù);

          • passess — 訓(xùn)練評(píng)估的總數(shù)。


          1. # Build LDA model2. lda_model = gensim.models.ldamodel.LdaModel(corpus=corpus,3.                                            id2word=id2word,4.                                            num_topics=20, 5.                                            random_state=100,6.                                            update_every=1,7.                                            chunksize=100,8.                                            passes=10,9.                                            alpha='auto',10.                                            per_word_topics=True)
           
          查看LDA模型中的主題
           
          我們可以可視化每個(gè)主題的關(guān)鍵詞和每個(gè)關(guān)鍵詞的權(quán)重(重要性)。

          1. # Print the Keyword in the 10 topics2. pprint(lda_model.print_topics())3. doc_lda = lda_model[corpus]


          計(jì)算模型困惑度(Perplexity)和一致性分?jǐn)?shù)(Coherence Score)

          模型困惑度是對(duì)概率分布或概率模型預(yù)測(cè)樣本好壞的一種度量。主題一致性通過(guò)測(cè)量主題中得分高的單詞之間的語(yǔ)義相似度來(lái)衡量單個(gè)主題的得分。

          簡(jiǎn)而言之,它們提供了一種方便的方法來(lái)判斷一個(gè)給定的主題模型有多好。
          1. # Compute Perplexity2. print('\nPerplexity: ', lda_model.log_perplexity(corpus))  # a measure of how good the model is. lower the better.3. 4. # Compute Coherence Score5. coherence_model_lda = CoherenceModel(model=lda_model, texts=data_lemmatized, dictionary=id2word, coherence='c_v')6. coherence_lda = coherence_model_lda.get_coherence()7. print('\nCoherence Score: ', coherence_lda)


          可視化主題-關(guān)鍵詞

          現(xiàn)在,我們可以檢查生成的主題和相關(guān)的關(guān)鍵詞。最好的方法是使用pyLDAvis可視化我們的模型。

          pyLDAvis旨在幫助用戶(hù)在一個(gè)適合文本數(shù)據(jù)語(yǔ)料庫(kù)的主題模型中解釋主題。它從擬合好的的線(xiàn)性判別分析主題模型(LDA)中提取信息,以實(shí)現(xiàn)基于網(wǎng)絡(luò)的交互式可視化。

          1. # Visualize the topics2. pyLDAvis.enable_notebook()3. vis = pyLDAvis.gensim.prepare(lda_model, corpus, id2word)4. vis



          至此,我們成功建立了一個(gè)可觀的主題模型!

          簡(jiǎn)要地解釋一下結(jié)果:左手邊的每個(gè)氣泡代表一個(gè)話(huà)題。氣泡越大,該主題就越盛行。根據(jù)經(jīng)驗(yàn),一個(gè)好的主題模型會(huì)有大的、不重疊的氣泡。

          我們也可以點(diǎn)擊右邊的側(cè)邊工具條,以調(diào)整阿爾法(alpha)參數(shù)。

          結(jié)語(yǔ)


          主題建模是自然語(yǔ)言處理的主要應(yīng)用之一。本文的目的是解釋什么是主題建模,以及如何在實(shí)際使用中實(shí)現(xiàn)潛在狄利克雷分配(LDA)模型。


          為此,我們深入研究了LDA的原理,使用Gensim包中的LDA構(gòu)建了一個(gè)基礎(chǔ)的主題模型,并使用pyLDAvis對(duì)主題進(jìn)行了可視化。

          希望您喜歡該文并有所收獲。


          References:


          Jelodar, H., Wang, Y., Yuan, C. et al. Latent Dirichlet allocation (LDA) and topic modeling: models, applications, a survey. Multimed Tools Appl 78, 15169–15211 (2019). https://doi.org/10.1007/s11042-018-6894-4
          https://jovian.ai/outlink?url=https%3A%2F%2Fdoi.org%2F10.1007%2Fs11042-018-6894-4
          D. Sarkar, Text Analytics with Python. A Practical Real-World Approach to Gaining Actionable Insights from Your Data
          https://www.machinelearningplus.com/nlp/topic-modeling-gensim-python/
          https://jovian.ai/outlink?url=https%3A%2F%2Fwww.machinelearningplus.com%2Fnlp%2Ftopic-modeling-gensim-python%2F
          https://towardsdatascience.com/topic-modelling-in-python-with-nltk-and-gensim-4ef03213cd21
          https://jovian.ai/outlink?url=https%3A%2F%2Ftowardsdatascience.com%2Ftopic-modelling-in-python-with-nltk-and-gensim-4ef03213cd21
          https://towardsdatascience.com/end-to-end-topic-modeling-in-python-latent-dirichlet-allocation-lda-35ce4ed6b3e0
          https://jovian.ai/outlink?url=https%3A%2F%2Ftowardsdatascience.com%2Fend-to-end-topic-modeling-in-python-latent-dirichlet-allocation-lda-35ce4ed6b3e0
          https://towardsdatascience.com/latent-dirichlet-allocation-lda-9d1cd064ffa2
          https://towardsdatascience.com/light-on-math-machine-learning-intuitive-guide-to-latent-dirichlet-allocation-437c81220158
          http://blog.echen.me/2011/08/22/introduction-to-latent-dirichlet-allocation/


          編輯:王菁

          校對(duì):林亦霖

          譯者簡(jiǎn)介

          劉思婧,清華大學(xué)新聞系研一在讀,數(shù)據(jù)傳播方向。文理兼愛(ài),有點(diǎn)小情懷的數(shù)據(jù)愛(ài)好者。希望結(jié)識(shí)更多不同專(zhuān)業(yè)、不同專(zhuān)長(zhǎng)的伙伴,拓寬眼界、優(yōu)化思維、日日自新。

          翻譯組招募信息

          工作內(nèi)容:需要一顆細(xì)致的心,將選取好的外文文章翻譯成流暢的中文。如果你是數(shù)據(jù)科學(xué)/統(tǒng)計(jì)學(xué)/計(jì)算機(jī)類(lèi)的留學(xué)生,或在海外從事相關(guān)工作,或?qū)ψ约和庹Z(yǔ)水平有信心的朋友歡迎加入翻譯小組。

          你能得到:定期的翻譯培訓(xùn)提高志愿者的翻譯水平,提高對(duì)于數(shù)據(jù)科學(xué)前沿的認(rèn)知,海外的朋友可以和國(guó)內(nèi)技術(shù)應(yīng)用發(fā)展保持聯(lián)系,THU數(shù)據(jù)派產(chǎn)學(xué)研的背景為志愿者帶來(lái)好的發(fā)展機(jī)遇。

          其他福利:來(lái)自于名企的數(shù)據(jù)科學(xué)工作者,北大清華以及海外等名校學(xué)生他們都將成為你在翻譯小組的伙伴。


          點(diǎn)擊文末“閱讀原文”加入數(shù)據(jù)派團(tuán)隊(duì)~



          轉(zhuǎn)載須知

          如需轉(zhuǎn)載,請(qǐng)?jiān)陂_(kāi)篇顯著位置注明作者和出處(轉(zhuǎn)自:數(shù)據(jù)派ID:DatapiTHU),并在文章結(jié)尾放置數(shù)據(jù)派醒目二維碼。有原創(chuàng)標(biāo)識(shí)文章,請(qǐng)發(fā)送【文章名稱(chēng)-待授權(quán)公眾號(hào)名稱(chēng)及ID】至聯(lián)系郵箱,申請(qǐng)白名單授權(quán)并按要求編輯。

          發(fā)布后請(qǐng)將鏈接反饋至聯(lián)系郵箱(見(jiàn)下方)。未經(jīng)許可的轉(zhuǎn)載以及改編者,我們將依法追究其法律責(zé)任。



          點(diǎn)擊“閱讀原文”擁抱組織



          瀏覽 74
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          評(píng)論
          圖片
          表情
          推薦
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  爱搞搞就爱搞 | 豆花视频网站在线观看 | 草逼123 | www.大香蕉在线 | 午夜gogo |