使用Doc2Vec的句子列表之间的余弦相似度

问题描述 投票:1回答:1

我是NLP的新手,但是我试图根据语义相似性将句子列表与Python中的另一个句子列表相匹配。例如,

list1 = ['what they ate for lunch', 'height in inches', 'subjectid']
list2 = ['food eaten two days ago', 'height in centimeters', 'id']

根据之前的帖子和先前的知识,似乎最好的方法是创建每个句子的文档向量并计算列表之间的余弦相似度得分。我发现的关于Doc2Vec的其他帖子,以及教程,似乎都集中在预测上。 This post手工完成计算,但我认为Doc2Vec已经可以做到这一点。我正在使用的代码是

import gensim
from gensim.models.doc2vec import Doc2Vec, TaggedDocument

def build_model(train_docs, test_docs, comp_docs):
    '''
    Parameters
    -----------
    train_docs: list of lists - combination of known both sentence list
    test_docs: list of lists - one of the sentence lists
    comp_docs: list of lists - combined sentence lists to match the index to the sentence 
    '''
    # Train model
    model = Doc2Vec(dm = 0, dbow_words = 1, window = 2, alpha = 0.2)#, min_alpha = 0.025)
    model.build_vocab(train_docs)
    for epoch in range(10):
        model.train(train_docs, total_examples = model.corpus_count, epochs = epoch)
        #model.alpha -= 0.002
        #model.min_alpha = model.alpha


    scores = []

    for doc in test_docs:
        dd = {}
        # Calculate the cosine similarity and return top 40 matches
        score = model.docvecs.most_similar([model.infer_vector(doc)],topn=40)
        key = " ".join(doc)
        for i in range(len(score)):
            # Get index and score
            x, y = score[i]
            #print(x)
            # Match sentence from other list
            nkey = ' '.join(comp_docs[x])
            dd[nkey] = y
        scores.append({key: dd})

    return scores

它用于计算相似性得分,但问题在于我必须在两个列表或其中一个列表的所有句子上训练模型,然后进行匹配。有没有办法使用Doc2Vec来获取向量,然后计算余弦相似度?要清楚,我正试图在列表之间找到最相似的句子。我希望输出像

scores = []
for s1 in list1:
    for s2 in list2:
        scores.append((s1, s2, similarity(s1, s2)))

print(scores)
[('what they ate for lunch', 'food eaten two days ago', 0.23567),
 ('what they ate for lunch', 'height in centimeters', 0.120),
 ('what they ate for lunch', 'id', 0.01023),
 ('height in inches', 'food eaten two days ago', 0.123),
 ('height in inches', 'height in centimeters', 0.8456),
 ('height in inches', 'id', 0.145),
 ('subjectid', 'food eaten two days ago', 0.156),
 ('subjectid', 'height in centimeters', 0.1345),
 ('subjectid', 'id', 0.9567)]
python-3.x nlp data-science cosine-similarity doc2vec
1个回答
0
投票

Doc2vec可以生成一个向量,如果你为它提供了你想要它生成一个向量的单词,那么doc2vec模型就需要存在。但是,这个模型不一定需要训练你想要比较的句子。我不知道是否存在doc2vec预生成模型,但我知道你可以导入具有预训练向量的word2vec模型。你是否想要这样做取决于你所比较的句子类型 - 通常word2vec模型是在维基百科或20newsgroup等语料库上训练的。因此,对于这些文章中不常出现的单词,他们可能没有向量(或不良向量),即如果您试图将句子与许多科学术语进行比较,则可能不希望使用预训练模型。但是,如果没有先培训模型,您将无法生成矢量(我认为这是您的核心问题)。

© www.soinside.com 2019 - 2024. All rights reserved.