NetworkX:邻接矩阵与图形不对应

FaC*_*fee 4 python matrix adjacency-list networkx adjacency-matrix

假设我有两个选项来生成网络的邻接矩阵: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)
Run Code Online (Sandbox Code Playgroud)

这是可视化: 在此输入图像描述

邻接矩阵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]]
Run Code Online (Sandbox Code Playgroud)

根据它,节点0(整个第1行和整个第1列)连接到节点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)
Run Code Online (Sandbox Code Playgroud)

这会产生:

[[ 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.]]
Run Code Online (Sandbox Code Playgroud)

这表示节点0连接到节点13.为什么存在这种差异?这种情况有什么问题?

Joe*_*oel 7

Networkx不知道您希望节点的顺序.

以下是如何称呼它:adjacency_matrix(G, nodelist=None, weight='weight').

如果需要特定订单,请将nodelist设置为该订单中的列表.所以例如adjacency_matrix(G, nodelist=range(9))应该得到你想要的.

为什么是这样?好吧,因为图形可以包含任何东西作为其节点(任何可以清除).你的一个节点可能是"parrot"(1,2).因此它将节点存储为dict中的键,而不是假设它是从0开始的非负整数.Dict键具有任意顺序.