python - 如何使用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 个节点,其中哪个节点的度数最高?
解决方案
如果我正确理解了这个问题,下面的代码应该给出你所追求的:
代码:
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'}
推荐阅读
- azure-devops - Azure Pipelines 如何为“仅限手动”触发的版本筛选每个阶段的工件
- bash - 如何在 BASH 中为特定输入编写错误消息?
- c++ - 为什么 volatile 不是 sig_atomic_t 的一部分
- api - Instagram 的 Webhook 在评论广告时是否提供信息?
- c++ - 在定义之前显式实例化模板函数
- javascript - 使用 vainilla JS 获取触发事件的父 DOM 元素的 ID
- javascript - 带有弹出窗口的交互式签到页面
- javascript - 地理位置不适用于移动设备,但适用于我的桌面
- cocoapods - 尝试安装 Pod 时出现错误“with_indifferent_access”
- java - 为什么 super() 构造函数不采用与父构造函数相同的参数?