Python Gensim LDA主题模型:文本分析,主题数选择及可视化
以下是使用 Python 的 Gensim 库实现的 LDA 主题模型代码,用于对 txt 文件进行分析,包括选取最优主题数和可视化结果:
import os
import re
import nltk
import gensim
import pyLDAvis.gensim
from gensim import corpora, models
from nltk.corpus import stopwords
# 加载停用词
nltk.download('stopwords')
stop_words = stopwords.words('english')
# 从 txt 文件加载数据
def load_txt(file_path):
with open(file_path, 'r') as f:
data = f.read()
return data
# 预处理数据
def preprocess_data(data):
# 去除标点和数字
data = re.sub('[^a-zA-Z]', ' ', data)
# 转换为小写
data = data.lower()
# 分割成词语
words = data.split()
# 去除停用词
words = [word for word in words if word not in stop_words]
# 词形还原
lemmatizer = nltk.WordNetLemmatizer()
words = [lemmatizer.lemmatize(word) for word in words]
# 创建二元组
bigram = nltk.bigrams(words)
words = [' '.join(bg) for bg in bigram]
return words
# 加载并预处理数据
file_path = 'data.txt'
data = load_txt(file_path)
words = preprocess_data(data)
# 创建字典和语料库
dictionary = corpora.Dictionary([words])
corpus = [dictionary.doc2bow(words)]
# 查找最佳主题数
num_topics = range(2, 10)
perplexities = []
for num in num_topics:
lda_model = models.LdaModel(corpus=corpus, id2word=dictionary, num_topics=num, passes=10)
perplexity = lda_model.log_perplexity(corpus)
perplexities.append(perplexity)
# 绘制困惑度曲线
import matplotlib.pyplot as plt
plt.plot(num_topics, perplexities)
plt.xlabel('主题数')
plt.ylabel('困惑度')
plt.show()
# 使用最佳主题数训练 LDA 模型
num_topics = 4
lda_model = models.LdaModel(corpus=corpus, id2word=dictionary, num_topics=num_topics, passes=10)
# 可视化主题
vis = pyLDAvis.gensim.prepare(lda_model, corpus, dictionary)
pyLDAvis.display(vis)
这段代码首先加载了 NLTK 库的停用词和数据文件,然后使用正则表达式进行数据预处理,包括去除标点、数字、转换为小写、去除停用词、词形还原和创建二元组。接着,使用 Gensim 库的 Dictionary 和 corpus 对象创建字典和语料库。然后,使用循环找到最佳主题数,将每个主题的困惑度保存在 perplexities 列表中,并可视化结果。选取最优主题数后,使用 Gensim 库的 LdaModel 对象训练 LDA 主题模型。最后,使用 pyLDAvis 库可视化结果。
原文地址: https://www.cveoy.top/t/topic/n6tl 著作权归作者所有。请勿转载和采集!