以下是对 df.content_cutted 数据集,LDA 模型,设置最大主题数为 16,绘制主题数与困惑度曲线的代码:

from gensim.models import LdaModel
from gensim.corpora.dictionary import Dictionary
from gensim.models import CoherenceModel
import matplotlib.pyplot as plt

dictionary = Dictionary(df.content_cutted)
corpus = [dictionary.doc2bow(text) for text in df.content_cutted]

perplexity_values = []
coherence_values = []
model_list = []

for num_topics in range(1, 17):
    lda_model = LdaModel(corpus=corpus,
                         id2word=dictionary,
                         num_topics=num_topics,
                         passes=10,
                         alpha='auto',
                         eta='auto')
    model_list.append(lda_model)
    perplexity_values.append(lda_model.log_perplexity(corpus))
    coherence_model_lda = CoherenceModel(model=lda_model, texts=df.content_cutted, dictionary=dictionary, coherence='c_v')
    coherence_values.append(coherence_model_lda.get_coherence())

# Plotting
x = range(1, 17)
plt.plot(x, perplexity_values)
plt.xlabel('Number of Topics')
plt.ylabel('Perplexity score')
plt.show()

plt.plot(x, coherence_values)
plt.xlabel('Number of Topics')
plt.ylabel('Coherence score')
plt.show()

这段代码会绘制出两张图,第一张图是主题数与困惑度之间的曲线,第二张图是主题数与一致性得分之间的曲线。可以根据这两张图来确定最佳的主题数。

LDA 主题建模:使用困惑度和一致性得分确定最佳主题数

原文地址: https://www.cveoy.top/t/topic/m0Og 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录