为了计算LDA 的困惑度,费劲千辛万苦,终于有所收获,以此记录。

本篇文章主要介绍perplexity的计算方式,并未涉及过多的困惑度原理,想了解更多原理部分,请移步perplexity介绍

本文主要是对Perplexity per word进行困惑度计算,公式:

以下是实现代码(工具pycharm、Python3.7),分了三个部分

1.LDA的主题生成

from gensim import corpora, modelsdef ldamodel(num_topics):cop = open(r'D:\360MoveData\Users\admin\Desktop\copus.txt', 'r', encoding='UTF-8')train = []for line in cop.readlines():line = [word.strip() for word in line.split(' ')]train.append(line)  # list of list 格式dictionary = corpora.Dictionary(train)corpus = [dictionary.doc2bow(text) for text intrain]  # corpus里面的存储格式(0, 1), (1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1)corpora.MmCorpus.serialize('corpus.mm', corpus)lda = models.LdaModel(corpus=corpus, id2word=dictionary, random_state=1,num_topics=num_topics)  # random_state 等价于随机种子的random.seed(),使每次产生的主题一致topic_list = lda.print_topics(num_topics, 10)# print("主题的单词分布为:\n")# for topic in topic_list:#     print(topic)return lda,dictionary

2.编辑perplexity的计算函数

import math
def perplexity(ldamodel, testset, dictionary, size_dictionary, num_topics):print('the info of this ldamodel: \n')print('num of topics: %s' % num_topics))prep = 0.0prob_doc_sum = 0.0topic_word_list = [] for topic_id in range(num_topics):topic_word = ldamodel.show_topic(topic_id, size_dictionary)dic = {}for word, probability in topic_word:dic[word] = probabilitytopic_word_list.append(dic)  doc_topics_ist = []  for doc in testset:doc_topics_ist.append(ldamodel.get_document_topics(doc, minimum_probability=0))testset_word_num = 0for i in range(len(testset)):prob_doc = 0.0  # the probablity of the docdoc = testset[i]doc_word_num = 0  for word_id, num in dict(doc).items():prob_word = 0.0  doc_word_num += numword = dictionary[word_id]for topic_id in range(num_topics):# cal p(w) : p(w) = sumz(p(z)*p(w|z))prob_topic = doc_topics_ist[i][topic_id][1]prob_topic_word = topic_word_list[topic_id][word]prob_word += prob_topic * prob_topic_wordprob_doc += math.log(prob_word)  # p(d) = sum(log(p(w)))prob_doc_sum += prob_doctestset_word_num += doc_word_numprep = math.exp(-prob_doc_sum / testset_word_num)  # perplexity = exp(-sum(p(d)/sum(Nd))print("模型困惑度的值为 : %s" % prep)return prep

3.主函数入口,并作图

from gensim import corpora, models
import matplotlib.pyplot as plt
import perplexity
import lda_catchdef graph_draw(topic, perplexity):  # 做主题数与困惑度的折线图x = topicy = perplexityplt.plot(x, y, color="red", linewidth=2)plt.xlabel("Number of Topic")plt.ylabel("Perplexity")plt.show()
if __name__ == '__main__':for i in range(20,300,1): # 多少文档中抽取一篇(这里只是为了调试最优结果,可以直接设定不循环)print("抽样为"+str(i)+"时的perplexity")a=range(1,20,1) # 主题个数p=[]for num_topics in a:lda,dictionary =lda_catch.ldamodel(num_topics)corpus = corpora.MmCorpus('corpus.mm')testset = []for c in range(int(corpus.num_docs/i)):testset.append(corpus[c*i])prep = perplexity.perplexity(lda, testset, dictionary, len(dictionary.keys()), num_topics)p.append(prep)graph_draw(a,p)

最终结果:(不同训练集测试部分图)

初学者对困惑度计算的了解,若有不足请指出。

参考文献:

python下进行lda主题挖掘(三)——计算困惑度perplexity

