主题模型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] += 1
 
texts = [
    [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 whitespace
            yield 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 time
    print(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 stoplist
    if 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

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值