我想计算单词列表之间的相似度,例如:
import math,re
from collections import Counter
test = ['address','ip']
list_a = ['identifiant', 'ip', 'address', 'fixe', 'horadatee', 'cookie', 'mac', 'machine', 'network', 'cable']
list_b = ['address','city']
def counter_cosine_similarity(c1, c2):
terms = set(c1).union(c2)
print(c2.get('ip',0)**2)
dotprod = sum(c1.get(k, 0) * c2.get(k, 0) for k in terms)
magA = math.sqrt(sum(c1.get(k, 0)**2 for k in terms))
magB = math.sqrt(sum(c2.get(k, 0)**2 for k in terms))
return dotprod / (magA * magB)
counter1 = Counter(test)
counter2 = Counter(list_a)
counter3 = Counter(list_b)
score = counter_cosine_similarity(counter1,counter2)
print(score) # output : 0.4472135954999579
score = counter_cosine_similarity(counter1,counter3)
print(score) # output : 0.4999999999999999
对我来说,这不完全是我想要获得的分数,分数必须相反,因为list_a包含地址和ip,所以它是100%的测试匹配项,我知道在这种情况下,余弦相似度会与test和list_a进行比较,因此由于list_a上有一些不在测试中的元素是因为分数很低,因此我将准确地将测试与list_a进行比较,而不是以两种方式进行比较。
所需的输出
score = counter_cosine_similarity(counter1,counter2)
print(score) # output : score higher than list_b = 1.0 may be
score = counter_cosine_similarity(counter1,counter3)
print(score) # output : score less the list_a = 0.5 may be
答案 0 :(得分:1)
如果您想要更高的值,则更多的术语都相同,请使用以下代码:
score = len(set(test).intersection(set(list_x)))
这将告诉您两个列表有多少个常用术语。如果您想提高重复次数的得分,请尝试
commonTerms = set(test).intersection(set(list_x))
counter = Counter(list_x)
score = sum((counter.get(term) for term in commonTerms)) #edited
如果您需要将分数缩放到[0..1],我需要更多地了解您的数据集。