我有两个包含字符串的列表,如下所示:
a_file = ['a', 'b', 'c']
b_file = ['b', 'x', 'y', 'z']
我想计算这两个列表的余弦相似度,我知道如何实现它:
# count word occurrences
a_vals = Counter(a_file)
b_vals = Counter(b_file)
# convert to word-vectors
words = list(a_vals.keys() | b_vals.keys())
a_vect = [a_vals.get(word, 0) for word in words]
b_vect = [b_vals.get(word, 0) for word in words]
# find cosine
len_a = sum(av*av for av in a_vect) ** 0.5
len_b = sum(bv*bv for bv in b_vect) ** 0.5
dot = sum(av*bv for av,bv in zip(a_vect, b_vect))
cosine = dot / (len_a * len_b)
print(cosine)
然而,如果我想在sklearn中使用cosine_similarity
,它会显示问题:could not convert string to float: 'a'
。如何纠正呢?
from sklearn.metrics.pairwise import cosine_similarity
a_file = ['a', 'b', 'c']
b_file = ['b', 'x', 'y', 'z']
print(cosine_similarity(a_file, b_file))
cosine_similarity([a_vect], [b_vect])
。第一:它需要词向量。 第二:它需要二维向量--就像在具有许多行的DataFrame
中。 - furas