LDA主题模型绘制困惑度(perplexity)-主题数曲线——python

主题建模作为一种基于机器学习的文本内容分析技术,一般用于推断文本文档中隐藏主题的技术。很多研究使用了基于Latent Dirichlet Allocation (LDA)的主题建模算法来处理大规模文档并识别潜在主题。LDA主题模型已经在多个研究领域得到应用,且都有着不俗表现。

LDA作为一种无监督机器学习技术,利用词袋方法识别隐藏在大规模文档集或语料库中的主题信息。LDA模型可挖掘出文档集或语料库中的潜在主题信息,并采用词 袋构建模型,在不考虑词汇出现顺序的情况下,构成“文档-主题分布”和“主题-词分布”。

 对于LDA模型,最常用的两个评价方法困惑度(Perplexity)、一致性(coherence)。本文先介绍如何用python对个含有多条文本的文件进行LDA主题建模,并绘制主题-困惑度曲线来得到最好的主题数。

import gensim
from gensim import corpora, models
import matplotlib.pyplot as plt
import matplotlib
from nltk.tokenize import RegexpTokenizer
from nltk.stem.porter import PorterStemmer



 # 准备数据
PATH = "C:/Users/out.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 = Lda(corpus, num_topics=num_topics, id2word = dictionary, passes=50)  #passes为迭代次数,次数越多越精准
    print(ldamodel.print_topics(num_topics=num_topics, num_words=7))  #num_words为每个主题下的词语数量
    print(ldamodel.log_perplexity(corpus))
    return ldamodel.log_perplexity(corpus)

# 绘制困惑度折线图
x = range(1,30)  #主题范围数量
y = [perplexity(i) for i in x]
plt.plot(x, y)
plt.xlabel('主题数目')
plt.ylabel('困惑度大小')
plt.rcParams['font.sans-serif']=['SimHei']
matplotlib.rcParams['axes.unicode_minus']=False
plt.title('主题-困惑度变化情况')
plt.show()

我的代码最后得到的图如下:

之后的文章我还会介绍如何用coherence来评价LDA主题模型。

猜你喜欢

转载自blog.csdn.net/weixin_41168304/article/details/121758203
今日推荐