Python:两个网络之间的jaccard相似性?

标签 python networkx similarity

我有 2 large 网络 GG1 使用 networkx 生成包裹。我想计算所有节点之间的jaccard 相似度 索引。

一种可能的方式如下:

def returnJaccardNetworks(G, G1):
    tmp =   list(G.nodes())
    tmp1 =  list(G1.nodes())
    tmp2 =  np.unique([tmp, tmp1]) ### Find nodes in the networks
    jc = []
    for i in tmp2:
    ## if the node i is in G and in G1 compute 
    ## the similarity between the lists of the ajacent nodes
    ## otherwise append 0
        if (i in G) and (i in G1):  
            k1 = list(G[i]) ## adjacent nodes of i in the network G     
            k2 = list(G1[i]) ## adjacent nodes of i in the network G1 
            ### Start Jaccard Similarity
            intersect = list(set(k1) & set(k2))
            n = len(intersect)
            jc.append(n / float(len(k1) + len(k2) - n))
            ### End Jaccard Similariy
        else:
            jc.append(0)
    return jc

我想知道是否有更有效的方法。我注意到包中有一个名为 jaccard_coefficient 的函数,但我不确定它是如何工作的。

https://networkx.github.io/documentation/networkx-1.9/reference/generated/networkx.algorithms.link_prediction.jaccard_coefficient.html

最佳答案

您的实现非常高效(尽管不完美,IMO)。使用这个版本,我可以在我的机器上减少 15% 的执行时间:

def get_jaccard_coefficients(G, H):
    for v in G:
        if v in H:
            n = set(G[v]) # neighbors of v in G
            m = set(H[v]) # neighbors of v in H
            length_intersection = len(n & m)
            length_union = len(n) + len(m) - length_intersection
            yield v, float(length_intersection) / length_union
        else:
            yield v, 0. # should really yield v, None as measure is not defined for these nodes

这个其他版本更加紧凑​​且更易于维护,但代价是执行时间增加 30%:

def get_jaccard_coefficients(G, H):
    for v in set(G.nodes) & set(H.nodes): # i.e. the intersection
        n = set(G[v]) # neighbors of v in G
        m = set(H[v]) # neighbors of v in H
        yield v, len(n & m) / float(len(n | m))

关于Python:两个网络之间的jaccard相似性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50704439/

相关文章:

python - 使用 Python 解析 xml 文件中的特定元素

python - 在大型 NetworkX 图中删除 tie=1 的节点

python-3.x - Networkx:使用端口连接节点

python - 在 Networkx 1.10 中,configuration_model() 获得了关键字参数 'create_using' 的多个值

similarity - RGBA 颜色空间中的颜色相似度/距离

python Django : join view on the admin interface

python - pandas 0.18.0 中带时间片的滚动计数

python - 无法从延迟加载网站获取某些标签

algorithm - 比较Canny算法的轮廓结果和相似度

edit - 如何将 TF-IDF 与编辑距离或 Jaro-winkler 距离结合起来