我试图使用潜在的语义索引来根据一个大型语料库产生的主题来生成两句句子之间的余弦相似度,但我很难找到任何完全符合我所寻找的内容的教程--我发现的最接近的是Semantic Similarity between Phrases Using GenSim,但我并不想找到与查询最相似的句子,我特别想使用LSI模型来降低两句句子的维数,然后测量这两句话的余弦相似度。有人能帮忙吗?
从引用的文章中,我想我可能看了下面的代码,然后进行余弦相似度计算?但我被困住了。
import gensim
from gensim import corpora, models, similarities
from gensim.models import LsiModel
# texts = list of list of words from a database
dictionary = corpora.Dictionary(texts)
corpus = [dictionary.doc2bow(text) for text in texts]
lsi = models.LsiModel(corpus, id2word=dictionary, num_topics=400)
doc_1 = "Mary and Samantha arrived at the bus station early but waited until noon for the bus"
doc_2 = "when the seagulls follow the trawler, it is because they think sardines will be dropped in the sea"
vec_bow_1 = dictionary.doc2bow(doc_1.lower().split())
vec_bow_2 = dictionary.doc2bow(doc_2.lower().split())
vec_lsi_1 = lsi[vec_bow_1]
vec_lsi_2 = lsi[vec_bow_2]发布于 2022-07-13 23:36:35
如果您已经成功地使vec_lsi_1成为您的doc1的向量,而vec_lsi_2成为您的doc2的向量,那么您是否尝试过简单地计算这两个向量之间的余弦相似性?余弦相似度的计算方法是取两个向量的点积,然后除以它们的单位范数。例:
import numpy as np
cossim = (
np.dot(vec_lsi_1, vec_lsi_2)
/
(np.linalg.norm(vec_lsi_1) * np.linalg.norm(vec_lsi_2))
)更新的完整性:,如果vec_lsi_1等是稀疏向量--假定未提及的索引为0.0的某种形式的(index, value) --那么np.dot()可能无法直接工作;参见https://radimrehurek.com/gensim/matutils.html#gensim.matutils.sparse2full中的帮助函数,以将Gensim的稀疏格式转换为密集的numpy向量。
https://stackoverflow.com/questions/72972973
复制相似问题