#将句子转成词典中对应的ID值和出现的次数对应的关系
texts = [['human', 'interface', 'computer''human'],
['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']]
from gensim import corpora
#词典
dictionary = corpora.Dictionary(texts)
#格式 词ID:数量
corpus = [dictionary.doc2bow(text) for text in texts]
print(corpus[0]) # [(0, 1), (1, 1), (2, 1)]
#将上述处理后的语料出现此处根据TF-IDF计算成各自对应的值
from gensim import models
tfidf = models.TfidfModel(corpus)
doc_bow = [(0, 1), (1, 1)]
print tfidf[doc_bow] # [(0, 0.70710678), (1, 0.70710678)]
#保存TF-IDF模型
tfidf.save("./model.tfidf")
#加载TF-IDF模型
tfidf = models.TfidfModel.load("./model.tfidf")
# 构造LSI模型并将待检索的query和文本转化为LSI主题向量
# 转换之前的corpus和query均是BOW向量
query = [(0, 1), (1, 1), (2, 1)]
#这个模型可以把语料中的稀疏的变量编程一个密集的向量,使用一个密集的向量可以表示这个句子
lsi_model = models.LsiModel(corpus, id2word=dictionary, num_topics=2)
documents = lsi_model[corpus]
print(documents[0])
query_vec = lsi_model[query]
from gensim.similarities import MatrixSimilarity
index = MatrixSimilarity(documents)
index.save('/tmp/deerwester.index')
index = MatrixSimilarity.load('/tmp/deerwester.index')
#检查了与所有语料中的余弦相似度
sims = index[query_vec] # return: an iterator of tuple (idx, sim)
print(sims)
总体的来说,首先用DOC2BOW表示一条句子,存在离散的缺点,之后使用TF-IDF根据不同的词所在环境的不同重要程度不同进一步的进行了句子的向量表示,最后使用LSI(LSA)模型对每个句子用一个密集的向量进行表示,表示完毕后,可以使用余弦相似度算法对相似度进行计算。接下来详细介绍LSI(LSA)模型