主题模型Gensim入门系列之二:语料和向量空间

2024-08-24 01:48

本文主要是介绍主题模型Gensim入门系列之二:语料和向量空间,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

系列目录:

(1)主题模型Gensim入门系列之一:核心概念

(2)主题模型Gensim入门系列之二:语料和向量空间

(3)主题模型Gensim入门系列之三:主题和变换

(4)主题模型Gensim入门系列之四:文本相似度查询

————————————————————————————

 

本文主要介绍将文档(Document)转换为向量空间,同时介绍语料流(corpus streaming) 和通过多种格式存储到磁盘。

 

1、从字符串到向量

首先,假设作为字符串,有如下语料:

documents = ["Human machine interface for lab abc computer applications","A survey of user opinion of computer system response time","The EPS user interface management system","System and human system engineering testing of EPS","Relation of user perceived response time to error measurement","The generation of random binary unordered trees","The intersection graph of paths in trees","Graph minors IV Widths of trees and well quasi ordering","Graph minors A survey",
]

该语料包含9个文档,每个文档包含1句话。

首先,和上一小节一样,将文档切分为词,并进行停止词和低频词的过滤(频率<=1)。

from pprint import pprint  # pretty-printer
from collections import defaultdict# 删除停止词和标点符号
stoplist = set('for a of the and to in'.split())
texts = [[word for word in document.lower().split() if word not in stoplist]for document in documents
]# 删除频率<=1的词
frequency = defaultdict(int)
for text in texts:for token in text:frequency[token] += 1texts = [[token for token in text if frequency[token] > 1]for text in texts
]pprint(texts)#输出
"""
[['human', 'interface', 'computer'],['survey', 'user', 'computer', 'system', 'response', 'time'],['eps', 'user', 'interface', 'system'],['system', 'human', 'system', 'eps'],['user', 'response', 'time'],['trees'],['graph', 'trees'],['graph', 'minors', 'trees'],['graph', 'minors', 'survey']]
"""

接下来就将预处理好的文档转换到向量空间,需要指出的是,文档转换成哪种向量空间取决于你想要提取到文档中的什么特性。以词袋向量(bag-of-word)为例,它忽略了单词出现在文档中的顺序,”你喜欢张三"和"张三喜欢你"会转换为同样的词袋向量,但是在一些对词序敏感的任务中,显然是不合适的。

作为示例,下面还是通过词袋模型进行说明,关于词袋模型,可以参考:01-gensim系列之一:核心概念

首先,利用原始的语料生成字典,并将字典保存成 .dict 文件。

from gensim import corpora
dictionary = corpora.Dictionary(texts)
dictionary.save('/tmp/test_corpora.dict')  # store the dictionary, for future reference
print(dictionary)#输出
"""
Dictionary(12 unique tokens: ['computer', 'human', 'interface', 'response', 'survey']...)
"""

上述代码实际上是利用gensim.corpora.Dictionary类,输入原始的语料,生成语料的字典并保存。字典包含语料中的所有单词,每一个单词有一个独立的索引。

如果要查看词典中每个词的索引,可以通过以下代码:

print(dictionary.token2id)#输出
"""
{'computer': 0, 'human': 1, 'interface': 2, 'response': 3, 'survey': 4, 'system': 5, 'time': 6, 'user': 7, 'eps': 8, 'trees': 9, 'graph': 10, 'minors': 11}
"""

有了词典之后,就可以把预处理后的语料转换为词袋向量,同时也可以将转换后的词袋向量保存成 .mm文件,方便以后加载使用:

corpus = [dictionary.doc2bow(text) for text in texts]
corpora.MmCorpus.serialize('/tmp/deerwester.mm', corpus)  # store to disk, for later use
print(corpus)#输出
"""
[
[(0, 1), (1, 1), (2, 1)],
[(0, 1), (3, 1), (4, 1), (5, 1), (6, 1), (7, 1)],
[(2, 1), (5, 1), (7, 1), (8, 1)],
[(1, 1), (5, 2), (8, 1)],
[(3, 1), (6, 1), (7, 1)],
[(9, 1)],
[(9, 1), (10, 1)],
[(9, 1), (10, 1), (11, 1)],
[(4, 1), (10, 1), (11, 1)]
]
"""

 

2、语料流(corpus streaming)—一次一个文档

在上面的小型样例语料的处理中,是一次性将语料加载到内存进行处理的。实际情况中,我们往往会碰到大规模的语料,难以一次性加载到内存。通常情况下,我们会把语料存储到一个文件中,文件的每一行代表一个文档,此时我们可以利用gensim进行逐行处理,代码如下:

