Jaccard, 又称为Jaccard相似系数(Jaccard similarity coefficient)用于比较有限样本集之间的相似性与差异性。Jaccard系数值越大,样本相似度越高
公式:
假设arr1 = [11, 2, 3, 8, 10, 0, 2, 0, 0, 2, 1, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0] ,长度为21
假设arr2 = [9, 4, 4, 6, 6, 1, 3, 1, 0, 0, 4, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0],长度为21
则arr1,arr2的公共部分arr_common = [3,0,0,0,1,0,0,0, 0, 0, 0, 0, 0, 0], 长度为14
arr1,arr2的相似度为:14 / (21+21-14) = 0.5
1 def get_Jaccard(arr1,arr2): 2 common = 0 3 # 计算公共相似值的个数 4 for item in arr1: 5 if item in arr2: 6 common += 1 7 if common==0: 8 return 0 9 print(common) 10 return float(common/(len(arr1) + len(arr2) - common)) 11 12 a1 = [11, 2, 3, 8, 10, 0, 2, 0, 0, 2, 1, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0] 13 a2 = [9, 4, 4, 6, 6, 1, 3, 1, 0, 0, 4, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0] 14 res = get_Jaccard(a1,a2) 15 print(res)
测试结果: