【问题标题】:Computing Jaccard similarity on multiple dictionaries in Python?在 Python 中计算多个字典的 Jaccard 相似度?
【发布时间】:2019-11-04 14:58:08
【问题描述】:

我有一本像这样的字典:

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 在这种情况下是一个缺失值,我认为这对我的情况有效。

【问题讨论】:

标签: python dictionary data-science similarity


【解决方案1】:

您需要的是 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]))

那么得到的dict看起来像

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 函数检查该对是否已被计算,否则它会进行计算

【讨论】:

    猜你喜欢
    • 2017-03-27
    • 2022-01-04
    • 1970-01-01
    • 2018-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-26
    相关资源
    最近更新 更多