You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

非连通图处理方案:基于aves-weaver-social数据集提取子图并分析属性

非连通图的子图提取与属性分析方案

核心实现代码

import networkx as nx

# 读取图数据
G = nx.read_edgelist('./aves-weaver-social.edges', create_using=nx.Graph, nodetype=int, data=(('weight', int),))

# 获取所有连通分量,按节点数从多到少排序
connected_components = sorted(nx.connected_components(G), key=len, reverse=True)

# 遍历处理每个连通子图
for idx, component_nodes in enumerate(connected_components, 1):
    subgraph = G.subgraph(component_nodes)
    print(f"=== 第{idx}个连通子图 ===")
    print(f"节点数: {subgraph.number_of_nodes()}")
    print(f"边数: {subgraph.number_of_edges()}")
    # 计算子图直径(仅连通图可计算,此处已确保子图连通)
    diameter = nx.diameter(subgraph)
    print(f"直径: {diameter}")
    print("------------------------")

关键细节说明

  • nx.connected_components(G):返回图中所有连通分量的节点集合,每个集合对应一个独立的连通子图。
  • 排序处理:通过sorted(..., key=len, reverse=True)将最大的连通子图优先展示,方便聚焦核心分析对象。
  • 子图生成:G.subgraph(component_nodes)生成的是原图的视图,若需要独立可修改的子图,可改用nx.Graph(G.subgraph(component_nodes))。

可选:子图可视化

如果需要查看单个子图的结构,可添加以下代码:

import matplotlib.pyplot as plt

# 可视化第一个(最大的)连通子图
first_subgraph = G.subgraph(connected_components[0])
nx.draw(first_subgraph, with_labels=True, node_size=300, font_size=8)
plt.show()

内容的提问来源于stack exchange,提问作者Ayush Paudel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 15:27:31