python - 如何使用networkX在有向加权图中检测社区?

标签 python data-science networkx graph-theory data-analysis

我有一个连接的组件-具有边缘加权的有向图,我尝试使用


  community.best_partition(G)


要获得一个分区,但是,我得到类型错误:错误的图形类型,仅使用非有向图。这就是为什么我将有向图转换为无向图然后得到分区的原因。是否有某种方法可以解决问题,而无需将定向转换为无向且也使用权重?

另外,我还有另一个问题,我如何才能获得每个分区社区中排名前5位的中心度节点。
例如:


  undirected_strong_partition =
  community.best_partition(undirectedstrong_community,weight ='weight')
  undirected_strong_partition


{'node1': 0,
 'node2': 0,
 'node3': 0,
 'node4': 0,
 'node5': 1,
 'node6': 2,
 'node7': 2,
 'node8': 2,
 'node9': 2,
...}


如果可能的话,我想获得每个社区中排名前5位的节点。例如:

{community0: [nodetop1,nodetop2...nodetop5]}


先感谢您。

最佳答案

这可以通过以下方式解决:

码:

import community
import networkx as nx

# Generate test graph
G = nx.fast_gnp_random_graph(100, 0.1)

# 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 to first sort the nodes in the community by degree, then take the top 5.
highest_degree = {k: sorted(v, key=lambda x: G.degree(x))[-5:] for k, v in communities_dict.items()}


输出:

>>> highest_degree
{0: ['node_91', 'node_24', 'node_19', 'node_8', 'node_83'],
 1: ['node_54', 'node_69', 'node_88', 'node_48', 'node_84'],
 2: ['node_79', 'node_34', 'node_52', 'node_46', 'node_36'],
 3: ['node_98', 'node_96', 'node_86', 'node_76', 'node_30'],
 4: ['node_29', 'node_40', 'node_10', 'node_90', 'node_32'],
 5: ['node_94', 'node_97', 'node_59', 'node_25', 'node_37'],
 6: ['node_31', 'node_56', 'node_57', 'node_62', 'node_63']}

关于python - 如何使用networkX在有向加权图中检测社区?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59894785/

相关文章:

python - Networkx 读取军械调查 - ITN 综合传输网络?/读取 GML 文件

python - 如何在 PySimpleGUIQt 中实现复选框功能?

machine-learning - 理解具有多个自变量的多项式回归方程

machine-learning - 预测一段时间内的客户流失

machine-learning - 使用无监督点击日志评估搜索引擎

python - networkX node_connected_component 未针对定向类型实现

python - 如何修改此正则表达式以不匹配不间断空格?

python - 在 Selenium Web 驱动程序上发送键 shift+tab

python - vlc.py 是如何播放视频流的?

python - 基于数据框的两列创建网络并将其组件 ID 添加为新的聚合列