我想使用围绕Word2vec的Python包装器。下面是一个单词嵌入或一组单词,我正在尝试从中确定哪两个单词最相似。
我该怎么做?
['architect', 'nurse', 'surgeon', 'grandmother', 'dad']
我想使用围绕Word2vec的Python包装器。下面是一个单词嵌入或一组单词,我正在尝试从中确定哪两个单词最相似。
我该怎么做?
['architect', 'nurse', 'surgeon', 'grandmother', 'dad']
@rylan-feldspar的回答通常是正确的方法,会起作用,但您可以使用标准Python库/惯用语更紧凑地完成此操作,特别是使用itertools
、列表推导式和排序函数。
例如,首先使用itertools
中的combinations()
生成所有候选单词对:
Original Answer翻译成"最初的回答"
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
print(sorted([(w2v_model.wv.similarity(p[0], p[1]), p)
for p in combinations(candidate_words, 2)
], reverse=True)[0])
更新:
结合 @ryan-feldspar 的建议,采用最小化的方式,以下代码也可以报告最佳匹配对(但不包括其得分):
print(max(combinations(candidate_words, 2),
key=lambda p:w2v_model.wv.similarity(p[0], p[1])))
max(scored_pairs, key=lambda p: p[1])
或差异的min
可能更有效。 - Will Tmax()
比完整排序略微更有效率,可以在单次遍历中抓取最佳项。由于元组中分数在第一个([0]
)索引中,我认为您不需要指定一个key
:逐个元素进行比较,从p[0]
开始,只有在早期元素中存在平局时才会继续比较p[1]
(等等)。 (但您也可以完全跳过推导/排序,并使用计算对的相似性的max()
和key
函数!) - gojomo如果你正在使用gensim的word2vec,根据你的评论:
加载或训练嵌入模型,然后在你的模型上调用:
most_similar()
以获取与给定单词最相似的单词列表。
原始回答:Original Answer
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