python-3.x - 使用 Doc2Vec 的句子列表之间的余弦相似度

标签 python-3.x nlp data-science cosine-similarity doc2vec

我是 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)]

最佳答案

如果您关心的是训练模型并在运行时获得结果是一项耗时的任务。然后考虑保存模式。您可以在单独的文件中训练模型并将其保存到磁盘中。

训练结束后

model.save("similar_sentence.model")

创建一个新文件并加载模型,如下所示,

model = Doc2Vec.load("similar_sentence.model")

模型文件将保存您训练好的句子中的向量。

模型对象可以在代码的任何地方保存和加载。

Semantic “Similar Sentences” with your dataset-NLP

关于python-3.x - 使用 Doc2Vec 的句子列表之间的余弦相似度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55067412/

相关文章:

python - Keras log_loss 错误是一样的

python - 获取句子中单词之间的关系

python - 将特征哈希应用于 DataFrame 中的特定列

machine-learning - 替换卡住 Tensorflow 模型中的节点

python - python给我的解决方案是什么 "ValueError: setting an array element with a sequence."

python - 将函数分配为python中有限状态机的变量

python - 仍然没有适用于 Python 3(或 3.3)的 wxPython?

python - 多表密码的 for 循环末尾未打印文本

r - 为什么 stemDocument 将结尾 'y' 更改为 'i' ?如何阻止它?

python - 在 scipy 中按稀疏矩阵分组并返回矩阵