繁体   English   中英

如何修复 Python networkx 中边/节点标签不一致的问题?

[英]How to fix inconsistent labelling of edges/nodes in Python's networkx?

我想为图上的最大切割问题定义一个目标 function。 我使用以下表达式, 0.5*sum([w[i,j]*(1-spin[i]*spin[j]) for i,j in G.edges])其中G是 networkx 图, w是从该图(连接矩阵)生成的 numpy 矩阵(连接矩阵),并且spin是一个数组,其条目为 -1 或 1 以表示节点位于分区的哪一侧。

我认为一切都很好,但事实证明边缘的标签与节点的标签不一致,请参见下面的代码。 例如在图 G1 中,边权重w[1,5]为 0,即使边 (1,5) 在图中。 有关如何解决此问题的任何建议?

干杯

import networkx as nx

G1 = nx.random_regular_graph(3,6, seed = 1)
G2 = nx.random_regular_graph(3,6, seed = 1)

# labelling seems not to be conserved when transforming to matrix and back
G2 = nx.to_numpy_matrix(G2)
G2 = nx.from_numpy_matrix(G2)

print(nx.to_numpy_matrix(G1))
print(G1.edges)
print(nx.to_numpy_matrix(G2))
print(G2.edges)

Output

[[0. 1. 0. 1. 0. 1.]
 [1. 0. 1. 0. 1. 0.]
 [0. 1. 0. 1. 0. 1.]
 [1. 0. 1. 0. 1. 0.]
 [0. 1. 0. 1. 0. 1.]
 [1. 0. 1. 0. 1. 0.]] # matrix of G1

[(0, 1), (0, 4), (0, 3), (1, 2), (1, 5), (2, 3), (2, 4), (4, 5), (5, 3)] # edges of G1

[[0. 1. 0. 1. 0. 1.]
 [1. 0. 1. 0. 1. 0.]
 [0. 1. 0. 1. 0. 1.]
 [1. 0. 1. 0. 1. 0.]
 [0. 1. 0. 1. 0. 1.]
 [1. 0. 1. 0. 1. 0.]] # matrix of G2
[(0, 1), (0, 3), (0, 5), (1, 2), (1, 4), (2, 3), (2, 5), (3, 4), (4, 5)] # edges of G2

to_numpy_matrix文档中所述,如果未使用参数nodelist ,则该方法隐式使用G.nodes()的排序。

使用以下代码应该可以修复排序

nx.to_numpy_matrix(G, nodelist=sorted(G))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM