使用Word2vec确定一组单词中哪两个单词最相似

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

我试图使用Word2vec周围的python包装器。我有一个单词嵌入或一组单词可以在下面看到,我试图确定哪两个单词彼此最相似。

我怎样才能做到这一点?

['建筑师','护士','外科医生','祖母','爸爸']

python word2vec
2个回答
1
投票

@ rylan-feldspar的答案通常是正确的方法并且可以工作,但你可以使用标准的Python库/习语,特别是itertools,列表理解和排序功能,更紧凑地做到这一点。

例如,首先使用combinations()中的itertools生成所有候选词对:

from itertools import combinations
candidate_words = ['architect', 'nurse', 'surgeon', 'grandmother', 'dad']
all_pairs = combinations(candidate_words, 2)

然后,用它们的成对相似度装饰这些对:

scored_pairs = [(w2v_model.wv.similarity(p[0], p[1]), p)
                for p in all_pairs]

最后,排序将最相似的对放在第一位,并报告该得分和对:

sorted_pairs = sorted(scored_pairs, reverse=True)
print(sorted_pairs[0])  # first item is most-similar pair

如果你想要紧凑但可读性稍差,它可能是一个(长)“1-liner”:

print(sorted([(w2v_model.wv.similarity(p[0], p[1]), p) 
              for p in combinations(candidate_words, 2)
             ], reverse=True)[0])

更新:

整合@ ryan-feldspar关于max()的建议,并追求最低限度,这也应该能够报告最好的一对(但不是它的得分):

print(max(combinations(candidate_words, 2),
          key=lambda p:w2v_model.wv.similarity(p[0], p[1])))

2
投票

根据你的评论,鉴于你正在使用gensim的word2vec:

加载或训练嵌入模型,然后在模型上调用:

min_distance = float('inf')
min_pair = None
word2vec_model_wv = model.wv  # Unsure if this can be done in the loop, but just to be safe efficiency-wise
for candidate_word1 in words:
    for candidate_word2 in words:
        if candidate_word1 == candidate_word2:
            continue  # ignore when the two words are the same

        distance = word2vec_model_wv.distance(candidate_word1, candidate_word2)
        if distance < min_distance:
            min_pair = (candidate_word1, candidate_word2)
            min_distance = distance

https://radimrehurek.com/gensim/models/keyedvectors.html#gensim.models.keyedvectors.WordEmbeddingsKeyedVectors.distance

也可能是相似性(我不完全确定是否存在差异)。 https://radimrehurek.com/gensim/models/keyedvectors.html#gensim.models.keyedvectors.WordEmbeddingsKeyedVectors.similarity

如果相似度随着更接近的单词变得更大,正如我所期望的那样,那么你将希望最大化而不是最小化并且仅用相似性调用替换距离函数调用。基本上这只是对的简单最小/最大函数。

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