本文转自:LDA主题模型原理解析与python实现_wind_blast的博客-CSDN博客



 

python实现:

#-*- coding:utf-8 -*-
import logging
import logging.config
import ConfigParser
import numpy as np
import random
import codecs
import osfrom collections import OrderedDict
#获取当前路径
path = os.getcwd()
#导入日志配置文件
logging.config.fileConfig("logging.conf")
#创建日志对象
logger = logging.getLogger()
# loggerInfo = logging.getLogger("TimeInfoLogger")
# Consolelogger = logging.getLogger("ConsoleLogger")#导入配置文件
conf = ConfigParser.ConfigParser()
conf.read("setting.conf")
#文件路径
trainfile = os.path.join(path,os.path.normpath(conf.get("filepath", "trainfile")))
wordidmapfile = os.path.join(path,os.path.normpath(conf.get("filepath","wordidmapfile")))
thetafile = os.path.join(path,os.path.normpath(conf.get("filepath","thetafile")))
phifile = os.path.join(path,os.path.normpath(conf.get("filepath","phifile")))
paramfile = os.path.join(path,os.path.normpath(conf.get("filepath","paramfile")))
topNfile = os.path.join(path,os.path.normpath(conf.get("filepath","topNfile")))
tassginfile = os.path.join(path,os.path.normpath(conf.get("filepath","tassginfile")))
#模型初始参数
K = int(conf.get("model_args","K"))
alpha = float(conf.get("model_args","alpha"))
beta = float(conf.get("model_args","beta"))
iter_times = int(conf.get("model_args","iter_times"))
top_words_num = int(conf.get("model_args","top_words_num"))
class Document(object):def __init__(self):self.words = []self.length = 0
#把整个文档及真的单词构成vocabulary(不允许重复)
class DataPreProcessing(object):def __init__(self):self.docs_count = 0self.words_count = 0#保存每个文档d的信息(单词序列,以及length)self.docs = []#建立vocabulary表,照片文档的单词self.word2id = OrderedDict()def cachewordidmap(self):with codecs.open(wordidmapfile, 'w','utf-8') as f:for word,id in self.word2id.items():f.write(word +"\t"+str(id)+"\n")
class LDAModel(object):def __init__(self,dpre):self.dpre = dpre #获取预处理参数##模型参数#聚类个数K,迭代次数iter_times,每个类特征词个数top_words_num,超参数α(alpha) β(beta)#self.K = Kself.beta = betaself.alpha = alphaself.iter_times = iter_timesself.top_words_num = top_words_num ##文件变量#分好词的文件trainfile#词对应id文件wordidmapfile#文章-主题分布文件thetafile#词-主题分布文件phifile#每个主题topN词文件topNfile#最后分派结果文件tassginfile#模型训练选择的参数文件paramfile#self.wordidmapfile = wordidmapfileself.trainfile = trainfileself.thetafile = thetafileself.phifile = phifileself.topNfile = topNfileself.tassginfile = tassginfileself.paramfile = paramfile# p,概率向量 double类型,存储采样的临时变量# nw,词word在主题topic上的分布# nwsum,每各topic的词的总数# nd,每个doc中各个topic的词的总数# ndsum,每各doc中词的总数self.p = np.zeros(self.K)# nw,词word在主题topic上的分布self.nw = np.zeros((self.dpre.words_count,self.K),dtype="int")# nwsum,每各topic的词的总数self.nwsum = np.zeros(self.K,dtype="int")# nd,每个doc中各个topic的词的总数self.nd = np.zeros((self.dpre.docs_count,self.K),dtype="int")# ndsum,每各doc中词的总数self.ndsum = np.zeros(dpre.docs_count,dtype="int")self.Z = np.array([ [0 for y in xrange(dpre.docs[x].length)] for x in xrange(dpre.docs_count)])        # M*doc.size(),文档中词的主题分布#随机先分配类型,为每个文档中的各个单词分配主题for x in xrange(len(self.Z)):self.ndsum[x] = self.dpre.docs[x].lengthfor y in xrange(self.dpre.docs[x].length):topic = random.randint(0,self.K-1)#随机取一个主题self.Z[x][y] = topic#文档中词的主题分布self.nw[self.dpre.docs[x].words[y]][topic] += 1self.nd[x][topic] += 1self.nwsum[topic] += 1self.theta = np.array([ [0.0 for y in xrange(self.K)] for x in xrange(self.dpre.docs_count) ])self.phi = np.array([ [ 0.0 for y in xrange(self.dpre.words_count) ] for x in xrange(self.K)]) def sampling(self,i,j):#换主题topic = self.Z[i][j]#只是单词的编号,都是从0开始word就是等于jword = self.dpre.docs[i].words[j]#if word==j:#    print 'true'self.nw[word][topic] -= 1self.nd[i][topic] -= 1self.nwsum[topic] -= 1self.ndsum[i] -= 1Vbeta = self.dpre.words_count * self.betaKalpha = self.K * self.alphaself.p = (self.nw[word] + self.beta)/(self.nwsum + Vbeta) * \(self.nd[i] + self.alpha) / (self.ndsum[i] + Kalpha)#随机更新主题的吗# for k in xrange(1,self.K):#     self.p[k] += self.p[k-1]# u = random.uniform(0,self.p[self.K-1])# for topic in xrange(self.K):#     if self.p[topic]>u:#         break#按这个更新主题更好理解,这个效果还不错p = np.squeeze(np.asarray(self.p/np.sum(self.p)))topic = np.argmax(np.random.multinomial(1, p))self.nw[word][topic] +=1self.nwsum[topic] +=1self.nd[i][topic] +=1self.ndsum[i] +=1return topicdef est(self):# Consolelogger.info(u"迭代次数为%s 次" % self.iter_times)for x in xrange(self.iter_times):for i in xrange(self.dpre.docs_count):for j in xrange(self.dpre.docs[i].length):topic = self.sampling(i,j)self.Z[i][j] = topiclogger.info(u"迭代完成。")logger.debug(u"计算文章-主题分布")self._theta()logger.debug(u"计算词-主题分布")self._phi()logger.debug(u"保存模型")self.save()def _theta(self):for i in xrange(self.dpre.docs_count):#遍历文档的个数词self.theta[i] = (self.nd[i]+self.alpha)/(self.ndsum[i]+self.K * self.alpha)def _phi(self):for i in xrange(self.K):self.phi[i] = (self.nw.T[i] + self.beta)/(self.nwsum[i]+self.dpre.words_count * self.beta)def save(self):# 保存theta文章-主题分布logger.info(u"文章-主题分布已保存到%s" % self.thetafile)with codecs.open(self.thetafile,'w') as f:for x in xrange(self.dpre.docs_count):for y in xrange(self.K):f.write(str(self.theta[x][y]) + '\t')f.write('\n')# 保存phi词-主题分布logger.info(u"词-主题分布已保存到%s" % self.phifile)with codecs.open(self.phifile,'w') as f:for x in xrange(self.K):for y in xrange(self.dpre.words_count):f.write(str(self.phi[x][y]) + '\t')f.write('\n')# 保存参数设置logger.info(u"参数设置已保存到%s" % self.paramfile)with codecs.open(self.paramfile,'w','utf-8') as f:f.write('K=' + str(self.K) + '\n')f.write('alpha=' + str(self.alpha) + '\n')f.write('beta=' + str(self.beta) + '\n')f.write(u'迭代次数  iter_times=' + str(self.iter_times) + '\n')f.write(u'每个类的高频词显示个数  top_words_num=' + str(self.top_words_num) + '\n')# 保存每个主题topic的词logger.info(u"主题topN词已保存到%s" % self.topNfile)with codecs.open(self.topNfile,'w','utf-8') as f:self.top_words_num = min(self.top_words_num,self.dpre.words_count)for x in xrange(self.K):f.write(u'第' + str(x) + u'类:' + '\n')twords = []twords = [(n,self.phi[x][n]) for n in xrange(self.dpre.words_count)]twords.sort(key = lambda i:i[1], reverse= True)for y in xrange(self.top_words_num):word = OrderedDict({value:key for key, value in self.dpre.word2id.items()})[twords[y][0]]f.write('\t'*2+ word +'\t' + str(twords[y][1])+ '\n')# 保存最后退出时,文章的词分派的主题的结果logger.info(u"文章-词-主题分派结果已保存到%s" % self.tassginfile)with codecs.open(self.tassginfile,'w') as f:for x in xrange(self.dpre.docs_count):for y in xrange(self.dpre.docs[x].length):f.write(str(self.dpre.docs[x].words[y])+':'+str(self.Z[x][y])+ '\t')f.write('\n')logger.info(u"模型训练完成。")
# 数据预处理,即:生成d()单词序列,以及词汇表
def preprocessing():logger.info(u'载入数据......')with codecs.open(trainfile, 'r','utf-8') as f:docs = f.readlines()logger.debug(u"载入完成,准备生成字典对象和统计文本数据...")# 大的文档集dpre = DataPreProcessing()items_idx = 0for line in docs:if line != "":tmp = line.strip().split()# 生成一个文档对象:包含单词序列(w1,w2,w3,,,,,wn)可以重复的doc = Document()for item in tmp:if dpre.word2id.has_key(item):# 已有的话,只是当前文档追加doc.words.append(dpre.word2id[item])else:  # 没有的话,要更新vocabulary中的单词词典及wordidmapdpre.word2id[item] = items_idxdoc.words.append(items_idx)items_idx += 1doc.length = len(tmp)dpre.docs.append(doc)else:passdpre.docs_count = len(dpre.docs) # 文档数dpre.words_count = len(dpre.word2id) # 词汇数logger.info(u"共有%s个文档" % dpre.docs_count)dpre.cachewordidmap()logger.info(u"词与序号对应关系已保存到%s" % wordidmapfile)return dpre
def run():# 处理文档集,及计算文档数,以及vocabulary词的总个数,以及每个文档的单词序列dpre = preprocessing()lda = LDAModel(dpre)lda.est()
if __name__ == '__main__':run()