class MyCorpus(object):def __iter__(self):for line in open('tmp/mycorpus.txt'):# assume there's one document per line, tokens separated by whitespaceyield dictionary.doc2bow(line.lower().split())

gensim 可以输入任何形式的语料,不限于list、dataframe、array等,只要是可迭代的对象,都可以作为gensim的输入。

接下来,就可以通过MyCorpus创建迭代器,该迭代器将语料中的文档逐条转换为词袋向量:

corpus_memory_friendly = MyCorpus()  # doesn't load the corpus into memory!
print(corpus_memory_friendly)#输出
<__main__.MyCorpus object at 0x7f2f3d6fcc50># 通过迭代的方式打印出每一条文档的词袋向量
for vector in corpus_memory_friendly:  # load one vector into memory at a timeprint(vector)# 输出
"""
[(0, 1), (1, 1), (2, 1)]
[(0, 1), (3, 1), (4, 1), (5, 1), (6, 1), (7, 1)]
[(2, 1), (5, 1), (7, 1), (8, 1)]
[(1, 1), (5, 2), (8, 1)]
[(3, 1), (6, 1), (7, 1)]
[(9, 1)]
[(9, 1), (10, 1)]
[(9, 1), (10, 1), (11, 1)]
[(4, 1), (10, 1), (11, 1)]
"""

通过迭代器的方式产生的词袋向量和原来一致,但是内存占用比不采用迭代器的方式要少得多,在处理大型语料的时候一般采用这种方式。

同样地,我们可以用这种方式创建一个字典:

from six import iteritems# 对语料中的单词进行统计
dictionary = corpora.Dictionary(line.lower().split() for line in open('tmp/mycorpus.txt'))# 找出停止词的索引
stop_ids = [dictionary.token2id[stopword]for stopword in stoplistif stopword in dictionary.token2id
]once_ids = [tokenid for tokenid, docfreq in iteritems(dictionary.dfs) if docfreq == 1]
dictionary.filter_tokens(stop_ids + once_ids)  # remove stop words and words that appear only once
dictionary.compactify()  # remove gaps in id sequence after words that were removed
print(dictionary)# 输出
"""
Dictionary(12 unique tokens: ['computer', 'human', 'interface', 'response', 'survey']...)
"""

 

3、语料格式

语料转化到向量空间之后可以保存成功多种格式的文件,方便后续调用。其中用的最多的格式为矩阵市场格式(Market Matrix format),一个保存的样例如下:

corpus = [[(1, 0.5)], []]  # 将一个文档设为空,just for fan
corpora.MmCorpus.serialize('/tmp/corpus.mm', corpus)

相应的,加载保存的语料代码如下:

corpus = corpora.MmCorpus('/tmp/corpus.mm')

其它的保存格式还包括 Joachim’s SVMlight 格式, Blei’s LDA-C 格式 and GibbsLDA++ 格式,相应的代码如下:

corpora.SvmLightCorpus.serialize('/tmp/corpus.svmlight', corpus)
corpora.BleiCorpus.serialize('/tmp/corpus.lda-c', corpus)
corpora.LowCorpus.serialize('/tmp/corpus.low', corpus)

加载的语料是一个流的对象,所以不能直接打印出转换后的文档,通过以下两个方法可以获取文档中的原始内容:

# 第1种方法,将整个语料加载到内存中
print(list(corpus))#输出
"""
[[(1, 0.5)], []]
"""# 第2种方法逐个加载,逐个打印,占用内存较小
for doc in corpus:print(doc)"""
[(1, 0.5)]
[]
"""

从上面的代码可以看出,gensim同样可以作为一种语料格式转换的工具,加载一种格式的语料,然后转换为另外一种格式的语料。

 

4、和 Numpy、Scipy的兼容性

Gensim 的语料可以从 Numpy或者scipy的矩阵中转换而来,它本身提供的简单易用的函数。一个示例代码如下:

import gensim
import numpy as np
numpy_matrix = np.random.randint(10, size=[5, 2])  # 作为示例的numpy随机矩阵# 将numpy矩阵转换为gensim的corpus
corpus = gensim.matutils.Dense2Corpus(numpy_matrix)# 将gensim的corpus转换为numpy的矩阵
numpy_matrix = gensim.matutils.corpus2dense(corpus, num_terms=number_of_corpus_features)

同样的,scipy矩阵和gensim corpus之间转换的示例代码如下:

