用python计算lda语言模型的困惑度并作图.docx

用python计算lda语言模型的困惑度并作图.docx

  1. 1、本文档共3页,可阅读全部内容。
  2. 2、有哪些信誉好的足球投注网站(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
  3. 3、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载
  4. 4、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
?python计算lda语?模型的困惑度并作图 困惑度?般在?然语?处理中?来衡量训练出的语?模型的好坏。在?LDA做主题和词聚类时,?章中的公式为: perplexity=exp^{ - (∑log(p(w))) / (N) } 其中,P(W)是指的测试集中出现的每?个词的概率,具体到LDA的模型中就是P(w)=∑z p(z|d)*p(w|z)【z,d分别指训练过的主题和测试集的各篇?档】。分母的N是测试集中出现的所有词,或者说是测试集的总长度,不排重。 因?python程序代码块需要包括?个??: 1.对训练的LDA模型,将Topic-word分布?档转换成字典,?便查询概率,即计算perplexity的分?2.统计测试集长度,即计算perplexity的分母 计算困惑度 对于不同的Topic数量的模型,计算的困惑度,画折线图。python代码如下: 1 # -*- coding: UTF-8-*- 2 import numpy import math import string import matplotlib.pyplot as plt 6 import re 7 def dictionary_found(wordlist): #对模型训练出来的词转换成?个词为KEY,概率为值的字典。 word_dictionary1={} for i in xrange(len(wordlist)): 11 if i%2==0: if word_dictionary1.has_key(wordlist[i])==True: word_probability=word_dictionary1.get(wordlist[i]) word_probability=float(word_probability)+float(wordlist[i+1]) word_dictionary1.update({wordlist[i]:word_probability}) else: word_dictionary1.update({wordlist[i]:wordlist[i+1]}) else: pass return word_dictionary1 21 def look_into_dic(dictionary,testset): #对于测试集的每?个词,在字典中查找其概率。 Calculates the TF-list for perplexity frequency=[] letter_list=[] 26 a=0.0 for letter in testset.split(): if letter not in letter_list: letter_list.append(letter) letter_frequency=(dictionary.get(letter)) frequency.append(letter_frequency) else: pass for each in frequency: if each!=None: a+=float(each) else: pass return a 40 41 def f_testset_word_count(testset): #测试集的词数统计 reture the sum of words in testset which is the denominator of the formula of Perplexity testset_clean=testset.split() return (len(testset_clean)-testset.count(\n)) 46 def f_perplexity(word_frequency,word_count): #计算困惑度 Search the probability of each word in dictionary Calculates the perplexity of the LDA model for every parameter T duishu=-math.log(word_frequency) kuohaoli=duishu/word_count perplexity=math.exp(kuohaoli) return perplexity 54 def graph_draw(topic,perplexity): #做主题数与困惑度的折线图 x=topic y=perplexity plt.plot(x,y,color=red,linewidth=2) plt.xlabel(Number of Topic) plt.ylabel(Perplexity) plt.show() 62 63 topic=[

文档评论(0)

暗伤 + 关注
实名认证
内容提供者

该用户很懒,什么也没介绍

1亿VIP精品文档

相关文档