到2018年3月7日为止,本系列三篇文章已写完,可能后续有新的内容的话会继续更新。

python下进行lda主题挖掘(一)——预处理(英文) python下进行lda主题挖掘(二)——利用gensim训练LDA模型 python下进行lda主题挖掘(三)——计算困惑度perplexity

本篇是我的LDA主题挖掘系列的第二篇,介绍如何利用gensim包提供的方法来训练自己处理好的语料。 gensim提供了多种方法: ###速度较慢的: 具体参数说明及使用方法请参照官网:models.ldamodel – Latent Dirichlet Allocation

from gensim.models.ldamodel import LdaModel

# 利用处理好的语料训练模型

lda = LdaModel(corpus, num_topics=10)

# 推断新文本的主题分布

doc_lda = lda[doc_bow]

# 用新语料更新模型

lda.update(other_corpus)

###速度较快,使用多核心的: 具体参数说明及使用方法请参照官网:models.ldamulticore – parallelized Latent Dirichlet Allocation

>>> from gensim import corpora, models

>>> lda = LdaMulticore(corpus, id2word=id2word, num_topics=100)  # train model

>>> print(lda[doc_bow]) # get topic probability distribution for a document

>>> lda.update(corpus2) # update the LDA model with additional documents

>>> print(lda[doc_bow])

使用多进程对性能的提升:

Wall-clock performance on the English Wikipedia (2G corpus positions, 3.5M documents, 100K features, 0.54G non-zero entries in the final bag-of-words matrix), requesting 100 topics: (Measured on this i7 server with 4 physical cores, so that optimal workers=3, one less than the number of cores.) | algorithm| training time| | ------------- |:-------------? | LdaMulticore(workers=1) | 2h30m | | LdaMulticore(workers=2) | 1h24m | | LdaMulticore(workers=3) | 1h6m | | oldLdaModel | 3h44m | | simply iterating over input corpus = I/O overhead | 20m | workers的值需要比电脑的核心数小1 本文代码使用多核心的方法。 有问题欢迎留言交流。 本文在将语料转化为corpus后,进行了如下操作:

tfidf = models.TfidfModel(corpus)

corpusTfidf = tfidf[corpus]

这一步是用来调整语料中不同词的词频,将那些在所有文档中都出现的高频词的词频降低,具体原理可参见阮一峰老师的系列博客:TF-IDF与余弦相似性的应用(一):自动提取关键词,我经过这一步处理后,貌似效果提升不明显,而且这一步时间消耗较大,不建议采用。可直接将corpus作为训练数据传入lda模型中。

#-*-coding:utf-8-*-

import sys

reload(sys)

sys.setdefaultencoding('utf-8')

import os

import codecs

from gensim.corpora import Dictionary

from gensim import corpora, models

from datetime import datetime

import platform

import logging

logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s : ', level=logging.INFO)

platform_info = platform.platform().lower()

if 'windows' in platform_info:

code = 'gbk'

elif 'linux' in platform_info:

code = 'utf-8'

path = sys.path[0]

class GLDA(object):

"""docstring for GdeltGLDA"""

def __init__(self, stopfile=None):

super(GLDA, self).__init__()

if stopfile:

with codecs.open(stopfile, 'r', code) as f:

self.stopword_list = f.read().split(' ')

print ('the num of stopwords is : %s'%len(self.stopword_list))

else:

self.stopword_list = None

def lda_train(self, num_topics, datafolder, middatafolder, dictionary_path=None, corpus_path=None, iterations=5000, passes=1, workers=3):

time1 = datetime.now()

num_docs = 0

doclist = []

if not corpus_path or not dictionary_path: # 若无字典或无corpus,则读取预处理后的docword。一般第一次运行都需要读取,在后期调参时,可直接传入字典与corpus路径

for filename in os.listdir(datafolder): # 读取datafolder下的语料

with codecs.open(datafolder+filename, 'r', code) as source_file:

for line in source_file:

num_docs += 1

if num_docs%100000==0:

print ('%s, %s'%(filename, num_docs))

