python - 如何使用networkX找到社区分区结构中节点的度中心性?

标签 python data-science networkx graph-theory sna

我使用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'}

关于python - 如何使用networkX找到社区分区结构中节点的度中心性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59872861/

相关文章:

python - 如何删除 pytest-html 报告中的环境表

machine-learning - 机器学习中的倾斜类和不平衡类

python - 坐标到图表

java - 如何使用 Pyspark 连接 Teradata

python - Pandas groupby 获取另一列最小的列的值

python - 如何在 Optuna 中建议多变量比率(有界限)?

python - 基于列表/字典动态更改 networkx 中箭头的大小

python - 给定一组三角形顶点和面,分离对象并形成单独的网格

python - TensorFlow AttributeError : 'NoneType' object has no attribute 'TF_DeleteStatus'

machine-learning - 推理分析和预测分析有什么区别?