首页 > 解决方案 > 如何使用networkX找到社区分区结构中节点的度中心性?

问题描述

我曾经partition = community.best_partition(test_graph)从 networkX 图中获取分区。我有一本这样的字典:

{node0: 0,
 node1: 0,
 node2: 0,
 node3: 1,
 node4: 1,
 node5: 1,
 node5: 2,
 node6: 2,
...
}

其中键是节点,值是社区编号。我想在每个社区号中找到大多数度中心性节点。例如,在本例中:社区 1:我有 3 个节点,其中哪个节点的度数最高?

标签: pythondata-sciencenetworkxgraph-theorysna

解决方案


如果我正确理解了这个问题,下面的代码应该给出你所追求的:

代码:

import community
import networkx as nx

# Generate test graph
G = nx.erdos_renyi_graph(30, 0.05)

# Relabel nodes
G = nx.relabel_nodes(G, {i: f"node_{i}" for i in G.nodes})

# Compute partition
partition = community.best_partition(G)

# Get a set of the communities
communities = set(partition.values())

# Create a dictionary mapping community number to nodes within that community
communities_dict = {c: [k for k, v in partition.items() if v == c] for c in communities}

# Filter that dictionary to map community to the node of highest degree within the community
highest_degree = {k: max(v, key=lambda x: G.degree(x)) for k, v in communities_dict.items()}

输出:

>>> partition
{'node_0': 0,
 'node_1': 1,
 'node_2': 2,
 'node_3': 3,
 ...
 'node_25': 3,
 'node_26': 11,
 'node_27': 12,
 'node_28': 10,
 'node_29': 10}
>>> highest_degree
{0: 'node_0',
 1: 'node_1',
 2: 'node_2',
 3: 'node_3',
 4: 'node_19',
 5: 'node_9',
 6: 'node_10',
 7: 'node_11',
 8: 'node_13',
 9: 'node_21',
 10: 'node_24',
 11: 'node_26',
 12: 'node_27'}

推荐阅读