杰卡德相关系数python代码实现
以下是一个简单的Python代码实现杰卡德相关系数:
def jaccard_similarity(set1, set2):
"""
计算杰卡德相关系数
:param set1: 集合1
:param set2: 集合2
:return: 杰卡德相关系数
"""
intersection = len(set1 & set2) # 交集元素个数
union = len(set1 | set2) # 并集元素个数
return intersection / union # 计算杰卡德相关系数
使用示例:
set1 = set([1, 2, 3, 4, 5])
set2 = set([4, 5, 6, 7, 8])
js = jaccard_similarity(set1, set2)
print(js) # 输出结果为 0.2857142857142857
在上面的示例中,集合1为{1, 2, 3, 4, 5},集合2为{4, 5, 6, 7, 8},它们的交集为{4, 5},并集为{1, 2, 3, 4, 5, 6, 7, 8},因此它们的杰卡德相关系数为2/7=0.2857142857142857
原文地址: https://www.cveoy.top/t/topic/e0jz 著作权归作者所有。请勿转载和采集!