【NLP学习笔记】(三)gensim使用之相似性查询(Similarity Queries)

简介:

相似性查询(Similarity Queries)

本文主要翻译自https://radimrehurek.com/gensim/tut3.html
在之前的教程语料和向量空间主题和转换中,我们学会了如何在向量空间模型中表示语料和如何在不同的向量空间之间转换。实际工作中,这样做的一个最常见的目的是比较两个文档之间的相似性或比较某一个文档与其它文档的相似性(比如用户查询已经索引的文档中的某一个文档)

加载字典和语料

与上一章相同,首先加载第一章中保存的字典和语料。

from gensim import corpora, models, similarities
import os
if(os.path.exists('./gensim_out/deerwester.dict')):
    dictionary = corpora.Dictionary.load('./gensim_out/deerwester.dict')
    corpus = corpora.MmCorpus('./gensim_out/deerwester.mm')
    print("使用之前已经存储的字典和语料向量")
else:
    print("请先通过第一章生成deerwester.dict和deerwester.mm")

第一步

定义模型LSI,并将语料corpus转换为索引

lsi = models.LsiModel(corpus, id2word=dictionary, num_topics=2)

index = similarities.MatrixSimilarity(lsi[corpus])
index.save('./gensim_out/deerwester.index') #保存训练后的index
index = similarities.MatrixSimilarity.load('./gensim_out/deerwester.index')#从已保存的文件中加载index。


第二步

假设我们要查询新文本 'human computer interaction'。我们期望得出与新文本最相思的三个文本。

doc = 'human computer interaction'
vec_bow = dictionary.doc2bow(doc.lower().split())
vec_lsi = lsi[vec_bow]
print(vec_lsi)

第三步

比较新文本vec_lsi与语料库的相似性

sims = index[vec_lsi]
print(list(enumerate(sims))) #打印结果(document_number, document_similarity) 2-tuples

上面结果为:
[(0, 0.99809301), (1, 0.93748635), (2, 0.99844527), (3, 0.9865886), (4, 0.90755945),(5, -0.12416792), (6, -0.1063926), (7, -0.098794639), (8, 0.05004178)]

(0, 0.99809301)的意思是第0篇文章与新文档的相似性为 0.99809301

将上面结果按相似性降序排列

sims = sorted(enumerate(sims), key = lambda item : -item[1])
print(sims)

结果:

[(2, 0.99844527), # The EPS user interface management system
(0, 0.99809301), # Human machine interface for lab abc computer applications
(3, 0.9865886), # System and human system engineering testing of EPS
(1, 0.93748635), # A survey of user opinion of computer system response time
(4, 0.90755945), # Relation of user perceived response time to error measurement
(8, 0.050041795), # Graph minors A survey
(7, -0.098794639), # Graph minors IV Widths of trees and well quasi ordering
(6, -0.1063926), # The intersection graph of paths in trees
(5, -0.12416792)] # The generation of random binary unordered trees

可以看出与文档“human computer interface”最相似的三篇文章分别是第2篇、第0篇、第三篇。

目录
相关文章
|
12月前
|
自然语言处理 算法
NLP学习笔记(十) 分词(下)
NLP学习笔记(十) 分词(下)
98 0
|
12月前
|
机器学习/深度学习 自然语言处理
NLP学习笔记(八) GPT简明介绍 下
NLP学习笔记(八) GPT简明介绍
131 0
|
12月前
|
自然语言处理
NLP学习笔记(八) GPT简明介绍 上
NLP学习笔记(八) GPT简明介绍
109 0
|
12月前
|
自然语言处理
NLP学习笔记(七) BERT简明介绍 下
NLP学习笔记(七) BERT简明介绍
148 0
NLP学习笔记(七) BERT简明介绍 下
|
12月前
|
机器学习/深度学习 自然语言处理
NLP学习笔记(七) BERT简明介绍 上
NLP学习笔记(七) BERT简明介绍
90 0
|
12月前
|
机器学习/深度学习 自然语言处理 计算机视觉
NLP学习笔记(六) Transformer简明介绍
NLP学习笔记(六) Transformer简明介绍
136 0
|
12月前
|
机器学习/深度学习 自然语言处理
NLP学习笔记(五) 注意力机制
NLP学习笔记(五) 注意力机制
114 0
|
12月前
|
机器学习/深度学习 自然语言处理
NLP学习笔记(四) Seq2Seq基本介绍
NLP学习笔记(四) Seq2Seq基本介绍
118 0
|
12月前
|
机器学习/深度学习 自然语言处理
NLP学习笔记(三) GRU基本介绍
NLP学习笔记(三) GRU基本介绍
184 0
|
12月前
|
机器学习/深度学习 自然语言处理 资源调度
NLP学习笔记(二) LSTM基本介绍
NLP学习笔记(二) LSTM基本介绍
145 0
NLP学习笔记(二) LSTM基本介绍