[python]LDA模型使用流程及代码

本文介绍了Python中使用LDA进行主题模型构建的详细流程,包括数据预处理、去除停用词、构建LDA模型、使用pyLDAvis进行可视化,以及如何通过困惑度和一致性得分确定最佳主题个数。
摘要由CSDN通过智能技术生成

目录

数据预处理

去除停用词

构建LDA模型

可视化——pyLDAvis

 主题个数确认

困惑度计算

一致性得分


数据预处理

该步骤可自行处理,用excel也好,用python也罢,只要将待分析文本处理为csv或txt存储格式即可。注意:一条文本占一行

例如感想.txt:

我喜欢吃汉堡

小明喜欢吃螺蛳粉

螺蛳粉外卖好贵

以上句子来源于吃完一个汉堡还想再点碗螺蛳粉,但外卖好贵从而选择放弃的我

去除停用词

import re
import jieba as jb
def stopwordslist(filepath):
    stopwords = [line.strip() for line in open(filepath, 'r', encoding='utf-8').readlines()]
    return stopwords

# 对句子进行分词
def seg_sentence(sentence):
    sentence = re.sub(u'[0-9\.]+', u'', sentence)
    #jb.add_word('词汇')		# 这里是加入自定义的词来补充jieba词典
    sentence_seged = jb.cut(sentence.strip())
    stopwords = stopwordslist('自己搜来的停用词表.txt')  # 这里加载停用词的路径
    outstr = ''
    for word in sentence_seged:
        if word not in stopwords and word.__len__()>1:
            if word != '\t':
                outstr += word
                outstr += " "
    return outstr


inputs = open('感想.txt', 'r', encoding='utf-8')

outputs = open('感想分词.txt', 'w',encoding='utf-8')
for line in inputs:
    line_seg = seg_sentence(line)  # 这里的返回值是字符串
    outputs.write(line_seg + '\n')
outputs.close()
inputs.close()

该步骤生成感想分词.txt:

我 喜欢 吃 汉堡

小明 喜欢 吃 螺蛳粉

螺蛳粉 外卖 好贵

句子 来源于 吃完 一个 汉堡  再点碗 螺蛳粉 外卖 好贵  选择 放弃 

构建LDA模型

假设主题个数设为4个(num_topics的参数)

import codecs
from gensim import corpora
from gensim.models import LdaModel
from gensim.corpora import Dictionary


train = []

fp = codecs.open('感想分词.txt','r',encoding='utf8')
for line in fp:
    if line != '':
        line = line.split()
        train.append([w for w in line])

dictionary = corpora.Dictiona
确定LDA模型的最佳主题数的方法有很多,常见的方法是使用Perplexity和Coherence两种度量指标。其中,Perplexity越小,模型效果越好;Coherence越高,模型效果越好。 以下是一个使用Coherence度量指标确定LDA模型最佳主题数的Python代码示例: ```python from gensim.models.ldamodel import LdaModel from gensim.models.coherencemodel import CoherenceModel from gensim.corpora import Dictionary import matplotlib.pyplot as plt # 导入数据并生成词典 texts = [["apple", "banana", "orange", "pear", "peach"], ["dog", "cat", "bird", "fish"], ["red", "yellow", "blue", "green"]] dictionary = Dictionary(texts) corpus = [dictionary.doc2bow(text) for text in texts] # 定义函数,计算LDA模型的Coherence值 def compute_coherence_values(dictionary, corpus, texts, limit, start=2, step=2): coherence_values = [] model_list = [] for num_topics in range(start, limit, step): model = LdaModel(corpus=corpus, num_topics=num_topics, id2word=dictionary) model_list.append(model) coherence_model_lda = CoherenceModel(model=model, texts=texts, dictionary=dictionary, coherence='c_v') coherence_values.append(coherence_model_lda.get_coherence()) return model_list, coherence_values # 调用函数,计算不同主题数下的Coherence值 model_list, coherence_values = compute_coherence_values(dictionary=dictionary, corpus=corpus, texts=texts, start=2, limit=10, step=1) # 可视化Coherence值随主题数变化的趋势 x = range(2, 10, 1) plt.plot(x, coherence_values) plt.xlabel("Num Topics") plt.ylabel("Coherence score") plt.legend(("coherence_values"), loc='best') plt.show() ``` 运行以上代码,可以得到一个Coherence值随主题数变化的趋势图,从图中可以看出最佳主题数在哪个范围内。
评论 35
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值