1.LDAの全体的な考え方
LDA トピック モデルは主にドキュメントのトピック分布を推測するために使用され、ドキュメント セット内の各ドキュメントのトピックを確率分布の形式で与え、トピックに基づいてトピック クラスタリングやテキスト分類を実行できます。LDA トピック モデルはドキュメント内の単語の順序を考慮せず、通常はバッグ オブ ワード機能を使用してドキュメントを表現します。
LDA モデルは、トピックは語彙分布によって表現でき、記事はトピック分布によって表現できると考えています。
例えば、「食」と「美容」という2つのテーマがあります。LDA は、次の 2 つのトピックを語彙分布で表現できると述べています。
{パン:0.4、ホットポット:0.5、アイブロウペンシル:0.03、チーク:0.07}
{アイブロウペンシル:0.4、チーク:0.5、パン:0.03、ホットポット:0.07}
同様に、2 つの記事について、LDA はその記事が次のようなトピック分布で表現できると考えています。
『ビューティーダイアリー』{美しさ:0.8、食べ物:0.1、その他:0.1}
「食の探求」{食:0.8、美容:0.1、その他:0.1}
したがって、記事を生成したい場合は、まず上にある特定のトピックを一定の確率で選択し、次にそのトピックの下にある特定の単語を一定の確率で選択し、この 2 つの手順を繰り返すことで最終的な記事を生成できます。
文書集合内の各文書のトピックは確率分布の形で与えられ、いくつかの文書を分析してトピック(分布)を抽出した後、トピック(分布)に応じてトピッククラスタリングやテキスト分類を行うことができます。
これは典型的なバッグオブワード モデルです。つまり、文書は単語のグループで構成されており、単語間に順序関係はありません。さらに、ドキュメントには複数のトピックを含めることができ、ドキュメント内の各単語はトピックの 1 つによって生成されます。
2. 書類の作成方法
LDA モデルでは、ドキュメントは次のように生成されます。
- ディリクレ分布アルファからサンプリングしてドキュメント i のトピック分布 θi を生成する
- トピックの多項分布 θi からサンプリングすることにより、文書 i の j 番目の単語のトピック zij を生成します
- トピック zij に対応する単語分布 φzij を生成するためのディリクレ分布ベータからのサンプリング
- 単語の多項分布 φzij からのサンプリングにより、最終的に単語 wij が生成されます。
このうち、ベータ様分布は二項分布の共役事前確率分布であり、ディリクレ分布は多項分布の共役事前確率分布です。
特定の数式ロジックのリファレンス:
LDA トピックに関する一般的な理解 model_lda model_v_JULY_v のブログ-CSDN ブログ
2、Pythonの実装
import gensim
from gensim import corpora
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
import warnings
warnings.filterwarnings('ignore') # To ignore all warnings that arise here to enhance clarity
from gensim.models.coherencemodel import CoherenceModel
from gensim.models.ldamodel import LdaModel
# 准备数据
PATH = "E:/data/output.csv"
file_object2=open(PATH,encoding = 'utf-8',errors = 'ignore').read().split('\n') #一行行的读取内容
data_set=[] #建立存储分词的列表
for i in range(len(file_object2)):
result=[]
seg_list = file_object2[i].split()
for w in seg_list :#读取每一行分词
result.append(w)
data_set.append(result)
print(data_set)
dictionary = corpora.Dictionary(data_set) # 构建 document-term matrix
corpus = [dictionary.doc2bow(text) for text in data_set]
#Lda = gensim.models.ldamodel.LdaModel # 创建LDA对象
#计算困惑度
def perplexity(num_topics):
ldamodel = LdaModel(corpus, num_topics=num_topics, id2word = dictionary, passes=30)
print(ldamodel.print_topics(num_topics=num_topics, num_words=15))
print(ldamodel.log_perplexity(corpus))
return ldamodel.log_perplexity(corpus)
#计算coherence
def coherence(num_topics):
ldamodel = LdaModel(corpus, num_topics=num_topics, id2word = dictionary, passes=30,random_state = 1)
print(ldamodel.print_topics(num_topics=num_topics, num_words=10))
ldacm = CoherenceModel(model=ldamodel, texts=data_set, dictionary=dictionary, coherence='c_v')
print(ldacm.get_coherence())
return ldacm.get_coherence()
# 绘制困惑度折线图
x = range(1,15)
# z = [perplexity(i) for i in x]
y = [coherence(i) for i in x]
plt.plot(x, y)
plt.xlabel('主题数目')
plt.ylabel('coherence大小')
plt.rcParams['font.sans-serif']=['SimHei']
matplotlib.rcParams['axes.unicode_minus']=False
plt.title('主题-coherence变化情况')
plt.show()
from gensim.models import LdaModel
import pandas as pd
from gensim.corpora import Dictionary
from gensim import corpora, models
import csv
# 准备数据
PATH = "E:/data/output1.csv"
file_object2=open(PATH,encoding = 'utf-8',errors = 'ignore').read().split('\n') #一行行的读取内容
data_set=[] #建立存储分词的列表
for i in range(len(file_object2)):
result=[]
seg_list = file_object2[i].split()
for w in seg_list :#读取每一行分词
result.append(w)
data_set.append(result)
dictionary = corpora.Dictionary(data_set) # 构建 document-term matrix
corpus = [dictionary.doc2bow(text) for text in data_set]
lda = LdaModel(corpus=corpus, id2word=dictionary, num_topics=5, passes = 30,random_state=1)
topic_list=lda.print_topics()
print(topic_list)
result_list =[]
for i in lda.get_document_topics(corpus)[:]:
listj=[]
for j in i:
listj.append(j[1])
bz=listj.index(max(listj))
result_list.append(i[bz][0])
print(result_list)
import pyLDAvis.gensim
pyLDAvis.enable_notebook()
data = pyLDAvis.gensim.prepare(lda, corpus, dictionary)
pyLDAvis.save_html(data, 'E:/data/topic.html')