首页 > 解决方案 > 使用Word2vec判断一组词中哪两个词最相似

问题描述

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

我怎样才能做到这一点?

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

标签: pythonword2vec

解决方案


根据您的评论,鉴于您使用的是 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

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


推荐阅读