Gensim-Doc2vec模型:如何计算使用预训练Doc2vec模型获得的语料库的相似度?

2024-04-19 02:16:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个基于doc2vec的多文档模型。我想用这个模型来推断另一个文档的向量,我想用它作为比较的语料库。所以,当我寻找与我介绍的句子最相似的句子时,它使用这个新的文档向量,而不是经过训练的语料库。 目前,我正在使用infer_vector()来计算新文档中每个句子的向量,但是我不能使用most_similar()函数来获得向量列表,它必须是KeyedVectors。在

我想知道是否有任何方法可以计算新文档的这些向量,允许使用most_similar()函数,或者是否需要计算新文档中每个句子和我单独介绍的句子之间的相似度(在本例中,Gensim中是否有任何实现允许我计算2个向量之间的余弦相似性。在

我是新来的Gensim和NLP,我愿意接受你的建议。在

我不能提供完整的代码,因为这是一个大学的项目,但以下是我遇到问题的主要部分。在

在对数据进行了一些预处理之后,我就这样训练我的模型:

documents = [TaggedDocument(doc, [i]) for i, doc in enumerate(train_data)]
assert gensim.models.doc2vec.FAST_VERSION > -1

cores = multiprocessing.cpu_count()

doc2vec_model = Doc2Vec(vector_size=200, window=5, workers=cores)
doc2vec_model.build_vocab(documents)
doc2vec_model.train(documents, total_examples=doc2vec_model.corpus_count, epochs=30)

我试着用这种方法计算新文档的向量:

^{pr2}$

然后我尝试计算新文档向量和输入短语之间的相似度:

text = str(input('Me: '))

tokens = text.split()

new_vector = doc2vec_model.infer_vector(tokens)

index = questions[i].most_similar([new_vector])

Tags: 方法函数文档模型mostmodel向量documents
1条回答
网友
1楼 · 发布于 2024-04-19 02:16:33

一个月前我在gensim==3.2.0中使用了一个肮脏的解决方案(语法可能已经改变)。在

您可以将推断的向量保存为keyedvertors格式。在

from gensim.models import KeyedVectors
from gensim.models.doc2vec import Doc2Vec
vectors = dict()
# y_names = doc2vec_model.docvecs.doctags.keys()
y_names = range(len(questions))

for name in y_names:
    # vectors[name] = doc2vec_model.docvecs[name]
    vectors[str(name)] = questions[name]
f = open("question_vectors.txt".format(filename), "w")
f.write("")
f.flush()
f.close()
f = open("question_vectors.txt".format(filename), "a")
f.write("{} {}\n".format(len(questions), doc2vec_model.vector_size))
for v in vectors:
    line = "{} {}\n".format(v, " ".join(questions[v].astype(str)))
    f.write(line)
f.close()

然后你可以加载和使用大多数相似的函数

^{pr2}$

另一个解决方案(特别是如果问题的数量不是那么多)将只是将问题转换为np.数组得到余弦距离),例如

import numpy as np

questions = np.array(questions)
texts_norm = np.linalg.norm(questions, axis=1)[np.newaxis].T
norm = texts_norm * texts_norm.T

product = np.matmul(questions, questions.T)
product = product.T / norm

# Otherwise the item is the closest to itself
for j in range(len(questions)):
    product[j, j] = 0

# Gives the top 10 most similar items to the 0th question
np.argpartition(product[0], 10)

相关问题 更多 >