#doc = [word for word in doc if word not in self.stopword_list]

doclist.append(line.split(' '))

print ('%s, %s'%(filename, num_docs))

if dictionary_path:

dictionary = corpora.Dictionary.load(dictionary_path) # 加载字典

else:

#构建词汇统计向量并保存

dictionary = corpora.Dictionary(doclist)

dictionary.save(middatafolder + 'dictionary.dictionary')

if corpus_path:

corpus = corpora.MmCorpus(corpus_path) # 加载corpus

else:

corpus = [dictionary.doc2bow(doc) for doc in doclist]

corpora.MmCorpus.serialize(middatafolder + 'corpus.mm', corpus) # 保存corpus

tfidf = models.TfidfModel(corpus)

corpusTfidf = tfidf[corpus]

time2 = datetime.now()

lda_multi = models.ldamulticore.LdaMulticore(corpus=corpusTfidf, id2word=dictionary, num_topics=num_topics, \

iterations=iterations, workers=workers, batch=True, passes=passes) # 开始训练

lda_multi.print_topics(num_topics, 30) # 输出主题词矩阵

print ('lda training time cost is : %s, all time cost is : %s '%(datetime.now()-time2, datetime.now()-time1))

#模型的保存/ 加载

lda_multi.save(middatafolder + 'lda_tfidf_%s_%s.model'%(num_topics, iterations)) # 保存模型

# lda = models.ldamodel.LdaModel.load('zhwiki_lda.model') # 加载模型

# save the doc-topic-id

topic_id_file = codecs.open(middatafolder + 'topic.json', 'w', 'utf-8')

for i in range(num_docs):

topic_id = lda_multi[corpusTfidf[i]][0][0] # 取概率最大的主题作为文本所属主题

topic_id_file.write(str(topic_id)+ ' ')

if __name__ == '__main__':

datafolder = path + os.sep + 'docword' + os.sep # 预处理后的语料所在文件夹,函数会读取此文件夹下的所有语料文件

middatafolder = path + os.sep + 'middata' + os.sep

dictionary_path = middatafolder + 'dictionary.dictionary' # 已处理好的字典,若无,则设置为False

corpus_path = middatafolder + 'corpus.mm' # 对语料处理过后的corpus,若无,则设置为False

# stopfile = path + os.sep + 'rest_stopwords.txt' # 新添加的停用词文件

num_topics = 50

passes = 2 # 这个参数大概是将全部语料进行训练的次数,数值越大,参数更新越多,耗时更长

iterations = 6000

workers = 3 # 相当于进程数

lda = GLDA()

lda.lda_train(num_topics, datafolder, middatafolder, dictionary_path=dictionary_path, corpus_path=corpus_path, iterations=iterations, passes=passes, workers=workers)

在训练好模型后该如何对模型进行评价,以选取合适的参数? 可参照下一篇博客python下进行lda主题挖掘(三)——计算困惑度

以上,欢迎交流与指正。

