热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

文档集数据处理gensimcorpora.Dictionary

gensim是一个python的自然语言处理库,能够将文档根据TF-IDF,LDA,LSI等模型转化成向量模式,以便进行进一步的处理。此外,

gensim是一个python的自然语言处理库,能够将文档根据TF-IDF, LDA, LSI 等模型转化成向量模式,以便进行进一步的处理。此外,gensim还实现了word2vec功能,能够将单词转化为词向量。


1. corpora 和 dictionary

  • 基本概念和用法:

   corpora是gensim中的一个基本概念,是文档集的表现形式,也是后续进一步处理的基础。从本质上来说,corpora其实是一种格式或者说约定,其实就是一个二维矩阵。在实际运行中,因为单词数量极多(上万甚至10万级别),而一篇文档的单词数是有限的,所以如果还是采用密集矩阵来表示的话,会造成极大的内存浪费,所以gensim内部是用稀疏矩阵的形式来表示的。 

  • 包名

from gensim import corpora
from collections import defaultdict

2. 词典操作

  将文档分割成词语之后,使用dictiOnary= corpora.Dictionary(texts)生成词典。并可以使用save函数将词典持久化。

  dictionary.save('/tmp/deerwester.dict')

  生成词典以后corpus = [dictionary.doc2bow(text) for text in texts]档转化为向量形式。

from gensim import corpora
from collections import defaultdict
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"]# 去掉停用词
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]# 去掉只出现一次的单词
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]dictionary = corpora.Dictionary(texts) # 生成词典# 将文档存入字典,字典有很多功能,比如
#
diction.token2id 存放的是单词-id key-value对
#
diction.dfs 存放的是单词的出现频率
dictionary.save('/tmp/deerwester.dict') # store the dictionary, for future reference
corpus = [dictionary.doc2bow(text) for text in texts]
corpora.MmCorpus.serialize(
'/tmp/deerwester.mm', corpus) # store to disk, for later use

3. 存储

  • 存储文件

dictionary.save('/tmp/deerwester.dict')

  • 序列化

 corpora.MmCorpus.serialize 将corpus持久化到磁盘中。

corpora.MmCorpus.serialize('/tmp/deerwester.mm', corpus)

  • 反序列化:

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

   除了MmCorpus以外,还有其他的格式,例如SvmLightCorpus, BleiCorpus, LowCorpus等等,用法类似。

4. 其他操作

# 过滤掉出现频率最高的N个单词
dictionary.filter_n_most_frequent(N) # 1.去掉出现次数低于no_below的
#
2.去掉出现次数高于no_above的。注意这个小数指的是百分数
#
3.在1和2的基础上,保留出现频率前keep_n的单词
dictionary.filter_extremes(no_below=5, no_above=0.5, keep_n=100000) # 有两种用法,一种是去掉bad_id对应的词,另一种是保留good_id对应的词而去掉其他词。注意这里bad_ids和good_ids都是列表形式
dictionary.filter_tokens(bad_ids=None, good_ids=None) # 在执行完前面的过滤操作以后,可能会造成单词的序号之间有空隙,这时就可以使用该函数来对词典来进行重新排序,去掉这些空隙。
dictionary.compacity()

5. 分批处理和分布式计算

当文本的规模很大时,也许会造成内存不足以容纳文本的情况,这就需要将所有文本分批处理,最后再将各批次计算得到的结果进行汇总。分布式计算时也有类似的需求。

这里假设在两个批次中,分别生成了dict1,corpus1以及dict2,corpus2. 
第一步,首先将两个词典合并。当然,如果是先统一生成词典再分批生成词向量的话,可以跳过这一步,因为词典是一样的。

dict2_to_dict1 = dict1.merge_with(dict2)

要注意的是,得到的dict2_to_dict1并不是生成后的词典,而是dict2中的单词序号到这些词在合并后词典新序号的映射表。而dict1本身成为合并后的新词典。

第二步,合并corpus 
如果之前跳过了第一步,即dict1就是dict2的话,可以直接进行合并。合并有两种方式,一种是

merged_corpus = [x for x in corpus1] + [x for x in corpus2]

另外一种,则需使用内置的itertools类

merged_corpus = itertools.chain(corpus1, corpus2)
merged_corpus
= [x for x in merged_corpus]

如果之前的词典也是分批生成的话,则需要对corpus2进行一定的处理

new_corpus2 = dict2_to_dict1[corpus2]
merged_corpus
= itertools.chain(corpus1, new_corpus2)
merged_corpus
= [x for x in merged_corpus]

这样,就把分批处理得到的dict和corpus都合并起来了。

6. models

在models中,可以对corpus进行进一步的处理,比如使用tf-idf模型,lsi模型,lda模型等,非常强大。 
在按照之前的方法生成了corpus和dictionary以后,就可以生成模型了。

