Doc2Vec 找到相似的句子

Doc2Vec find the similar sentence

我正在尝试使用 doc2vec 查找相似的句子。我找不到的是与受训句子匹配的实际句子。

下面是来自this article的代码:

from gensim.models.doc2vec import Doc2Vec, TaggedDocument
from nltk.tokenize import word_tokenize
data = ["I love machine learning. Its awesome.",
        "I love coding in python",
        "I love building chatbots",
        "they chat amagingly well"]

tagged_data = [TaggedDocument(words=word_tokenize(_d.lower()), tags=[str(i)]) for i, _d in enumerate(data)]
max_epochs = 100
vec_size = 20
alpha = 0.025

model = Doc2Vec(size=vec_size,
                alpha=alpha, 
                min_alpha=0.00025,
                min_count=1,
                dm =1)
  
model.build_vocab(tagged_data)

for epoch in range(max_epochs):
    print('iteration {0}'.format(epoch))
    model.train(tagged_data,
                total_examples=model.corpus_count,
                epochs=model.iter)
    # decrease the learning rate
    model.alpha -= 0.0002
    # fix the learning rate, no decay
    model.min_alpha = model.alpha

model.save("d2v.model")
print("Model Saved")

model= Doc2Vec.load("d2v.model")
#to find the vector of a document which is not in training data
test_data = word_tokenize("I love building chatbots".lower())
v1 = model.infer_vector(test_data)
print("V1_infer", v1)

# to find most similar doc using tags
similar_doc = model.docvecs.most_similar('1')
print(similar_doc)


# to find vector of doc in training data using tags or in other words, printing the vector of document at index 1 in training data
print(model.docvecs['1'])

但上面的代码只给我向量或数字。但是我怎样才能从训练数据中得到匹配的实际句子。例如 - 在这种情况下,我期望结果为“我喜欢构建聊天机器人”。

similar_doc的输出是:[('2', 0.991769552230835), ('0', 0.989276111125946), ('3', 0.9854298830032349)]

这显示 data 中每个文档与请求文档的相似度得分,并按降序排列。

基于此,data中的'2' index最接近请求的数据即test_data

print(data[int(similar_doc[0][0])])
// prints: I love building chatbots

注意:这段代码每次都会给出不同的结果,也许您需要更好的模型或更多的训练数据。

Doc2Vec 不会在玩具大小的数据集上给出好的结果,因此在使用更多数据之前,您不应该期望任何有意义的东西。

而且,Doc2Vec 模型本身不会保留您在训练期间提供的完整文本。它只记住每个文本的 tag 的学习向量——这通常是一个唯一标识符。因此,当您从 most_similar() 取回结果时,您将取回 tag 值,然后您需要自己在自己的 code/data 中查找这些值以检索完整文档。

分开:

在循环中多次调用 train() 是一个糟糕且容易出错的想法,显式管理 alpha/min_alpha 也是如此。您不应遵循任何推荐该方法的 tutorial/guide。

不要更改 alpha 参数的默认值,并使用您想要的 epochs 计数调用 train() 一次——它会执行正确的遍数,并且正确的学习率管理。

要获得实际结果,您必须将文本作为向量传递给 most_simlar 方法以获得实际结果。对 most_similar(1) 进行硬编码将始终给出静态结果。

similar_doc = model.docvecs.most_similar([v1])

您的代码的修改版本

from gensim.models.doc2vec import Doc2Vec, TaggedDocument
from nltk.tokenize import word_tokenize
data = ["I love machine learning. Its awesome.",
        "I love coding in python",
        "I love building chatbots",
        "they chat amagingly well"]

def output_sentences(most_similar):
    for label, index in [('MOST', 0), ('SECOND-MOST', 1), ('MEDIAN', len(most_similar)//2), ('LEAST', len(most_similar) - 1)]:
      print(u'%s %s: %s\n' % (label, most_similar[index][1], data[int(most_similar[index][0])])))

tagged_data = [TaggedDocument(words=word_tokenize(_d.lower()), tags=[str(i)]) for i, _d in enumerate(data)]
max_epochs = 100
vec_size = 20
alpha = 0.025

model = Doc2Vec(size=vec_size,
                alpha=alpha, 
                min_alpha=0.00025,
                min_count=1,
                dm =1)

model.build_vocab(tagged_data)

for epoch in range(max_epochs):
    print('iteration {0}'.format(epoch))
    model.train(tagged_data,
                total_examples=model.corpus_count,
                epochs=model.iter)
    # decrease the learning rate
    model.alpha -= 0.0002
    # fix the learning rate, no decay
    model.min_alpha = model.alpha

model.save("d2v.model")
print("Model Saved")

model= Doc2Vec.load("d2v.model")
#to find the vector of a document which is not in training data
test_data = word_tokenize("I love building chatbots".lower())
v1 = model.infer_vector(test_data)
print("V1_infer", v1)

# to find most similar doc using tags
similar_doc = model.docvecs.most_similar([v1])
print(similar_doc)

# to print similar sentences
output_sentences(similar_doc) 


# to find vector of doc in training data using tags or in other words, printing the vector of document at index 1 in training data
print(model.docvecs['1'])

Semantic “Similar Sentences” with your dataset-NLP

如果您正在使用您的数据集寻找准确的预测,而您的数据集较少,您可以选择,

pip install similar-sentences