繁体   English   中英

Python networkx:floyd_warshall_numpy 工作正常吗?

[英]Python networkx: Does the floyd_warshall_numpy work properly?

有人可以确认我发现 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]))

我的 output 是

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
[2, 6, 13]
[[ 0. inf inf]
 [inf  0. inf]
 [inf inf  0.]] 

我希望为所有 [2, 8, 13] 节点对计算非 Inf 距离,因为它们之间存在最短路径。 在我看来,这个实现试图以某种方式在子图中找到路径。

nx.floyd_warshall_numpy(G)

适用于所有节点。 我发现这里的文档不直观。 https://networkx.org/documentation/stable/reference/algorithms/generated/networkx.algorithms.shortest_paths.dense.floyd_warshall_numpy.html.networkx.algorithms.shortest_paths.dense.floyd_warshall_numpy

我查看了源代码,发生的事情是该算法只考虑涉及您给它的节点的路径。

因此,由于 2 和 8 之间没有仅包含节点 2、8 和 13 的路径,因此它返回inf

我不确定应该如何最好地修复它 - 更新文档或方法是否更好。

我怀疑您的代码是说print(nx.floyd_warshall_numpy(G, [2, 6, 13]))带有一组节点[2, 6, 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, [2, 6, 13]))                                                                         

生产

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
[2, 6, 13]
[[0. 1. 2.]
 [1. 0. 1.]
 [2. 1. 0.]]

我相信问题是文档中对nodelist的解释。 根据文档:
nodelist (list, optional) – 行和列按 nodelist 中的节点排序。 如果 nodelist 为 None 则排序由 G.nodes() 生成。 但它没有提到节点列表实际上修改了图形。 它使用节点列表中的节点制作另一个图。

假设您的图表有 4 个节点 [1,2,3,4],但您将节点列表定义为 [2,3,4]。 当您阅读文档时,您认为 function 将计算原始图中节点 2、3 和 4 之间的距离矩阵。 但是,它似乎从图中删除了节点 1(从技术上改变了原始图),然后计算了 2、3 和 4 之间的距离矩阵。如果节点 1 连接节点 2 和 3,则可能会出现问题。

具有 4 个节点的示例图

Dist_Mat=nx.algorithms.shortest_paths.dense.floyd_warshall_numpy(G,[1,2,3,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,[2,3,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}),3,4])
G.add_edge(1,2)
G.edges[1,2]['E']=120
G.add_edges_from([(1,3,{'E':130}),(1,4)])
G.nodes()
pos = {0: (0, 0),
       1: (1, 0),
       2: (0, 1),
       3: (1, 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,[1, 2,3,4])
print(Dist_Mat)
Dist_Mat=nx.algorithms.shortest_paths.dense.floyd_warshall_numpy(G,[2,3,4])
print(Dist_Mat)

暂无
暂无

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

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