查找多个列表之间的 Jaccard 相似度

Find Jaccard similarity between multiple list

假设我有 3 个列表:

l1 = ["a", "b", "c"]
l2 = ["c", "e", "f"]
l3 = ["c", "b", "a"]

对于 Jaccard 相似度,我使用了以下函数:

def jaccard_similarity(list1, list2):
    intersection = len(list(set(list1).intersection(list2)))
    union = (len(set(list1)) + len(set(list2))) - intersection
    return float(intersection) / union

如何计算所有组合的 Jaccard 相似度,即:

(l1,l1), (l1,l2), (l1, l3)
(l2,l1), (l2,l2), (l2, l3) 
(l3,l1), (l3,l2), (l3, l3)

我想避免为每对列表手动执行此操作。此外,最终输出需要是一个 3x3 矩阵。

您可以在原始函数中从 list(set(...)) 中删除 list。也无需将 intersection 转换为 float,因为您正在使用“浮点除法运算符”:

def jaccard_similarity(list1, list2):
    intersection = len(set(list1).intersection(list2))
    union = (len(set(list1)) + len(set(list2))) - intersection
    return intersection / union

您可以使用 itertools 模块中的 product 生成列表对,并使用 starmap 和您的函数使用它们:

from itertools import product, starmap

l1 = ['a', 'b', 'c']
l2 = ['c', 'e', 'f']
l3 = ['c', 'b', 'a']

inputs = product([l1, l2, l3], [l1, l2, l3])

result = list(starmap(jaccard_similarity, inputs))
print(result)

输出:

[1.0, 0.2, 1.0, 0.2, 1.0, 0.2, 1.0, 0.2, 1.0]

接下来,要创建矩阵,您可以查看 itertools 文档中的 grouper 配方:https://docs.python.org/3/library/itertools.html#itertools-recipes

下面是 grouper 函数的简化示例:

def group_three(it):
    iterators = [iter(it)] * 3
    return zip(*iterators)

print(list(group_three(result)))

输出:

[(1.0, 0.2, 1.0), (0.2, 1.0, 0.2), (1.0, 0.2, 1.0)]