将 igraph 转换为 networkx 以进行聚类

Converting igraph to networkx for clustering

我有一个使用 igraph 库的 python 代码

import igraph
edge =  [(0, 6), (0, 8), (0, 115), (0, 124), (0, 289), (0, 359), (0, 363), (6, 60), (6, 115), (6, 128), (6, 129), (6, 130), (6, 131), (6, 359), (6, 529), (8, 9), (8, 17), (8, 115)]
G = igraph.Graph(edges=edge, directed=False)
G.vs['label'] = nodes
G.es["weight"] = weights
dendrogram = G.community_edge_betweenness()
clusters = dendrogram.as_clustering()
membership = clusters.membership
out = pd.Series(membership, index=nodes)

我需要将其转换为 networkx 库。

import networkx as nx
G = nx.Graph(edges)
dendrogram = nx.edge_betweenness_centrality(G)
clusters = nx.clustering(dendrogram)
membership = clusters.membership
out = pd.Series(membership, index=nodes)

但是,dendrogram 不能在 networkx 库中聚类。有人可以帮助将 igraph 代码复制到 networkx 集群吗?

问题是 "clustering" 在网络科学中指的是两个不同的东西。它要么指聚类系数(自我图中三角形的分数;nx.clustering),要么指一组节点(a.k.a。数据聚类、网络社区、节点分区等)。

在这种情况下,您使用的是 igraph community_edge_betweenness() to hierarchically cluster your nodes, and then cut the dendrogram to create a node partition through dendrogram.as_clustering()

networkx 中的等价物是使用 girvan_newman:

from networkx.algorithms.community.centrality import girvan_newman

nx_dendrogram = girvan_newman(G)
move_down_dendrogram = itertools.takewhile(lambda c: len(c) <= 4, nx_dendrogram)
for c in move_down_dendrogram:
    clustering_list = c
print(clustering_list)

membership = [0] * G.number_of_nodes()
for ic, cset in enumerate(clustering_list):
    for n in cset:
        membership[n] = ic
out = pd.Series(membership, index=nodes)