主题模型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

相关文章

SpringCloud Stream 快速入门实例教程

《SpringCloudStream快速入门实例教程》本文介绍了SpringCloudStream(SCS)组件在分布式系统中的作用,以及如何集成到SpringBoot项目中,通过SCS,可... 目录1.SCS 组件的出现的背景和作用2.SCS 集成srping Boot项目3.Yml 配置4.Sprin

Java领域模型示例详解

《Java领域模型示例详解》本文介绍了Java领域模型(POJO/Entity/VO/DTO/BO)的定义、用途和区别,强调了它们在不同场景下的角色和使用场景,文章还通过一个流程示例展示了各模型如何协... 目录Java领域模型(POJO / Entity / VO/ DTO / BO)一、为什么需要领域模

关于MySQL将表中数据删除后多久空间会被释放出来

《关于MySQL将表中数据删除后多久空间会被释放出来》MySQL删除数据后,空间不会立即释放给操作系统,而是会被标记为“可重用”,以供未来插入新数据时使用,只有满足特定条件时,空间才可能真正返还给操作... 目录一、mysql数据删除与空间管理1.1 理解MySQL数据删除原理1.3 执行SQL1.3 使用

深入理解Redis线程模型的原理及使用

《深入理解Redis线程模型的原理及使用》Redis的线程模型整体还是多线程的,只是后台执行指令的核心线程是单线程的,整个线程模型可以理解为还是以单线程为主,基于这种单线程为主的线程模型,不同客户端的... 目录1 Redis是单线程www.chinasem.cn还是多线程2 Redis如何保证指令原子性2.

SpringMVC配置、映射与参数处理​入门案例详解

《SpringMVC配置、映射与参数处理​入门案例详解》文章介绍了SpringMVC框架的基本概念和使用方法,包括如何配置和编写Controller、设置请求映射规则、使用RestFul风格、获取请求... 目录1.SpringMVC概述2.入门案例①导入相关依赖②配置web.XML③配置SpringMVC

MySQL索引踩坑合集从入门到精通

《MySQL索引踩坑合集从入门到精通》本文详细介绍了MySQL索引的使用,包括索引的类型、创建、使用、优化技巧及最佳实践,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友... 目录mysql索引完整教程:从入门到入土(附实战踩坑指南)一、索引是什么?为什么需要它?1.1 什么

Java Lettuce 客户端入门到生产的实现步骤

《JavaLettuce客户端入门到生产的实现步骤》本文主要介绍了JavaLettuce客户端入门到生产的实现步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要... 目录1 安装依赖MavenGradle2 最小化连接示例3 核心特性速览4 生产环境配置建议5 常见问题

Linux五种IO模型的使用解读

《Linux五种IO模型的使用解读》文章系统解析了Linux的五种IO模型(阻塞、非阻塞、IO复用、信号驱动、异步),重点区分同步与异步IO的本质差异,强调同步由用户发起,异步由内核触发,通过对比各模... 目录1.IO模型简介2.五种IO模型2.1 IO模型分析方法2.2 阻塞IO2.3 非阻塞IO2.4

MySQL8.0临时表空间的使用及解读

《MySQL8.0临时表空间的使用及解读》MySQL8.0+引入会话级(temp_N.ibt)和全局(ibtmp1)InnoDB临时表空间,用于存储临时数据及事务日志,自动创建与回收,重启释放,管理高... 目录一、核心概念:为什么需要“临时表空间”?二、InnoDB 临时表空间的两种类型1. 会话级临时表

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

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