简体   繁体   English

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

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

I want to define an objective function for the max-cut problem on graphs.我想为图上的最大切割问题定义一个目标 function。 I use the following expression, 0.5*sum([w[i,j]*(1-spin[i]*spin[j]) for i,j in G.edges]) where G is a networkx graph, w is the numpy matrix generated from that graph (connectivity matrix), and spin is an array with entries -1 or 1 to denote which side of the partition the node is in.我使用以下表达式, 0.5*sum([w[i,j]*(1-spin[i]*spin[j]) for i,j in G.edges])其中G是 networkx 图, w是从该图(连接矩阵)生成的 numpy 矩阵(连接矩阵),并且spin是一个数组,其条目为 -1 或 1 以表示节点位于分区的哪一侧。

All good I thought, but it turns out that the labelling of the edges is not consistent with the labelling of the nodes, see code below.我认为一切都很好,但事实证明边缘的标签与节点的标签不一致,请参见下面的代码。 For example in the graph G1, edge weight w[1,5] is 0 even though the edge (1,5) is in the graph.例如在图 G1 中,边权重w[1,5]为 0,即使边 (1,5) 在图中。 Any recommendations on how to fix this?有关如何解决此问题的任何建议?

Cheers干杯

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 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

As described in to_numpy_matrix documentation, the method implicitly uses the ordering of G.nodes() , if the parameter nodelist is not used.to_numpy_matrix文档中所述,如果未使用参数nodelist ,则该方法隐式使用G.nodes()的排序。

Using the following code should fix the ordering使用以下代码应该可以修复排序

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

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

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