使用gensim计算文档的相似度

gensim是一个主题模型的python库,可以在官网下载http://radimrehurek.com/gensim/index.html

以下代码使用gensim来计算文档之间的相关性,使用的是tfidf模型。文档在下面用一句话代替
from gensim import corpora,models,similarities


#nine documents,each consisting of only a single sentence
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"]

#remove commen words and tokenize
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]

#remove words that appear only once
from collections import defaultdict
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]

from pprint import pprint
pprint(texts)

dictionary=corpora.Dictionary(texts)
dictionary.save('/tmp/deerwester.dict') #store the dictionary,for future reference

print(dictionary)
print(dictionary.token2id)

new_doc="Human computer interaction"
#the word 'interaction' does not appear in the dictionary and is ignored
new_vec=dictionary.doc2bow(new_doc.lower().split())
print(new_vec)

corpus=[dictionary.doc2bow(text) for text in texts]
corpora.MmCorpus.serialize('/tmp/deerwester.mm',corpus) #store to dist,for later use
pprint(corpus)


#set tfidf model
tfidf=models.TfidfModel(corpus)

featureNum=len(dictionary.token2id.keys())
index = similarities.SparseMatrixSimilarity(tfidf[corpus], num_features=featureNum)
sims=index[tfidf[new_vec]]

print(sims)



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值