【问题标题】:Doc2Vec find the similar sentenceDoc2Vec 找到类似的句子
【发布时间】:2019-10-02 17:39:01
【问题描述】:

我正在尝试使用 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'])

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

【问题讨论】:

    标签: python nlp gensim doc2vec sentence-similarity


    【解决方案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
    

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

    【讨论】:

      【解决方案2】:

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

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

      分别:

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

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

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2010-11-22
          • 2015-01-23
          • 1970-01-01
          • 2020-12-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多