当前位置: 首页 > news >正文

自然语言处理Gensim入门:建模与模型保存

文章目录

  • 自然语言处理Gensim入门:建模与模型保存
    • 关于gensim基础知识
    • 1. 模块导入
    • 2. 内部变量定义
    • 3. 主函数入口 (`if __name__ == '__main__':`)
    • 4. 加载语料库映射
    • 5. 加载和预处理语料库
    • 6. 根据方法参数选择模型训练方式
    • 7. 保存模型和变换后的语料
    • 8.代码

自然语言处理Gensim入门:建模与模型保存

关于gensim基础知识

Gensim是一个专门针对大规模文本数据进行主题建模和相似性检索的Python库。
MmCorpus是gensim用于高效读写大型稀疏矩阵的一种格式,适用于大数据集。
TF-IDF是一种常见的文本表示方法,通过对词频进行加权以突出重要性较高的词语。
LSI、LDA和RP都是降维或主题提取方法,常用于信息检索、文本分类和聚类任务。

这段代码是使用gensim库生成主题模型的一个脚本,它根据用户提供的语言和方法参数来训练文本数据集,并将训练好的模型保存为文件。以下是核心代码逻辑的分析与解释:

1. 模块导入

  • 导入了logging模块用于记录程序运行日志。
  • 导入sys模块以获取命令行参数和程序名。
  • 导入os.path模块处理文件路径相关操作。
  • 从gensim.corpora导入dmlcorpus(一个用于加载特定格式语料库的模块)和MmCorpus(存储稀疏矩阵表示的文档-词项矩阵的类)。
  • 从gensim.models导入四个模型:lsimodel、ldamodel、tfidfmodel、rpmodel,分别对应潜在语义索引(LSI)、潜在狄利克雷分配(LDA)、TF-IDF转换模型以及随机投影(RP)。

2. 内部变量定义

  • DIM_RP, DIM_LSI, DIM_LDA 分别指定了RP、LSI和LDA模型的维度大小。

3. 主函数入口 (if __name__ == '__main__':)

  • 配置日志输出格式并设置日志级别为INFO。
  • 检查输入参数数量是否满足要求(至少包含语言和方法两个参数),否则打印帮助信息并退出程序。
  • 获取指定的语言和方法参数。

4. 加载语料库映射

  • 根据传入的语言参数创建DmlConfig对象,该对象包含了语料库的相关配置信息,如存放结果的目录等。
  • 加载词汇表字典,即wordids.txt文件,将其转换成id2word字典结构,以便在后续模型构建中将词语ID映射回实际词语。

5. 加载和预处理语料库

  • 使用MmCorpus加载二进制bow.mm文件,该文件存储了文档-词项矩阵,每个文档是一个稀疏向量表示。

6. 根据方法参数选择模型训练方式

  • 如果方法为’tfidf’,则训练并保存TF-IDF模型,该模型对原始词频进行加权,增加了逆文档频率因子。
  • 若方法为’lda’,则训练LDA模型,这是一个基于概率统计的主题模型,通过文档-主题分布和主题-词语分布抽取主题结构。
  • 若方法为’lsi’,首先用TF-IDF模型转换语料,然后在此基础上训练LSI模型,它是一种线性代数方法,用于发现文本中的潜在主题空间。
  • 若方法为’rp’,同样先转为TF-IDF表示,然后训练RP模型,利用随机投影技术降低数据维数。
  • 对于未知的方法,抛出ValueError异常。

7. 保存模型和变换后的语料

  • 训练完相应模型后,将其保存到指定的文件中(例如model_lda.pkl或model_lsi.pkl)。
  • 将原始语料经过所训练模型变换后得到的新语料(即主题表示形式)保存为一个新的MM格式文件,文件名反映所使用的主题模型方法。

8.代码

