假设我有两个选项来生成网络的邻接矩阵:nx.adjacency_matrix()和我自己的代码.我想测试我的代码的正确性,并提出了一些奇怪的不等式.
示例:3×3网格网络.
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)
与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(整个第1行和整个第1列)连接到节点5和8.但是如果你看上面的图像这是错误的,因为它连接到节点1和3.
现在我的代码(在与上面相同的脚本中运行):
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.为什么存在这种差异?这种情况有什么问题?
最佳答案 Networkx不知道您希望节点的顺序.
以下是如何调用它:adjacency_matrix(G,nodelist = None,weight =’weight’).
如果需要特定订单,请将nodelist设置为该订单中的列表.
因此,例如adjacency_matrix(G,nodelist = range(9))应该得到你想要的.
为什么是这样?好吧,因为图形可以包含任何东西作为其节点(任何可以清除).你的一个节点可能是“鹦鹉”或(1,2).因此它将节点存储为dict中的键,而不是假设它是从0开始的非负整数.Dict键have an arbitrary order.