问题描述
有人可以确认我发现 networkx 2.5 的 floyd_warshall_numpy 方法的实现不正确吗?
要复现的代码是:
G = nx.balanced_tree(2,3)
print(G.nodes())
print(nx.shortest_path(G,2,13))
print(nx.floyd_warshall_numpy(G,[2,8,13]))
我的输出是
[0,1,3,4,5,6,7,9,10,11,12,13,14]
[2,13]
[[ 0. inf inf]
[inf 0. inf]
[inf inf 0.]]
我期望为所有 [2,13] 节点对计算非 Inf 距离,因为最短路径存在于所有节点对中。在我看来,这个实现试图以某种方式在子图中找到路径。
nx.floyd_warshall_numpy(G)
解决方法
我查看了源代码,发现算法只考虑涉及您提供的节点的路径。
因此,由于 2 和 8 之间没有仅包含节点 2、8 和 13 的路径,因此它返回 inf
。
我不确定应该如何最好地修复它 - 更新文档或方法是否更好。
,我怀疑您的代码打算用一组节点 print(nx.floyd_warshall_numpy(G,[2,6,13]))
而不是 [2,13]
来表示 [2,8,13]
。对吗?
G = nx.balanced_tree(2,3)
print(G.nodes())
print(nx.shortest_path(G,2,13))
print(nx.floyd_warshall_numpy(G,13]))
生产
[0,1,3,4,5,7,9,10,11,12,13,14]
[2,13]
[[0. 1. 2.]
[1. 0. 1.]
[2. 1. 0.]]
,
我认为问题在于文档中对 nodelist 的解释。
基于文档:
nodelist (list,optional) – 行和列按 nodelist 中的节点排序。如果 nodelist 为 None 则排序由 G.nodes() 生成。
但它没有提到节点列表实际上修改了图形。它使用节点列表中的节点制作另一个图。
假设您的图有 4 个节点 [1,4],但您将节点列表定义为 [2,4]。当您阅读文档时,您认为该函数会计算原始图中节点 2、3 和 4 之间的距离矩阵。但是,它似乎从图中删除了节点 1(技术上更改了原始图),然后计算了 2、3 和 4 之间的距离矩阵。如果节点 1 连接节点 2 和 3,则可能会出现问题。
Dist_Mat=nx.algorithms.shortest_paths.dense.floyd_warshall_numpy(G,[1,4])
print(Dist_Mat)
[[0. 1. 1. 1.]
[1. 0. 2. 2.]
[1. 2. 0. 2.]
[1. 2. 2. 0.]]
Dist_Mat=nx.algorithms.shortest_paths.dense.floyd_warshall_numpy(G,4])
print(Dist_Mat)
[[ 0. inf inf]
[inf 0. inf]
[inf inf 0.]]
请找到下面的代码
import networkx as nx
import matplotlib.pyplot as plt
import nxviz as nv
G=nx.Graph()
G.add_node(1)
G.nodes[1]['N']=10
G.add_nodes_from([(2,{'N':20}),4])
G.add_edge(1,2)
G.edges[1,2]['E']=120
G.add_edges_from([(1,{'E':130}),(1,4)])
G.nodes()
pos = {0: (0,0),1: (1,2: (0,1),3: (1,4: (0.5,2.0)}
print(G.nodes(data=True))
print(G.edges(data=True))
nx.draw(G,pos,with_labels=True,font_weight='bold')
FIG=nv.CircosPlot(G,node_size=1)
FIG.draw();plt.show()
Dist_Mat=nx.algorithms.shortest_paths.dense.floyd_warshall_numpy(G,4])
print(Dist_Mat)
Dist_Mat=nx.algorithms.shortest_paths.dense.floyd_warshall_numpy(G,4])
print(Dist_Mat)