NLP

LSI(LSA)和gensim中的实现

2019-07-10  本文已影响0人  华小锐

LSI原理

通过SVD将文档与词的TF-IDF的矩阵进行分解。SVD分解后的三个矩阵是文档与主题,主题与词义,词义与词三个矩阵,通过三个矩阵的不同解释,可以实现在降低维度的基础上有意义的解释。

文档与主题矩阵可以实现文档相似度的计算。词义与词的矩阵可以实现词相似度的计算,同时可以表示一意多词的情况。

gensim中LSI的使用

代码实现了bow形式表示语料->将bow中的次数转变成TF-IDF值->使用LSI方法对TF-IDF文档和词组成的矩阵进行分解。最后利用余弦相似度,根据文档和主题矩阵可以实现文档之间相似度的计算。依据就是主题类似的文档的相似度高。

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)

print(dictionary)

#把语料变成每个词对应的ID和出现的次数

corpus = [dictionary.doc2bow(text) for text in texts]

print (corpus) # [(0, 1), (1, 1), (2, 1)]

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")

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)

上一篇 下一篇

猜你喜欢

热点阅读