LDA主题模型原理解析与python实现相关推荐

  1. 基于sklearn实现LDA主题模型(附实战案例)

    目录 LDA主题模型 1.LDA主题模型原理 2.LDA主题模型推演过程 3.sklearn实现LDA主题模型(实战) 3.1数据集介绍 3.2导入数据 3.3分词处理 3.4文本向量化 3.5构建L ...

  2. 【机器学习之LDA主题模型】

    文章目录 前言 一.LDA主题模型是什么? 1.LDA主题模型原理 2.LDA主题模型推演过程 三.问题总结 1.怎么确定LDA的标题个数? 四.拔高亮点 1. 如何用主题模型解决推荐系统中的冷启动问 ...

  3. LDA主题模型的原理及使用教程

    这是一个NLP参赛项目的主题分析环节的代码,总体的工程代码已经上传至github,可以直接下载使用. https://github.com/stay-leave/weibo-public-opinio ...

  4. LDA主题模型的原理和建模

    目录 什么是LDA主题模型 背景知识 贝叶斯理论 gamma函数 多个分布 博鲁尼分布 二项分布 多项分布 beta分布 Dirichlet 分布 开始了解LDA Python建模 什么是LDA主题模 ...

  5. LDA主题模型简介及Python实现

    一.LDA主题模型简介 LDA主题模型主要用于推测文档的主题分布,可以将文档集中每篇文档的主题以概率分布的形式给出根据主题进行主题聚类或文本分类. LDA主题模型不关心文档中单词的顺序,通常使用词袋特 ...

  6. LDA主题模型及python实现

    LDA(Latent Dirichlet Allocation)中文翻译为:潜在狄利克雷分布.LDA主题模型是一种文档生成模型,是一种非监督机器学习技术.它认为一篇文档是有多个主题的,而每个主题又对应 ...

  7. Python实现的《芳华》WordCloud词云+LDA主题模型

    WordCloud 词云 + LDA 主题模型 何小嫚&刘峰原图.jpg 人物词云效果.jpg 电影<芳华>在春节重映了一波,加上之前的热映,最终取得了 14 亿票房的好成绩.严歌 ...

  8. LDA主题模型绘制困惑度(perplexity)-主题数曲线——python

    主题建模作为一种基于机器学习的文本内容分析技术,一般用于推断文本文档中隐藏主题的技术.很多研究使用了基于Latent Dirichlet Allocation (LDA)的主题建模算法来处理大规模文档 ...

  9. 【项目实战】Python实现基于LDA主题模型进行电商产品评论数据情感分析

    说明:这是一个机器学习.数据挖掘实战项目(附带数据+代码+文档+视频讲解),如需数据+代码+文档+视频讲解可以直接到文章最后获取. 视频: Python实现基于LDA模型进行电商产品评论数据情感分析 ...

