【发布时间】:2020-05-15 08:16:00
【问题描述】:
我尝试使用余弦距离 (source) 计算两个单词的相似度。 这是代码:
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]
当我调用时相似度为 0.1889822365046136:
cosdis(word2vec('tahu') , word2vec('tempe'))
当尝试使用库(gensim word2vec)与相似性结果进行比较时,结果是不同的(例如差异为 0.2)。这是为什么? 这就是我使用库获得相似性的方式:
from gensim.models import Word2Vec
modelword2vec = Word2Vec.load("/idwiki_word2vec_300.model")
modelword2vec.similarity('tahu' , 'tempe')
相似度为0.21785985
【问题讨论】:
-
这种基于字符的表示,虽然它是从“单词”派生的“向量”,但它并不是真正的“word2vec”算法。但是,您能否在代码中更清楚地说明(1)您正在应用哪些库计算函数,以及它们的测试输入结果; (2) 你的代码为这些相同的测试输入返回什么?此外,不确定您的
cosdis()是否与“余弦距离”的通常定义相匹配,并且请记住,“余弦距离”和“余弦相似度”是相关但不同的:“最接近”的词接近1.0余弦相似度,但是0.0余弦距离。 -
我已经在问题中编辑了我如何调用库来计算相似度。
标签: python nlp cosine-similarity edit-distance