主题模型LDA教程:主题数选取 困惑度perplexing

LDA主题数

LDA作为一种无监督学习方法,类似于k-means聚类算法,需要给定超参数主题数K,但如何评价主题数的优劣并无定论,一般采取人为干预、主题困惑度preplexing和主题一致性得分coherence score,本文介绍困惑度。

困惑度

在信息论中,perplexity(困惑度)用来度量一个概率分布或概率模型预测样本的好坏程度。它也可以用来比较两个概率分布或概率模型。低困惑度的概率分布模型或概率模型能更好地预测样本。

1.概率分布的困惑度

定义离散概率分布的困惑度如下:
2 H ( p ) = 2 −

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
首先,你需要安装并导入 gensim 库和 pyLDAvis 库。然后,你可以按照以下步骤进行 LDA 主题分类: 1. 加载语料库并创建字典和词袋模型: ```python from gensim import corpora, models # 加载语料库 corpus = corpora.TextCorpus('path/to/corpus') # 创建字典 dictionary = corpus.dictionary # 创建词袋模型 bow_corpus = [dictionary.doc2bow(doc) for doc in corpus] ``` 2. 训练 LDA 模型并计算困惑度: ```python from gensim.models import CoherenceModel, LdaModel # 训练 LDA 模型 model_list = [] for num_topics in range(2, 11): lda_model = LdaModel(bow_corpus, num_topics=num_topics, id2word=dictionary) model_list.append(lda_model) # 计算困惑度 coherence_scores = [] for model in model_list: coherence_model = CoherenceModel(model=model, corpus=bow_corpus, coherence='u_mass') coherence_score = coherence_model.get_coherence() coherence_scores.append(coherence_score) ``` 3. 找到困惑度最低的主题: ```python import matplotlib.pyplot as plt # 绘制困惑度主题变化的曲线 num_topics = range(2, 11) plt.plot(num_topics, coherence_scores) plt.xlabel("Number of Topics") plt.ylabel("Coherence score") plt.show() # 找到困惑度最低的主题 best_num_topics = num_topics[coherence_scores.index(min(coherence_scores))] print("Best number of topics:", best_num_topics) ``` 4. 使用最优主题重新训练 LDA 模型并得到每篇文档的概率生成分布: ```python # 训练最优主题LDA 模型 best_lda_model = LdaModel(bow_corpus, num_topics=best_num_topics, id2word=dictionary) # 得到每篇文档的概率生成分布 doc_topic_distribution = [] for doc in bow_corpus: doc_topic_distribution.append(best_lda_model.get_document_topics(doc)) ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Cachel wood

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值