对dpexcel类型数据集 lda模型设置最大主题数为16绘制主题数与困惑度曲线的代码
以下是对dpexcel类型数据集进行LDA模型的主题数与困惑度曲线的绘制代码:
import gensim
import gensim.corpora as corpora
from gensim.models import CoherenceModel
import matplotlib.pyplot as plt
# 导入数据集
data = pd.read_csv('dpexcel.csv')
# 将文本数据处理成列表形式
texts = [[word for word in doc.split()] for doc in data['text']]
# 构建词典
id2word = corpora.Dictionary(texts)
# 构建文档-词频矩阵
corpus = [id2word.doc2bow(text) for text in texts]
# 定义计算困惑度的函数
def compute_perplexity(corpus, dictionary, num_topics):
lda_model = gensim.models.ldamodel.LdaModel(corpus=corpus,
id2word=dictionary,
num_topics=num_topics,
random_state=42,
update_every=1,
chunksize=100,
passes=10,
alpha='auto',
per_word_topics=True)
perplexity = lda_model.log_perplexity(corpus)
return perplexity
# 设置主题数范围
min_topics = 2
max_topics = 16
step_size = 1
# 计算每个主题数的困惑度
topics_range = range(min_topics, max_topics+1, step_size)
perplexity_scores = []
for k in topics_range:
score = compute_perplexity(corpus, id2word, k)
perplexity_scores.append(score)
# 绘制主题数与困惑度曲线图
plt.plot(topics_range, perplexity_scores, '-o', color='blue')
plt.xlabel('Number of Topics')
plt.ylabel('Perplexity Score')
plt.grid(alpha=0.2)
plt.show()
运行代码后,将会得到一个主题数与困惑度曲线的图像。根据图像,可以选择一个合适的主题数来训练LDA模型。
原文地址: http://www.cveoy.top/t/topic/bw1H 著作权归作者所有。请勿转载和采集!