import scipy.sparse# 作为样例的随机稀疏矩阵
scipy_sparse_matrix = scipy.sparse.random(5, 2)# 将scipy的稀疏矩阵转换为gensim的corpus
corpus = gensim.matutils.Sparse2Corpus(scipy_sparse_matrix)# 将gensim的corpus转换为scipy的稀疏矩阵
scipy_csc_matrix = gensim.matutils.corpus2csc(corpus)

 

翻译和编辑自:Corpora and Vector Spaces

这篇关于主题模型Gensim入门系列之二:语料和向量空间的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1101102

相关文章

Three.js构建一个 3D 商品展示空间完整实战项目

《Three.js构建一个3D商品展示空间完整实战项目》Three.js是一个强大的JavaScript库,专用于在Web浏览器中创建3D图形,:本文主要介绍Three.js构建一个3D商品展... 目录引言项目核心技术1. 项目架构与资源组织2. 多模型切换、交互热点绑定3. 移动端适配与帧率优化4. 可

从入门到精通详解Python虚拟环境完全指南

《从入门到精通详解Python虚拟环境完全指南》Python虚拟环境是一个独立的Python运行环境,它允许你为不同的项目创建隔离的Python环境,下面小编就来和大家详细介绍一下吧... 目录什么是python虚拟环境一、使用venv创建和管理虚拟环境1.1 创建虚拟环境1.2 激活虚拟环境1.3 验证虚

Java List 使用举例(从入门到精通)

《JavaList使用举例(从入门到精通)》本文系统讲解JavaList,涵盖基础概念、核心特性、常用实现(如ArrayList、LinkedList)及性能对比,介绍创建、操作、遍历方法,结合实... 目录一、List 基础概念1.1 什么是 List?1.2 List 的核心特性1.3 List 家族成

c++日志库log4cplus快速入门小结

《c++日志库log4cplus快速入门小结》文章浏览阅读1.1w次,点赞9次,收藏44次。本文介绍Log4cplus,一种适用于C++的线程安全日志记录API,提供灵活的日志管理和配置控制。文章涵盖... 目录简介日志等级配置文件使用关于初始化使用示例总结参考资料简介log4j 用于Java,log4c

史上最全MybatisPlus从入门到精通

《史上最全MybatisPlus从入门到精通》MyBatis-Plus是MyBatis增强工具,简化开发并提升效率,支持自动映射表名/字段与实体类,提供条件构造器、多种查询方式(等值/范围/模糊/分页... 目录1.简介2.基础篇2.1.通用mapper接口操作2.2.通用service接口操作3.进阶篇3

Python自定义异常的全面指南(入门到实践)

《Python自定义异常的全面指南(入门到实践)》想象你正在开发一个银行系统,用户转账时余额不足,如果直接抛出ValueError,调用方很难区分是金额格式错误还是余额不足,这正是Python自定义异... 目录引言:为什么需要自定义异常一、异常基础:先搞懂python的异常体系1.1 异常是什么?1.2

Python实现Word转PDF全攻略(从入门到实战)

《Python实现Word转PDF全攻略(从入门到实战)》在数字化办公场景中,Word文档的跨平台兼容性始终是个难题,而PDF格式凭借所见即所得的特性,已成为文档分发和归档的标准格式,下面小编就来和大... 目录一、为什么需要python处理Word转PDF?二、主流转换方案对比三、五套实战方案详解方案1:

Spring WebClient从入门到精通

《SpringWebClient从入门到精通》本文详解SpringWebClient非阻塞响应式特性及优势,涵盖核心API、实战应用与性能优化,对比RestTemplate,为微服务通信提供高效解决... 目录一、WebClient 概述1.1 为什么选择 WebClient?1.2 WebClient 与

Spring Boot 与微服务入门实战详细总结

《SpringBoot与微服务入门实战详细总结》本文讲解SpringBoot框架的核心特性如快速构建、自动配置、零XML与微服务架构的定义、演进及优缺点,涵盖开发环境准备和HelloWorld实战... 目录一、Spring Boot 核心概述二、微服务架构详解1. 微服务的定义与演进2. 微服务的优缺点三

从入门到精通详解LangChain加载HTML内容的全攻略

《从入门到精通详解LangChain加载HTML内容的全攻略》这篇文章主要为大家详细介绍了如何用LangChain优雅地处理HTML内容,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录引言:当大语言模型遇见html一、HTML加载器为什么需要专门的HTML加载器核心加载器对比表二