Python_LDA实现方法详解
作者:liuph_ 发布时间:2021-06-29 11:43:18
LDA(Latent Dirichlet allocation)模型是一种常用而用途广泛地概率主题模型。其实现一般通过Variational inference和Gibbs Samping实现。作者在提出LDA模型时给出了其变分推理的C源码(后续贴出C++改编的类),这里贴出基于Python的第三方模块改写的LDA类及实现。
#coding:utf-8
import numpy as np
import lda
import lda.datasets
import jieba
import codecs
class LDA_v20161130():
def __init__(self, topics=2):
self.n_topic = topics
self.corpus = None
self.vocab = None
self.ppCountMatrix = None
self.stop_words = [u',', u'。', u'、', u'(', u')', u'·', u'!', u' ', u':', u'“', u'”', u'\n']
self.model = None
def loadCorpusFromFile(self, fn):
# 中文分词
f = open(fn, 'r')
text = f.readlines()
text = r' '.join(text)
seg_generator = jieba.cut(text)
seg_list = [i for i in seg_generator if i not in self.stop_words]
seg_list = r' '.join(seg_list)
# 切割统计所有出现的词纳入词典
seglist = seg_list.split(" ")
self.vocab = []
for word in seglist:
if (word != u' ' and word not in self.vocab):
self.vocab.append(word)
CountMatrix = []
f.seek(0, 0)
# 统计每个文档中出现的词频
for line in f:
# 置零
count = np.zeros(len(self.vocab),dtype=np.int)
text = line.strip()
# 但还是要先分词
seg_generator = jieba.cut(text)
seg_list = [i for i in seg_generator if i not in self.stop_words]
seg_list = r' '.join(seg_list)
seglist = seg_list.split(" ")
# 查询词典中的词出现的词频
for word in seglist:
if word in self.vocab:
count[self.vocab.index(word)] += 1
CountMatrix.append(count)
f.close()
#self.ppCountMatrix = (len(CountMatrix), len(self.vocab))
self.ppCountMatrix = np.array(CountMatrix)
print "load corpus from %s success!"%fn
def setStopWords(self, word_list):
self.stop_words = word_list
def fitModel(self, n_iter = 1500, _alpha = 0.1, _eta = 0.01):
self.model = lda.LDA(n_topics=self.n_topic, n_iter=n_iter, alpha=_alpha, eta= _eta, random_state= 1)
self.model.fit(self.ppCountMatrix)
def printTopic_Word(self, n_top_word = 8):
for i, topic_dist in enumerate(self.model.topic_word_):
topic_words = np.array(self.vocab)[np.argsort(topic_dist)][:-(n_top_word + 1):-1]
print "Topic:",i,"\t",
for word in topic_words:
print word,
def printDoc_Topic(self):
for i in range(len(self.ppCountMatrix)):
print ("Doc %d:((top topic:%s) topic distribution:%s)"%(i, self.model.doc_topic_[i].argmax(),self.model.doc_topic_[i]))
def printVocabulary(self):
print "vocabulary:"
for word in self.vocab:
print word,
def saveVocabulary(self, fn):
f = codecs.open(fn, 'w', 'utf-8')
for word in self.vocab:
f.write("%s\n"%word)
f.close()
def saveTopic_Words(self, fn, n_top_word = -1):
if n_top_word==-1:
n_top_word = len(self.vocab)
f = codecs.open(fn, 'w', 'utf-8')
for i, topic_dist in enumerate(self.model.topic_word_):
topic_words = np.array(self.vocab)[np.argsort(topic_dist)][:-(n_top_word + 1):-1]
f.write( "Topic:%d\t"%i)
for word in topic_words:
f.write("%s "%word)
f.write("\n")
f.close()
def saveDoc_Topic(self, fn):
f = codecs.open(fn, 'w', 'utf-8')
for i in range(len(self.ppCountMatrix)):
f.write("Doc %d:((top topic:%s) topic distribution:%s)\n" % (i, self.model.doc_topic_[i].argmax(), self.model.doc_topic_[i]))
f.close()
算法实现demo:
例如,抓取BBC川普当选的新闻作为语料,输入以下代码:
if __name__=="__main__":
_lda = LDA_v20161130(topics=20)
stop = [u'!', u'@', u'#', u',',u'.',u'/',u';',u' ',u'[',u']',u'$',u'%',u'^',u'&',u'*',u'(',u')',
u'"',u':',u'<',u'>',u'?',u'{',u'}',u'=',u'+',u'_',u'-',u'''''']
_lda.setStopWords(stop)
_lda.loadCorpusFromFile(u'C:\\Users\Administrator\Desktop\\BBC.txt')
_lda.fitModel(n_iter=1500)
_lda.printTopic_Word(n_top_word=10)
_lda.printDoc_Topic()
_lda.saveVocabulary(u'C:\\Users\Administrator\Desktop\\vocab.txt')
_lda.saveTopic_Words(u'C:\\Users\Administrator\Desktop\\topic_word.txt')
_lda.saveDoc_Topic(u'C:\\Users\Administrator\Desktop\\doc_topic.txt')
因为语料全部为英文,因此这里的stop_words全部设置为英文符号,主题设置20个,迭代1500次。结果显示,文档148篇,词典1347词,总词数4174,在i3的电脑上运行17s。
Topic_words部分输出如下:
Topic: 0
to will and of he be trumps the what policy
Topic: 1 he would in said not no with mr this but
Topic: 2 for or can some whether have change health obamacare insurance
Topic: 3 the to that president as of us also first all
Topic: 4 trump to when with now were republican mr office presidential
Topic: 5 the his trump from uk who president to american house
Topic: 6 a to that was it by issue vote while marriage
Topic: 7 the to of an are they which by could from
Topic: 8 of the states one votes planned won two new clinton
Topic: 9 in us a use for obama law entry new interview
Topic: 10 and on immigration has that there website vetting action given
Doc_Topic部分输出如下:
Doc 0:((top topic:4) topic distribution:[ 0.02972973 0.0027027 0.0027027 0.16486486 0.32702703 0.19189189
0.0027027 0.0027027 0.02972973 0.0027027 0.02972973 0.0027027
0.0027027 0.0027027 0.02972973 0.0027027 0.02972973 0.0027027
0.13783784 0.0027027 ])
Doc 1:((top topic:18) topic distribution:[ 0.21 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.11 0.01 0.01 0.01
0.01 0.01 0.01 0.01 0.01 0.01 0.31 0.21])
Doc 2:((top topic:18) topic distribution:[ 0.02075472 0.00188679 0.03962264 0.00188679 0.00188679 0.00188679
0.00188679 0.15283019 0.00188679 0.02075472 0.00188679 0.24716981
0.00188679 0.07735849 0.00188679 0.00188679 0.00188679 0.00188679
0.41698113 0.00188679])
当然,对于英文语料,需要排除大部分的虚词以及常用无意义词,例如it, this, there, that...在实际操作中,需要合理地设置参数。
换中文语料尝试,采用习大大就卡斯特罗逝世发表的吊唁文章和朴槿惠辞职的新闻。
Topic: 0
的 同志 和 人民 卡斯特罗 菲德尔 古巴 他 了 我
Topic: 1 在 朴槿惠 向 表示 总统 对 将 的 月 国民
Doc 0:((top topic:0) topic distribution:[ 0.91714123 0.08285877])
Doc 1:((top topic:1) topic distribution:[ 0.09200666 0.90799334])
还是存在一些虚词,例如“的”,“和”,“了”,“对”等词的干扰,但是大致来说,两则新闻的主题分布很明显,效果还不赖。
来源:http://blog.csdn.net/liuph_/article/details/53406609
![](https://www.aspxhome.com/images/zang.png)
![](https://www.aspxhome.com/images/jiucuo.png)
猜你喜欢
- 前言二维码现在是随处度可以看到,买东西,支付,添加好友只要你扫一扫就能完成整个工作,简单且方便。所以利用这个新春佳节做一个带着新春祝福的二维
- CSSer与其他IT职位一样,在找工作的时候,都会面临着面试官提出的问题,或者给出的试卷。一、超链接点击过后hover样式就不出现的问题?被
- MySQL目前不支持列的Default 为函数的形式,如达到你某列的默认值为当前更新日期与时间的功能,你可以使用TIMESTAMP列类型下面
- 本文实例讲述了python开发之基于thread线程搜索本地文件的方法。分享给大家供大家参考,具体如下:先来看看运行效果图:利用多个线程处理
- 传统来说,大家在CSS中使用的颜色要么是16进制格式,要么是rgb格式,就像rgb(171,205,239)。CSS3带来了一些新的处理颜色
- 先按照下面的表结构创建mysql_order_by_test数据表,我们用实例一点一点告诉你,MySQL order by的用法。ORDER
- 现在介绍加速网页图形显示速度的六种方法,为你解决这个难题。其最基本的宗旨就是,让你用买鱼的价钱,品尝到熊掌的美味和营养。 1.首先要确定图像
- IIS上设置301 跳转相信大家都会,只要在网站-属性-主目录里 选择重定向URL就行了,这样整站就跳转到目标站点了,但是有个问
- 教程使用的版本是2019.1新版本安装激活可以参考此篇教程,通用版!一、go安装1、建议去go语言中文网下载,网址:https://stud
- 导言:本文一步一步手把手教你打造一个极酷的三层分离的标准滑动门导航菜单,从思路、原理、步骤,手段可谓“无所不用其极”,即便你是菜鸟,相信你看
- 1、说明Python实现异步IO非常简单,asyncio是Python 3.4版本引入的标准库,直接内置了对异步IO的支持。asyncio的
- python实现阶乘-基础版本什么是阶乘呢?在数学运算中n!表示n的阶乘,用数学公式表示为:n!=1*2*3*....*(n-1)*n下面提
- 下面通过实例代码给大家分享Python切片操作去除字符串首尾的空格的方法,具体内容如下所示:#利用切片操作,实现一个trim()函数,去除字
- 主程序mainaddfunc.pyfrom flask import Flask, render_template, request, ur
- 昨天群里介绍了一个专门帮你PS图片的网站。吐司网。网站在图片的预览处理上有点意思。当鼠标经过图片,显示为处理过的图片。这样大家能很清晰的对比
- 摘要:利用xlrd读取excel利用xlwt写excel利用xlutils修改excel利用xlrd读取excel先需要在命令行中pip i
- 所以爱微网现在讲解先php内置函数 有大小写转换相关函数 文本html标签处理函数大小写有关函数 strtolower() strtoupp
- 异常描述有时我们的Excel有一个调整过自定义格式的日期字段:当我们用pandas读取时却是这样的效果:不管如何指定参数都无效。出现原因没有
- 项目有时要用一些Ajax的效果,因为比较简单,也就没有去用什么Ajax.net之类的东西,手写代码也就实现了。 第二天,有人反馈错
- 一、利用直方图的方式进行批量的图片缺陷检测(方法简单)二、步骤(完整代码见最后)2.1灰度转换(将原图和要检测对比的图分开灰度化)灰度化的作