corpora基本概念:
corpora是gensim中的一个基本概念,是文档集的表现形式,也是后续进一步处理的基础。从本质上来说,corpora其实是一种格式或者说约定,其实就是一个二维矩阵。在实际运行中,因为单词数量极多(上万甚至10万级别),而一篇文档的单词数是有限的,所以如果还是采用密集矩阵来表示的话,会造成极大的内存浪费,所以gensim内部是用稀疏矩阵的形式来表示的。
from gensim import corpora
from collections import defaultdict
import os
from gensim import corpora, models, similarities
from pprint import pprint
from matplotlib import pyplot as plt
# gensim是一个python的自然语言处理库,能够将文档根据TF-IDF, LDA, LSI 等模型转化成向量模式,
# 以便进行进一步的处理。此外,gensim还实现了word2vec功能,能够将单词转化为词向量。
# 词典操作
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())
print(stoplist)
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
print(frequency)
texts = [[token for token in text if frequency[token] > 1]
for text in texts]
print(texts)
dictionary = corpora.Dictionary(texts) # 生成词典
# 将文档存入字典,字典有很多功能,比如
# diction.token2id 存放的是单词-id key-value对
# diction.dfs 存放的是单词的出现频率
print(dictionary.token2id)
print(dictionary.dfs)
dictionary.save('./tmp/deerwester.dict') # store the dictionary, for future reference
corpus = [dictionary.doc2bow(text) for text in texts]
print(corpus)
# 序列化
# corpora.MmCorpus.serialize 将corpus持久化到磁盘中.
# 除了MmCorpus以外,还有其他的格式,例如SvmLightCorpus, BleiCorpus, LowCorpus等等,用法类似
corpora.MmCorpus.serialize('./tmp/deerwester.mm', corpus) # store to disk, for later use
# 反序列化
corpus = corpora.MmCorpus('./tmp/deerwester.mm')
# 其他操作
# 过滤掉出现频率最高的N个单词
dictionary.filter_n_most_frequent(4)
print(dictionary.dfs)
# 1.去掉出现次数低于no_below的
# 2.去掉出现次数高于no_above的。注意这个小数指的是百分数
# 3.在1和2的基础上,保留出现频率前keep_n的单词
dictionary.filter_extremes(no_below=1, no_above=0.5, keep_n=5)
print(dictionary.dfs)
# 有两种用法,一种是去掉bad_id对应的词,另一种是保留good_id对应的词而去掉其他词。注意这里bad_ids和good_ids都是列表形式
dictionary.filter_tokens(bad_ids=None, good_ids=None)
# models
# 在models中,可以对corpus进行进一步的处理,比如使用tf-idf模型,lsi模型,lda模型等
def PrintDictionary(dictionary):
token2id = dictionary.token2id
dfs = dictionary.dfs
token_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]
print(doc_tfidf)
# 将整个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)
print("lsi主题向量:\n", nodes)
pprint(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, random_state=1)
corpus_lda = lda_model[corpus_tfidf]
Show2dCorpora(corpus_lda)
nodes = list(corpus_lda)
pprint(list(corpus_lda))
# 此外,还有Random Projections, Hierarchical Dirichlet Process等模型
# similarities
# 负责计算文档间的相似度。与向量的相似度计算方式一样,采用余弦方法计算得到。
# 一般来讲,使用lsi模型得到的向量进行计算效果比较好。
corpus_simi_matrix = similarities.MatrixSimilarity(corpus_lsi, num_best=2)
# 计算一个新的文本与既有文本的相关度
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)))
原文:
https://www.cnblogs.com/nlpvv/articles/10953896.html