1

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

以下是本文的代码:

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'])

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

4

3 回答 3

3

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

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

基于此,'2' indexindata最接近请求的数据,即test_data.

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

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

于 2019-10-02T18:57:58.640 回答
2

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

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

分别地:

train()像您正在做的那样在循环中多次调用是一个糟糕且容易出错的想法,就像管理alpha/min_alpha显式一样。您不应遵循任何推荐该方法的教程/指南。

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

于 2019-10-02T20:48:16.200 回答
1

要获得实际结果,您必须将文本作为向量传递给 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'])

语义“相似句子”与您的数据集-NLP

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

pip install similar-sentences
于 2020-04-16T12:07:03.467 回答