使用Networkx的to_edgelist与from_edgelist后图不一致,是否操作有误?
为什么用nx.to_edgelist和nx.from_edgelist重建的图与原图邻接矩阵不一致?
代码
import networkx as nx import numpy as np # Create a graph random_graph = nx.erdos_renyi_graph(10, 0.5, seed=2) G = random_graph # Get the edge list representation edge_list = nx.to_edgelist(G) # Create a new graph from the edge list new_G = nx.from_edgelist(edge_list) # Check if the graphs are the same print("Original Graph Adjacency Matrix:") print(np.array(nx.adjacency_matrix(G).todense())) print("New Graph Adjacency Matrix:") print(np.array(nx.adjacency_matrix(new_G).todense())) # Print adjacency matrices of the original and reconstructed graphs original_adj_matrix = np.array(nx.adjacency_matrix(G).todense()) new_adj_matrix = np.array(nx.adjacency_matrix(new_G).todense()) # Compare adjacency matrices with a tolerance for floating-point differences if np.allclose(original_adj_matrix, new_adj_matrix, atol=1e-8): print("The original and reconstructed graphs are the same.") else: print("The original and reconstructed graphs are different.")
运行输出
Original Graph Adjacency Matrix: [[0 0 0 1 1 0 0 0 1 0] [0 0 0 0 1 1 1 0 0 0] [0 0 0 0 1 1 1 1 1 1] [1 0 0 0 1 0 0 0 1 1] [1 1 1 1 0 1 1 0 0 0] [0 1 1 0 1 0 1 0 0 0] [0 1 1 0 1 1 0 0 0 0] [0 0 1 0 0 0 0 0 1 0] [1 0 1 1 0 0 0 1 0 0] [0 0 1 1 0 0 0 0 0 0]] New Graph Adjacency Matrix: [[0 1 1 1 0 0 0 0 0 0] [1 0 1 1 0 0 0 0 0 1] [1 1 0 0 1 1 1 1 0 0] [1 1 0 0 0 0 0 1 1 0] [0 0 1 0 0 1 1 0 0 0] [0 0 1 0 1 0 1 1 0 0] [0 0 1 0 1 1 0 1 0 0] [0 0 1 1 0 1 1 0 1 1] [0 0 0 1 0 0 0 1 0 0] [0 1 0 0 0 0 0 1 0 0]] The original and reconstructed graphs are different.
问题
我是否操作有误?原本预期to_edgelist()和from_edgelist()方法应生成相同的图,但两者差异明显。多次运行后,原始图与新图的邻接矩阵各自保持一致,但彼此不匹配。
解答
你没有操作错误,差异的核心原因是邻接矩阵的节点排列顺序不同:
nx.adjacency_matrix()生成矩阵时,行和列的顺序由图的nodes()方法返回的节点顺序决定- 原图
G是通过erdos_renyi_graph生成的,节点默认按整数自然顺序(0,1,2,...,9)排列 - 而
nx.from_edgelist()创建的new_G,节点顺序是节点在边列表中首次出现的顺序,并非自然排序
两个图的结构完全一致,只是邻接矩阵的行/列对应节点的顺序不同,导致视觉上的差异。
验证方法
- 直接对比边集合:
print(set(G.edges()) == set(new_G.edges()))
输出为True,证明边完全一致。
- 强制按相同节点顺序生成邻接矩阵:
# 按0-9的排序顺序生成邻接矩阵 original_adj = np.array(nx.adjacency_matrix(G, nodelist=sorted(G.nodes())).todense()) new_adj = np.array(nx.adjacency_matrix(new_G, nodelist=sorted(new_G.nodes())).todense()) print(np.allclose(original_adj, new_adj))
输出为True,说明当节点顺序统一后,邻接矩阵完全相同。
总结:to_edgelist和from_edgelist确实正确重建了图,邻接矩阵的差异只是节点排列顺序导致的表象,图的实际结构没有变化。
内容的提问来源于stack exchange,提问作者Sukhwani Mitanshu Hundraj
相关产品推荐
相关产品推荐

