列表中两个单词之间的余弦相似度

cosine similarity between two words in a list

我正在定义一个函数,它接受一个单词列表和 returns 列表中单词的信息,这些单词彼此之间具有非零余弦相似度(以及相似度值)。

谁能帮我解决这个问题。我在想,如果我能得到一个预先计算的 word2vec 矢量文件,那将非常有帮助,但互联网上有 none。

你可以定义这两个函数

def word2vec(word):
    from collections import Counter
    from math import sqrt

    # count the characters in word
    cw = Counter(word)
    # precomputes a set of the different characters
    sw = set(cw)
    # precomputes the "length" of the word vector
    lw = sqrt(sum(c*c for c in cw.values()))

    # return a tuple
    return cw, sw, lw

def cosdis(v1, v2):
    # which characters are common to the two words?
    common = v1[1].intersection(v2[1])
    # by definition of cosine distance we have
    return sum(v1[0][ch]*v2[0][ch] for ch in common)/v1[2]/v2[2]

并像本例中那样使用它们

>>> a = 'safasfeqefscwaeeafweeaeawaw'
>>> b = 'tsafdstrdfadsdfdswdfafdwaed'
>>> c = 'optykop;lvhopijresokpghwji7'
>>> 
>>> va = word2vec(a)
>>> vb = word2vec(b)
>>> vc = word2vec(c)
>>> 
>>> print cosdis(va,vb)
0.551843662321
>>> print cosdis(vb,vc)
0.113746579656
>>> print cosdis(vc,va)
0.153494378078

顺便说一句,您在标签中提到的 word2vec 是完全不同的业务,这需要我们中的一个人花费大量时间和精力来研究它,你猜怎么着,我不是那个...

这个呢?

scipy.spatial.distance.cosine(word2vec(a),word2vec(b))

你可以为此使用 word2vec 库。