从gensim解释负面的Word2Vec相似性

时间:2017-02-22 03:00:47

标签: python nlp similarity gensim word2vec

E.g。我们使用gensim训练word2vec模型:

from gensim import corpora, models, similarities
from gensim.models.word2vec import Word2Vec

documents = ["Human machine interface for lab abc computer applications",
              "A survey of user opinion of computer system response time",
              "The EPS user interface management system",
              "System and human system engineering testing of EPS",
              "Relation of user perceived response time to error measurement",
              "The generation of random binary unordered trees",
              "The intersection graph of paths in trees",
              "Graph minors IV Widths of trees and well quasi ordering",
              "Graph minors A survey"]

texts = [[word for word in document.lower().split()] for document in documents]
w2v_model = Word2Vec(texts, size=500, window=5, min_count=1)

当我们查询单词之间的相似性时,我们发现负相似性得分:

>>> w2v_model.similarity('graph', 'computer')
0.046929569156789336
>>> w2v_model.similarity('graph', 'system')
0.063683518562347399
>>> w2v_model.similarity('survey', 'generation')
-0.040026775040430063
>>> w2v_model.similarity('graph', 'trees')
-0.0072684112978664561

我们如何解读负面分数?

如果余弦相似度的范围不是[0,1]

Word2Vec.similarity(x,y)函数的上限和下限是什么?文档中没有写得多:https://radimrehurek.com/gensim/models/word2vec.html#gensim.models.word2vec.Word2Vec.similarity =(

查看Python包装器代码,也不是很多:https://github.com/RaRe-Technologies/gensim/blob/develop/gensim/models/word2vec.py#L1165

(如果可能,请指出我实施相似性功能的.pyx代码。)

2 个答案:

答案 0 :(得分:9)

余弦相似度的范围为-1到1,与常规余弦波相同。

Cosine Wave

至于来源:

https://github.com/RaRe-Technologies/gensim/blob/ba1ce894a5192fc493a865c535202695bb3c0424/gensim/models/word2vec.py#L1511

def similarity(self, w1, w2):
    """
    Compute cosine similarity between two words.
    Example::
      >>> trained_model.similarity('woman', 'man')
      0.73723527
      >>> trained_model.similarity('woman', 'woman')
      1.0
    """
    return dot(matutils.unitvec(self[w1]), matutils.unitvec(self[w2])

答案 1 :(得分:-1)

正如其他人所说,基于被比较的两个矢量之间的角度,余弦相似度的范围可以从-1到1。 gensim中的确切实现是归一化向量的简单点积。

https://github.com/RaRe-Technologies/gensim/blob/4f0e2ae0531d67cee8d3e06636e82298cb554b04/gensim/models/keyedvectors.py#L581

def similarity(self, w1, w2):
        """
        Compute cosine similarity between two words.
        Example::
          >>> trained_model.similarity('woman', 'man')
          0.73723527
          >>> trained_model.similarity('woman', 'woman')
          1.0
        """
        return dot(matutils.unitvec(self[w1]), matutils.unitvec(self[w2]))

在解释方面,您可以考虑这些值,就像您可能会想到相关系数一样。值1是单词向量之间的完美关系(例如,"女性"与"女性"相比),值0表示单词之间没有关系,值为-1代表了一种完美的对立关系。