NetworkX:邻接矩阵与图不对应

6
我有两种方法可以生成网络的邻接矩阵:nx.adjacency_matrix() 和我自己写的代码。我想测试一下我的代码是否正确,但结果出现了一些奇怪的不等式。
例如:一个3x3的晶格网络。
import networkx as nx
N=3
G=nx.grid_2d_graph(N,N)
pos = dict( (n, n) for n in G.nodes() )
labels = dict( ((i,j), i + (N-1-j) * N ) for i, j in G.nodes() )
nx.relabel_nodes(G,labels,False)
inds=labels.keys()
vals=labels.values()
inds.sort()
vals.sort()
pos2=dict(zip(vals,inds))
plt.figure()
nx.draw_networkx(G, pos=pos2, with_labels=True, node_size = 200)

这是可视化效果: enter image description here 使用 nx.adjacency_matrix() 得到的邻接矩阵:
B=nx.adjacency_matrix(G)
B1=B.todense()

[[0 0 0 0 0 1 0 0 1]
 [0 0 0 1 0 1 0 0 0]
 [0 0 0 1 0 1 0 1 1]
 [0 1 1 0 0 0 1 0 0]
 [0 0 0 0 0 0 0 1 1]
 [1 1 1 0 0 0 0 0 0]
 [0 0 0 1 0 0 0 1 0]
 [0 0 1 0 1 0 1 0 0]
 [1 0 1 0 1 0 0 0 0]]

根据它所说,节点 0(整个第一行和整个第一列)连接到节点 58。但是,如果您查看上面的图像,这是错误的,因为它连接到节点 13
现在是我的代码(要在与上述相同的脚本中运行):
import numpy
import math

P=3

def nodes_connected(i, j):
     try: 
        if i in G.neighbors(j):
            return 1
     except nx.NetworkXError:
        return False          

A=numpy.zeros((P*P,P*P))

for i in range(0,P*P,1):
    for j in range(0,P*P,1):

        if i not in G.nodes():
            A[i][:]=0
            A[:][i]=0
        elif i in G.nodes():
            A[i][j]=nodes_connected(i,j)
                A[j][i]=A[i][j]

for i in range(0,P*P,1):
    for j in range(0,P*P,1):
            if math.isnan(A[i][j]):
                A[i][j]=0 

print(A)

这将产生以下结果:
[[ 0.  1.  0.  1.  0.  0.  0.  0.  0.]
 [ 1.  0.  1.  0.  1.  0.  0.  0.  0.]
 [ 0.  1.  0.  0.  0.  1.  0.  0.  0.]
 [ 1.  0.  0.  0.  1.  0.  1.  0.  0.]
 [ 0.  1.  0.  1.  0.  1.  0.  1.  0.]
 [ 0.  0.  1.  0.  1.  0.  0.  0.  1.]
 [ 0.  0.  0.  1.  0.  0.  0.  1.  0.]
 [ 0.  0.  0.  0.  1.  0.  1.  0.  1.]
 [ 0.  0.  0.  0.  0.  1.  0.  1.  0.]]

以下内容描述了节点0与节点1和节点3的连接情况。为什么存在这样的差异?在这种情况下出了什么问题?


1
不是100%确定,但与下面的答案相关,在上面使用dict的地方,您应该更改为使用collections.OrderedDict... - Corley Brigman
2个回答

10

Networkx不知道你想让节点以什么顺序排序。

以下是调用方法:adjacency_matrix(G, nodelist=None, weight='weight')

如果你想要特定的顺序,把nodelist设置成按照那个顺序排列的列表。例如,adjacency_matrix(G, nodelist=range(9))就可以得到你想要的结果。

这是为什么呢?因为一个图的节点可以是几乎任何东西(任何可哈希对象)。其中一个节点可以是"parrot"(1,2)。因此,它将节点作为字典中的键来存储,而不是假设它是从0开始的非负整数。字典键没有固定的顺序


2

如果您的节点具有某种逻辑排序,例如使用G=nx.grid_2d_graph(3,3)生成图形(返回从(0,0)到(2,2)的元组),则更通用的解决方案是使用以下方法:

adjacency_matrix(G,nodelist=sorted(G.nodes()))

这将对 G 的节点列表进行排序,并将其作为 nodelist 传递。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接