python用lda主题_python下进行lda主题挖掘(二)——利用gensim训练LDA模型相关推荐

  1. python环境变量配置_Python零基础入门到年薪二十万-1.1节: 在windows中安装Python

    教程引言: 该系列图文课程以及视频课程全部免费.课程会系统地讲解计算机的基础知识,Python的基础知识. 在讲解Python的高级知识中,会系统地讲解面向对象编程,并发编程,数据库编程,网络编程. ...

  2. python 打开targz文件_Python下使用pandas打开excel文件并进行处理

    单位有较多账户报表,经常要知道哪些账户的金额是多少. 最近python很火,感觉可以搞一下,但是0基础,自己摸索,著文以记之. 安装python.安装最新版,可以多活一段时间,什么都选择默认就好. 安 ...

  3. python threading类重写_python下threading模块使用的注意点

    python下threading模块使用的注意点 1. 线程执行代码的封装 通过上一小节,能够看出,通过使用threading模块能完成多任务的程序开发,为了让每个线程的封装性更完美,所以使用thre ...

  4. python 递归遍历目录排序_python下递归遍历目录和文件

    方法一:递归调用: import os def dirlist(path, allfile): filelist =  os.listdir(path) for filename in filelis ...

  5. python自动输入验证码_python下的自动化测试--selenium 验证码输入问题

    之前一直在研究scrapy下数据抓取,在研究ajax数据抓取时碰巧研究了一下selenium,确实很实用,不过只做scrapy下的数据抓取,不怎么合适,一是性能的损耗,一直需要开一个浏览器,二是对于爬 ...

  6. python语音标注平台_Python下的自然语言处理利器-LTP语言技术平台 pyltp 学习手札...

    1 什么是pyltp 语言技术平台(LTP) 是由 哈工大社会计算与信息检索研究中心 11 年的持续研发而形成的一个自然语言处理工具库,其提供包括中文分词.词性标注.命名实体识别.依存句法分析.语义角 ...

  7. python横线怎么打_python下划线怎么打出来

    python中下划线使用键盘上的Shift+减号键即可打出,减号键位于0和加号键之间. 在Python中下划线还具有 private 和 protected 类似的访问权限作用,下面我们具体分析.Py ...

  8. python输入年月日输出_python下输出指定年月日的方法之一

    参考自:http://www.cnblogs.com/rollenholt/archive/2012/04/11/2441699.html 格式字符串 datetime.date.time都提供了st ...

  9. python opencv 摄像头亮度_Python 下opencv 应用: 摄像头参数设置

    为了取得好的图片效果,我们需要设置摄像头的参数. 假如摄像流为 cap, 那么设置参数是cap.set(参数编号,参数) 获取参数值的函数是  cap.get(参数编号) 看一段摄像头参数设置读取的例 ...

  10. python图片读取优化_Python下图片的高斯模糊化的优化

    资源下载 #本文PDF版下载 Python下图片的高斯模糊化的优化(或者单击我博客园右上角的github小标,找到lab102的W6目录下即可) #本文代码下载 高斯模糊(一维)优化代码(和本文方法集 ...

最新文章

  1. 【机器学习算法-python实现】Adaboost的实现(1)-单层决策树(decision stump)
  2. Python利用pymysql连接Mysql数据库
  3. enterpriseTECH Dec 10
  4. python计算机知识点,最新最全Python基础的知识点复习完整版.pdf
  5. nginx转发websocket
  6. 检查一列数据的重复项 vba_提取重复值,但字典不是重点。
  7. 发自虎扑android客户端,巴斯托尼要长留我纯啊
  8. 汲取 IE6、IE8 消亡的经验,如何“杀死” IE11?
  9. kafak 命令使用
  10. 五子课堂---第一课(连珠基础一)
  11. matlab 设置计算精度,matlab计算精度设置
  12. python之微博批量关注,互粉
  13. Stata软件做门槛回归模型(汉森个人主页上的代码)
  14. 华为防火墙配置IPSEC实现二个站点间网络互通 隧道模式 CLI配置 (三)
  15. js-原生Js汉语拼音首字母匹配城市名
  16. 联想小新15用什么C语言程序,长处更长 优点更优 联想小新Air 15 2019首测
  17. 银河麒麟 kylin server v10上创建虚拟机(基于 鲲鹏920 CPU)
  18. 实现数字电视机顶盒画面的纯键盘和遥控操作网页
  19. agv系统介绍_AGV物流系统工作流程及模块介绍
  20. 最新仿猪八戒威客系统源码网整站源码下载

热门文章

  1. 91卫图助手免费获取高清影像
  2. mysql导入数据dmp文件怎么打开_如何在oracle中导入dmp数据库文件
  3. 基于51单片机WiFi温湿度远程控制
  4. 基于LSM和BLP的IPC进程通信模型
  5. PlutoSDR软件无线电平台带宽破解
  6. 通用数据库弱密码检测解决方案
  7. mac os安装Windows系统失败后不能合并为一个分区
  8. AP6212 蓝牙调试步骤
  9. SPSS数据转换插件v1.4发布
  10. weka安装需要java不_如何下载安装Weka机器学习工作平台