【发布时间】:2019-03-08 16:40:53
【问题描述】:
我是 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)]
【问题讨论】:
-
你能解释一下“列表之间最相似的句子”是什么意思吗?您提供的几个示例“列表”作为输入,然后是所需的输出? (另外:您正在使用一个非常大的
alpha,然后自己多次调用train(),使alpha非常大。最好保留默认的alpha并只调用train()一次,使用您想要的epochs计数,让代码为您做正确的事情。) -
谢谢@gojomo,我添加了一个例子。我发现
alpha在第一次训练我的模型时效果最好,但很高兴知道,所以我会尝试一些其他值。 -
所以您想计算
list1中每个项目与list2的成对相似度?看起来您已经有了工作代码,那么还有什么未决的需求? (或者,你还没有'similarity()`函数吗?) -
请注意,您当前显示的代码在其
alpha和train()管理中非常不典型,以至于达到荒谬的程度。它正在执行 10 个train()s,但第一个执行 0 个传递,最后一个执行 9 个传递,并且每个train()将有效 alpha 从0.2衰减到0.0001- 一个下降和上升的锯齿模式。这是不正确的 SGD,会导致早期文本总是以高 alpha 进行训练,而后期文本总是以低 alpha 进行训练。你应该得到一个更好的模型和更多的默认/理智的做法。 -
问题中的代码仍然在循环中显示
train(),每个train()执行更多内部epochs。也许 500 对简短的语料库(也许是小的个人文档?)有帮助,并且进一步通过给词向量(通过dbow_words=1)提供更多的培训会继续提供帮助——这远远超出了大型语料库和已发表作品的典型情况。
标签: python-3.x nlp data-science cosine-similarity doc2vec