Python_LDA实现方法详解


Posted in Python onOctober 25, 2017

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,
      print
  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,
    print
  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])

还是存在一些虚词,例如“的”,“和”,“了”,“对”等词的干扰,但是大致来说,两则新闻的主题分布很明显,效果还不赖。

总结

以上就是本文关于Python_LDA实现方法详解的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站:python+mongodb数据抓取详细介绍、Python探索之创建二叉树、Python探索之修改Python搜索路径等,有什么问题可以随时留言,欢迎大家一起交流讨论。感谢朋友们对本站的支持!

Python 相关文章推荐
python中list循环语句用法实例
Nov 10 Python
python实现字符串连接的三种方法及其效率、适用场景详解
Jan 13 Python
Python+matplotlib+numpy实现在不同平面的二维条形图
Jan 02 Python
Python实现JSON反序列化类对象的示例
Jan 31 Python
pandas数据分组和聚合操作方法
Apr 11 Python
符合语言习惯的 Python 优雅编程技巧【推荐】
Sep 25 Python
使用PyCharm创建Django项目及基本配置详解
Oct 24 Python
python实现微信自动回复机器人功能
Jul 11 Python
对Django项目中的ORM映射与模糊查询的使用详解
Jul 18 Python
对于Python深浅拷贝的理解
Jul 29 Python
keras在构建LSTM模型时对变长序列的处理操作
Jun 29 Python
Python 在 VSCode 中使用 IPython Kernel 的方法详解
Sep 05 Python
python+mongodb数据抓取详细介绍
Oct 25 #Python
python装饰器实例大详解
Oct 25 #Python
Python3 模块、包调用&amp;路径详解
Oct 25 #Python
Python探索之创建二叉树
Oct 25 #Python
Python探索之修改Python搜索路径
Oct 25 #Python
python中 logging的使用详解
Oct 25 #Python
python下载文件记录黑名单的实现代码
Oct 24 #Python
You might like
如何获得PHP相关资料
2006/10/09 PHP
ajax实现无刷新分页(php)
2010/07/18 PHP
ThinkPHP中session函数详解
2016/09/14 PHP
php加密解密字符串示例
2016/10/13 PHP
PHP中soap用法示例【SoapServer服务端与SoapClient客户端编写】
2018/12/25 PHP
javascript 常用代码技巧大收集
2009/02/25 Javascript
JavaScript中this的使用详解
2013/11/08 Javascript
JavaScript将字符串转换成字符编码列表的方法
2015/03/19 Javascript
jQuery实现页面滚动时动态加载内容的方法
2015/03/20 Javascript
用Node.js通过sitemap.xml批量抓取美女图片
2015/05/28 Javascript
手机端转盘抽奖代码分享
2015/09/10 Javascript
15个值得开发人员关注的jQuery开发技巧和心得总结【经典收藏】
2016/05/25 Javascript
详解XMLHttpRequest(二)响应属性、二进制数据、监测上传下载进度
2016/09/14 Javascript
jQuery+CSS3实现四种应用广泛的导航条制作实例详解
2016/09/17 Javascript
BootStrap网页中代码显示用法详解
2016/10/21 Javascript
AngularJS的$location使用方法详解
2017/10/19 Javascript
详解vue.js根据不同环境(正式、测试)打包到不同目录
2018/07/13 Javascript
vue打包使用Nginx代理解决跨域问题
2018/08/27 Javascript
vue中使用WX-JSSDK的两种方法(推荐)
2020/01/18 Javascript
JavaScript实现动态生成表格
2020/08/02 Javascript
[01:20:05]DOTA2-DPC中国联赛 正赛 Ehome vs VG BO3 第二场 2月5日
2021/03/11 DOTA
11个并不被常用但对开发非常有帮助的Python库
2015/03/31 Python
让python在hadoop上跑起来
2016/01/27 Python
几种实用的pythonic语法实例代码
2018/02/24 Python
对python PLT中的image和skimage处理图片方法详解
2019/01/10 Python
python实现登录密码重置简易操作代码
2019/08/14 Python
python3多线程知识点总结
2019/09/26 Python
python 实现生成均匀分布的点
2019/12/05 Python
python集合删除多种方法详解
2020/02/10 Python
物理教育专业毕业生推荐信
2013/11/03 职场文书
策划创业计划书
2014/02/06 职场文书
数控专业大学毕业生职业规划范文
2014/02/06 职场文书
2014年公司庆元旦活动方案
2014/03/05 职场文书
个人工作主要事迹
2014/05/08 职场文书
学生抄袭作业的检讨书
2014/10/02 职场文书
2015年度服装销售工作总结
2015/03/31 职场文书