#!/usr/bin/env python
#
# Copyright (C) 2010 Radim Rehurek <radimrehurek@seznam.cz>
# Licensed under the GNU LGPL v2.1 - https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html"""
USAGE: %(program)s LANGUAGE METHODGenerate topic models for the specified subcorpus. METHOD is currently one \
of 'tfidf', 'lsi', 'lda', 'rp'.Example: ./gensim_genmodel.py any lsi
"""import logging
import sys
import os.pathfrom gensim.corpora import dmlcorpus, MmCorpus
from gensim.models import lsimodel, ldamodel, tfidfmodel, rpmodelimport gensim_build# internal method parameters
DIM_RP = 300  # dimensionality for random projections
DIM_LSI = 200  # for lantent semantic indexing
DIM_LDA = 100  # for latent dirichlet allocationif __name__ == '__main__':logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s')logging.root.setLevel(level=logging.INFO)logging.info("running %s", ' '.join(sys.argv))program = os.path.basename(sys.argv[0])# check and process input argumentsif len(sys.argv) < 3:print(globals()['__doc__'] % locals())sys.exit(1)language = sys.argv[1]method = sys.argv[2].strip().lower()logging.info("loading corpus mappings")config = dmlcorpus.DmlConfig('%s_%s' % (gensim_build.PREFIX, language),resultDir=gensim_build.RESULT_DIR, acceptLangs=[language])logging.info("loading word id mapping from %s", config.resultFile('wordids.txt'))id2word = dmlcorpus.DmlCorpus.loadDictionary(config.resultFile('wordids.txt'))logging.info("loaded %i word ids", len(id2word))corpus = MmCorpus(config.resultFile('bow.mm'))if method == 'tfidf':model = tfidfmodel.TfidfModel(corpus, id2word=id2word, normalize=True)model.save(config.resultFile('model_tfidf.pkl'))elif method == 'lda':model = ldamodel.LdaModel(corpus, id2word=id2word, num_topics=DIM_LDA)model.save(config.resultFile('model_lda.pkl'))elif method == 'lsi':# first, transform word counts to tf-idf weightstfidf = tfidfmodel.TfidfModel(corpus, id2word=id2word, normalize=True)# then find the transformation from tf-idf to latent spacemodel = lsimodel.LsiModel(tfidf[corpus], id2word=id2word, num_topics=DIM_LSI)model.save(config.resultFile('model_lsi.pkl'))elif method == 'rp':# first, transform word counts to tf-idf weightstfidf = tfidfmodel.TfidfModel(corpus, id2word=id2word, normalize=True)# then find the transformation from tf-idf to latent spacemodel = rpmodel.RpModel(tfidf[corpus], id2word=id2word, num_topics=DIM_RP)model.save(config.resultFile('model_rp.pkl'))else:raise ValueError('unknown topic extraction method: %s' % repr(method))MmCorpus.saveCorpus(config.resultFile('%s.mm' % method), model[corpus])logging.info("finished running %s", program)
http://www.lryc.cn/news/307743.html

相关文章:

  • Windows 10中Visual Studio Code(VSCode)无法自动打开终端的解决办法
  • python dictionary 字典中的内置函数介绍及其示例
  • pdf转word文档怎么转?分享4种转换方法
  • 深度测试:指定DoC ID对ES写入性能的影响
  • 【JGit】 AddCommand 新增的文件不能添加到暂存区
  • golang学习6,glang的web的restful接口传参
  • Carla自动驾驶仿真八:两种查找CARLA地图坐标点的方法
  • HarmonyOS | 状态管理(八) | PersistentStorage(持久化存储UI状态)
  • Git 突破 文件尺寸限制
  • HarmonyOS开发云工程与开发云函数
  • SpringMVC了解
  • day44((VueJS)路由的懒加载使用 路由的元信息(meta) 路由守卫函数 vant组件库的应用)
  • 非线性优化资料整理
  • 踩坑wow.js 和animate.css一起使用没有效果
  • Laravel - API 项目适用的图片验证码
  • iMazing3安全吗?好不好用?值不值得下载
  • 韩国突发:将批准比特币ETF
  • Kubernetes IoTDB系列 | IoTDB数据库同步|IoTDB数据库高可用
  • 重拾前端基础知识:CSS
  • 综合实战(volume and Compose)
  • 国际黄金价格要具体市况具体分析
  • 【python】0、超详细介绍:json、http
  • 可观测性在威胁检测和取证日志分析中的作用
  • win32com打开带密码excel
  • IntelliJ IDEA 的常用快捷键
  • C语言统计成绩
  • LVS做集群四层负载均衡的简单理解
  • 2.1_6 线程的实现方式和多线程模型
  • 4.5 MongoDB 文档存储
  • 什么是服务级别协议(SLA)?