LDA计算 perplexity(困惑度)确定主题个数(代码)相关推荐

  1. lda主题模型困惑度_主题模型(三):LDA主题个数选择

    在上一篇文章的最后,我们生成了15个模型(主题数分别从1到15),然鹅,问题来了,到底多少个主题,才是最好的主题模型呢?到底有没有可以评价一个模型好坏的标准呢?答案肯定是有的,而且还不止一个呢! 先说 ...

  2. Python中LDA 计算 perplexity来确定主题数

    转载自 https://blog.csdn.net/qq_23926575/article/details/79472742 1.LDA主题模型困惑度  这部分参照:LDA主题模型评估方法–Perpl ...

  3. Perplexity(困惑度)

    转载请注明出处,谢谢. #什么是Perplexity(困惑度)? 在信息论中,perplexity(困惑度)用来度量一个概率分布或概率模型预测样本的好坏程度.它也可以用来比较两个概率分布或概率模型.( ...

  4. 困惑度、主题一致性,lda模型找出主题相关词

    困惑度perplexity:句子的概率的倒数.如果句子的概率越大,说明这句话越符合人话的规律,即p(句子),pp困惑度越小.模型对该句子就越不困惑. 通俗一点解释下就是,困惑度表示的对于一篇文章来说, ...

  5. Perplexity困惑度解释

    引用wiki上的话 "A model of an unknown probability distribution p, may be proposed based on a trainin ...

  6. java 阶乘后几位,java阶乘计算获得结果末尾0的个数代码实现

    看到题目后,分析了下, 10的阶乘就已经很大了.计算出来再得到这个末尾的0的个数,完全不现实,即使实现了也是很麻烦的. 后来想某个数的阶乘中乘积有5结尾的数字的时候就应该在结果的末尾产生一个0. 付诸 ...

  7. BTM主题模型构建及困惑度计算

    小白一枚,有什么不对的地方请多指教. BTM主题模型主要针对短文本而言,这里实现的方法主要参考论文<A Biterm Topic Model for Short Texts>,代码在作者的 ...

  8. LDA困惑度perplexity的一些个人理解

    纠结这个问题很久了,期间主要去了gensim的google论坛,以及在StackOverflow.StackexChange用关键词topic number perplexity搜了下,得到这些很模糊 ...

  9. 困惑度 (perplexity)

    困惑度 (perplexity) 在自然语言处理中,对于一个语言模型,一般用困惑度来衡量它的好坏,困惑度越低,说明语言模型面对一句话感到困惑的程度越低,语言模型就越好. 对于LDA模型,最常用的两个评 ...

最新文章

  1. php 4 创建公共的链接数据库php文件并在其它文件引用它
  2. Django中url匹配规则的补充
  3. 快速失败(fail-fast)和安全失败(fail-safe)
  4. java邻接图_Java数据结构 - 图(邻接表存储)
  5. php遍历数组的四种方法,PHP遍历数组的常见几种方法
  6. 中南大学 oracle试卷,数据库原理期末复习(中南大学)数据库原理、技术及应用2.ppt...
  7. android+坐标类,Android Path和PathMeasure类的使用之获取圆弧上的坐标值
  8. Docker基本使用(一)
  9. oracle表数据的导出到excel文件,文件怎么导出到excel表格数据库-如何导出oracle数据库中某张表到excel...
  10. mybatis采坑之 PageHelper.startPage出现两个limit情况
  11. Windows 提示“缺少所需的 CD/DVD 驱动器设备驱动程序”
  12. 汇集各种 webservice工厂,快递,ip,天气,身份证,手机,翻译,火车时刻,股票,邮编,二维码,公交,ISBN,ICP 查询接口 API
  13. 周口女子职专计算机分为哪些专业,周口女子职业中专学校
  14. Spring 中 配置文件 加入 aspectj-autoproxy 项目报错
  15. 高老师的架构设计_隽语集(AA_0151)
  16. 《MINECRAFT我的世界 新手完全攻略(第3版)》一1.1 注册与下载
  17. 多模块项目-项目复制出现Module xx must not contain source root xx The root already belongs to module xx
  18. 偶像和粉丝关系该是什么样的?
  19. Linux释放内存及手动释放Oracle共享内存段
  20. 星战 java_星战知识之多少 -- 暗黑原力西斯(Sith)篇

热门文章

  1. day09 多态抽象类接口
  2. vm15 虚拟机安装 mac x 10.11
  3. 安卓APP保活--十种方案
  4. 怎样选择青少年护眼灯?光照柔和的学生护眼灯
  5. VMWare 虚拟机如何扩展磁盘空间并挂载到已存在的根目录
  6. 华为手机 app 安装成功 点击桌面图标无反应!!
  7. QT - 20230707
  8. Golang之轻松化解defer的温柔陷阱 1
  9. 计算机无法访问文件怎么办,电脑无法识别文件提示Windows无法打开文件怎么办...
  10. 广义OOD检测最新综述