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

时间:2015-04-07 05:39:18

标签: python word2vec

我正在定义一个函数,它接受一个单词列表并返回列表中单词之间具有非零,余弦相似性的信息(以及相似度值)。

任何人都可以帮我解决这个问题。我在想如果我能得到一个预先计算的word2vec矢量文件,那么它会非常有用,但互联网上没有。

2 个答案:

答案 0 :(得分:3)

您可以定义这两个功能

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是一个完全不同的业务,需要我们中的一个人花费大量的时间和承诺来研究它并猜测是什么,我不是那个...

答案 1 :(得分:0)

那呢?

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

您可以为此使用word2vec库。

相关问题