计算 Python 中多个词典的 Jaccard 相似度?

Computing Jaccard similarity on multiple dictionaries in Python?

我有一本看起来像这样的字典:

my_dict = {'Community A': ['User 1', 'User 2', 'User 3'],
           'Community B': ['User 1', 'User 2'],
           'Community C': ['User 3', 'User 4', 'User 5'],
           'Community D': ['User 1', 'User 3', 'User 4', 'User 5']}

我的目标是对不同社区及其唯一用户集之间的网络关系进行建模,以查看哪些社区最相似。目前,我正在探索使用 Jaccard 相似性。

我遇到过执行类似操作的答案,但只针对恰好 2 个词典;在我的例子中,我有几个,并且需要计算每个集合之间的相似性。

此外,一些列表的长度不同:在其他答案中,我看到 0 sub in 在那种情况下是缺失值,我认为这对我的情况有用。

您需要的是 Jaccard 相似性矩阵。如果这是你喜欢用元组(groupA,groupB)索引的内容,你可以将它们存储为字典。

下面是一个简单的实现

def jaccard(first, second):
    return len(set(first).intersection(second)) / len(set(first).union(second))

keys = list(my_dict.keys())
result_dict = {}

for k in keys:
    for l in keys:
        result_dict[(k,l)] = result_dict.get((l,k), jaccard(my_dict[k], my_dict[l]))

然后生成的字典看起来像

print(result_dict)
{('Community A', 'Community A'): 1.0, ('Community A', 'Community B'): 0.6666666666666666, ('Community A', 'Community C'): 0.2, ('Community A', 'Community D'): 0.4, ('Community B', 'Community A'): 0.6666666666666666, ('Community B', 'Community B'): 1.0, ('Community B', 'Community C'): 0.0, ('Community B', 'Community D'): 0.2, ('Community C', 'Community A'): 0.2, ('Community C', 'Community B'): 0.0, ('Community C', 'Community C'): 1.0, ('Community C', 'Community D'): 0.75, ('Community D', 'Community A'): 0.4, ('Community D', 'Community B'): 0.2, ('Community D', 'Community C'): 0.75, ('Community D', 'Community D'): 1.0}

显然对角线元素是恒等元。

说明 get 函数检查该对是否已计算,否则它会计算