tfidf_model = models.TfidfModel(corpus)

注意,目前只是生成了一个模型,但这是类似于生成器,并不是将对应的corpus转化后的结果。对tf-idf模型而言,里面存储有各个单词的词频,文频等信息。想要将文档转化成tf-idf模式表示的向量,还要使用如下命令

corpus_tfidf = tfidf_model[corpus]

对于lda和lsi模型,用法有所不同

lsi_model = models.LsiModel(corpus_tfidf, id2word=dictionary, num_topics=2)
corpus_lsi
= lsi_model[corpus_tfidf]

可以看到,这里除了corpus以外,还多了num_topic的选项。这是指的潜在主题(topic)的数目,也等于转成lsi模型以后每个文档对应的向量长度。转化以后的向量在各项的值,即为该文档在该潜在主题的权重。因此lsi和lda的结果也可以看做该文档的文档向量,用于后续的分类,聚类等算法。值得注意的是,id2word是所有模型都有的选项,可以指定使用的词典。

  • 代码示例:

import os
from gensim import corpora, models, similarities
from pprint import pprint
from matplotlib import pyplot as plt
import logging# logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)def PrintDictionary(dictionary):token2id = dictionary.token2iddfs = dictionary.dfstoken_info = {}for word in token2id:token_info[word] = dict(word = word,id = token2id[word],freq = dfs[token2id[word]])token_items = token_info.values()token_items = sorted(token_items, key = lambda x:x['id'])print('The info of dictionary: ')pprint(token_items)print('--------------------------')def Show2dCorpora(corpus):nodes = list(corpus)ax0 = [x[0][1] for x in nodes] # 绘制各个doc代表的点ax1 = [x[1][1] for x in nodes]# print(ax0)# print(ax1)plt.plot(ax0,ax1,'o')plt.show()if (os.path.exists("/tmp/deerwester.dict")):dictionary = corpora.Dictionary.load('/tmp/deerwester.dict')corpus = corpora.MmCorpus('/tmp/deerwester.mm')print("Used files generated from first tutorial")
else:print("Please run first tutorial to generate data set")PrintDictionary(dictionary)# 尝试将corpus(bow形式) 转化成tf-idf形式
tfidf_model = models.TfidfModel(corpus) # step 1 -- initialize a model 将文档由按照词频表示 转变为按照tf-idf格式表示
doc_bow = [(0, 1), (1, 1),[4,3]]
doc_tfidf
= tfidf_model[doc_bow]# 将整个corpus转为tf-idf格式
corpus_tfidf = tfidf_model[corpus]
# pprint(list(corpus_tfidf))
#
pprint(list(corpus))## LSI模型 **************************************************
#
转化为lsi模型, 可用作聚类或分类
lsi_model = models.LsiModel(corpus_tfidf, id2word=dictionary, num_topics=2)
corpus_lsi
= lsi_model[corpus_tfidf]
nodes
= list(corpus_lsi)
# pprint(nodes)
lsi_model.print_topics(2) # 打印各topic的含义# ax0 = [x[0][1] for x in nodes] # 绘制各个doc代表的点
#
ax1 = [x[1][1] for x in nodes]
#
print(ax0)
#
print(ax1)
#
plt.plot(ax0,ax1,'o')
#
plt.show()

lsi_model.save(
'/tmp/model.lsi') # same for tfidf, lda, ...
lsi_model = models.LsiModel.load('/tmp/model.lsi')
# *********************************************************## LDA模型 **************************************************
lda_model = models.LdaModel(corpus_tfidf, id2word=dictionary, num_topics=2)
corpus_lda
= lda_model[corpus_tfidf]
Show2dCorpora(corpus_lsi)
# nodes = list(corpus_lda)
#
pprint(list(corpus_lda))# 此外,还有Random Projections, Hierarchical Dirichlet Process等模型

7. similarities

这一部分主要负责计算文档间的相似度。与向量的相似度计算方式一样,采用余弦方法计算得到。一般来讲,使用lsi模型得到的向量进行计算效果比较好。

  • 代码示例

corpus_simi_matrix = similarities.MatrixSimilarity(corpus_lsi)
# 计算一个新的文本与既有文本的相关度
test_text = "Human computer interaction".split()
test_bow
= dictionary.doc2bow(test_text)
test_tfidf
= tfidf_model[test_bow]
test_lsi
= lsi_model[test_tfidf]
test_simi
= corpus_simi_matrix[test_lsi]
print(list(enumerate(test_simi)))

得到结果[(0, 0.99916452), (1, 0.99632162), (2, 0.9990505), (3, 0.99886364), (4, 0.99996823), (5, -0.058117405), (6, -0.021589279), (7, 0.013524055), (8, 0.25163394)]。可以看到显然属于第一类。


 

转载自:https://www.cnblogs.com/wangqingyi/articles/5911647.html


