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

相关文章

0基础租个硬件玩deepseek,蓝耘元生代智算云|本地部署DeepSeek R1模型的操作流程

《0基础租个硬件玩deepseek,蓝耘元生代智算云|本地部署DeepSeekR1模型的操作流程》DeepSeekR1模型凭借其强大的自然语言处理能力,在未来具有广阔的应用前景,有望在多个领域发... 目录0基础租个硬件玩deepseek,蓝耘元生代智算云|本地部署DeepSeek R1模型,3步搞定一个应

Deepseek R1模型本地化部署+API接口调用详细教程(释放AI生产力)

《DeepseekR1模型本地化部署+API接口调用详细教程(释放AI生产力)》本文介绍了本地部署DeepSeekR1模型和通过API调用将其集成到VSCode中的过程,作者详细步骤展示了如何下载和... 目录前言一、deepseek R1模型与chatGPT o1系列模型对比二、本地部署步骤1.安装oll

Spring AI Alibaba接入大模型时的依赖问题小结

《SpringAIAlibaba接入大模型时的依赖问题小结》文章介绍了如何在pom.xml文件中配置SpringAIAlibaba依赖,并提供了一个示例pom.xml文件,同时,建议将Maven仓... 目录(一)pom.XML文件:(二)application.yml配置文件(一)pom.xml文件:首

如何在本地部署 DeepSeek Janus Pro 文生图大模型

《如何在本地部署DeepSeekJanusPro文生图大模型》DeepSeekJanusPro模型在本地成功部署,支持图片理解和文生图功能,通过Gradio界面进行交互,展示了其强大的多模态处... 目录什么是 Janus Pro1. 安装 conda2. 创建 python 虚拟环境3. 克隆 janus

本地私有化部署DeepSeek模型的详细教程

《本地私有化部署DeepSeek模型的详细教程》DeepSeek模型是一种强大的语言模型,本地私有化部署可以让用户在自己的环境中安全、高效地使用该模型,避免数据传输到外部带来的安全风险,同时也能根据自... 目录一、引言二、环境准备(一)硬件要求(二)软件要求(三)创建虚拟环境三、安装依赖库四、获取 Dee

Linux环境变量&&进程地址空间详解

《Linux环境变量&&进程地址空间详解》本文介绍了Linux环境变量、命令行参数、进程地址空间以及Linux内核进程调度队列的相关知识,环境变量是系统运行环境的参数,命令行参数用于传递给程序的参数,... 目录一、初步认识环境变量1.1常见的环境变量1.2环境变量的基本概念二、命令行参数2.1通过命令编程

DeepSeek模型本地部署的详细教程

《DeepSeek模型本地部署的详细教程》DeepSeek作为一款开源且性能强大的大语言模型,提供了灵活的本地部署方案,让用户能够在本地环境中高效运行模型,同时保护数据隐私,在本地成功部署DeepSe... 目录一、环境准备(一)硬件需求(二)软件依赖二、安装Ollama三、下载并部署DeepSeek模型选

Golang的CSP模型简介(最新推荐)

《Golang的CSP模型简介(最新推荐)》Golang采用了CSP(CommunicatingSequentialProcesses,通信顺序进程)并发模型,通过goroutine和channe... 目录前言一、介绍1. 什么是 CSP 模型2. Goroutine3. Channel4. Channe

Python基于火山引擎豆包大模型搭建QQ机器人详细教程(2024年最新)

《Python基于火山引擎豆包大模型搭建QQ机器人详细教程(2024年最新)》:本文主要介绍Python基于火山引擎豆包大模型搭建QQ机器人详细的相关资料,包括开通模型、配置APIKEY鉴权和SD... 目录豆包大模型概述开通模型付费安装 SDK 环境配置 API KEY 鉴权Ark 模型接口Prompt

基于Qt实现系统主题感知功能

《基于Qt实现系统主题感知功能》在现代桌面应用程序开发中,系统主题感知是一项重要的功能,它使得应用程序能够根据用户的系统主题设置(如深色模式或浅色模式)自动调整其外观,Qt作为一个跨平台的C++图形用... 目录【正文开始】一、使用效果二、系统主题感知助手类(SystemThemeHelper)三、实现细节