最新文章

  1. 模拟和存根有什么区别?
  2. mysql数据库的维护_MySQL数据库维护
  3. git新建分支并且在切换分支开发
  4. android的应用组件,跟我学android-Android应用基本组件介绍(五)
  5. python怎么关闭csv_Python2.7.1:如何打开、编辑和关闭CSV fi
  6. Docker tomcat 多版本环境搭建
  7. 如何使用Python玩转PDF各种骚操作?你看了就知道。
  8. MFC界面库BCGControlBar Pro for MFC v33.1 - 更适配Windows 11
  9. 请简述一下RS485通讯连接方式及其应用?
  10. 如何在Microsoft Word里面插入图片作为背景?
  11. 小米官网仿写部分代码+实训报告
  12. ip a命令显示的UP与LOWER_UP的区别
  13. 龙芯2h芯片不能进入pmon_2HSOCReleaseNotes - 龙芯开源社区
  14. 【Linux】数字ICer需要用到哪些Linux命令?
  15. openwrt 透明代理上网
  16. Spring 基本配置
  17. 利用FileReader和FileWriter完成一个文件拷贝功能
  18. 【STM32标准库】【基础知识】外部中断
  19. 谷歌dns服务器未响应,“DNS服务器未响应”怎么办? - 爱绿豆
  20. PHP中的打印LOG信息方式

热门文章

  1. c语言中char buffer,C语言对char*的封装,形成buffer
  2. webpack打包优化_如何提升 Webpack 打包速度
  3. html5动画在线制作工具,KoolShow-KoolShow(HTML5动画制作工具) v2.4.4 官方版-CE安全网...
  4. java 图片转成base64编码_java语言中如何将一个图片转换为base64编码的数据呢?
  5. 蒋本珊计算机组成原理知识点笔记,计算机组成原理习题答案解析(蒋本珊)
  6. python中while的特点_Python【2】:初入python 用户输入,if,(while 循环)
  7. dubbo protocol port 消费者端_Dubbo 优雅停机演进之路
  8. ajax瀑布流 dede,dedecms加载更多,无限下拉瀑布流插件
  9. mysql5.5 vsftpd_vsftpd-2.0.5+mysql-5.5+pam_mysql构建虚拟用户访问
  10. Python format()函数