转载于:https://www.cnblogs.com/nlpvv/articles/10953896.html


推荐阅读
  • 在本教程中,我们将看到如何使用FLASK制作第一个用于机器学习模型的RESTAPI。我们将从创建机器学习模型开始。然后,我们将看到使用Flask创建AP ... [详细]
  • Spring源码解密之默认标签的解析方式分析
    本文分析了Spring源码解密中默认标签的解析方式。通过对命名空间的判断,区分默认命名空间和自定义命名空间,并采用不同的解析方式。其中,bean标签的解析最为复杂和重要。 ... [详细]
  • 本文介绍了在Python3中如何使用选择文件对话框的格式打开和保存图片的方法。通过使用tkinter库中的filedialog模块的asksaveasfilename和askopenfilename函数,可以方便地选择要打开或保存的图片文件,并进行相关操作。具体的代码示例和操作步骤也被提供。 ... [详细]
  • eclipse学习(第三章:ssh中的Hibernate)——11.Hibernate的缓存(2级缓存,get和load)
    本文介绍了eclipse学习中的第三章内容,主要讲解了ssh中的Hibernate的缓存,包括2级缓存和get方法、load方法的区别。文章还涉及了项目实践和相关知识点的讲解。 ... [详细]
  • 本文讨论了一个关于cuowu类的问题,作者在使用cuowu类时遇到了错误提示和使用AdjustmentListener的问题。文章提供了16个解决方案,并给出了两个可能导致错误的原因。 ... [详细]
  • 本文介绍了计算机网络的定义和通信流程,包括客户端编译文件、二进制转换、三层路由设备等。同时,还介绍了计算机网络中常用的关键词,如MAC地址和IP地址。 ... [详细]
  • 本文介绍了如何使用python从列表中删除所有的零,并将结果以列表形式输出,同时提供了示例格式。 ... [详细]
  • 超级简单加解密工具的方案和功能
    本文介绍了一个超级简单的加解密工具的方案和功能。该工具可以读取文件头,并根据特定长度进行加密,加密后将加密部分写入源文件。同时,该工具也支持解密操作。加密和解密过程是可逆的。本文还提到了一些相关的功能和使用方法,并给出了Python代码示例。 ... [详细]
  • Python的参数解析argparse模块的学习
    本文介绍了Python中参数解析的重要模块argparse的学习内容。包括位置参数和可选参数的定义和使用方式,以及add_argument()函数的详细参数关键字解释。同时还介绍了命令行参数的操作和可接受数量的设置,其中包括整数类型的参数。通过学习本文内容,可以更好地理解和使用argparse模块进行参数解析。 ... [详细]
  • 本文介绍了使用PHP实现断点续传乱序合并文件的方法和源码。由于网络原因,文件需要分割成多个部分发送,因此无法按顺序接收。文章中提供了merge2.php的源码,通过使用shuffle函数打乱文件读取顺序,实现了乱序合并文件的功能。同时,还介绍了filesize、glob、unlink、fopen等相关函数的使用。阅读本文可以了解如何使用PHP实现断点续传乱序合并文件的具体步骤。 ... [详细]
  • 本文介绍了iOS数据库Sqlite的SQL语句分类和常见约束关键字。SQL语句分为DDL、DML和DQL三种类型,其中DDL语句用于定义、删除和修改数据表,关键字包括create、drop和alter。常见约束关键字包括if not exists、if exists、primary key、autoincrement、not null和default。此外,还介绍了常见的数据库数据类型,包括integer、text和real。 ... [详细]
  • 开发笔记:实验7的文件读写操作
    本文介绍了使用C++的ofstream和ifstream类进行文件读写操作的方法,包括创建文件、写入文件和读取文件的过程。同时还介绍了如何判断文件是否成功打开和关闭文件的方法。通过本文的学习,读者可以了解如何在C++中进行文件读写操作。 ... [详细]
  • CentOS7.8下编译muduo库找不到Boost库报错的解决方法
    本文介绍了在CentOS7.8下编译muduo库时出现找不到Boost库报错的问题,并提供了解决方法。文章详细介绍了从Github上下载muduo和muduo-tutorial源代码的步骤,并指导如何编译muduo库。最后,作者提供了陈硕老师的Github链接和muduo库的简介。 ... [详细]
  • 安装oracle软件1创建用户组、用户和目录bjdb节点下:[rootnode1]#groupadd-g200oinstall[rootnode1]#groupad ... [详细]
  • 工作经验谈之-让百度地图API调用数据库内容 及详解
    这段时间,所在项目中要用到的一个模块,就是让数据库中的内容在百度地图上展现出来,如经纬度。主要实现以下几点功能:1.读取数据库中的经纬度值在百度上标注出来。2.点击标注弹出对应信息。3 ... [详细]
author-avatar
mobiledu2502887897
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有