使用networkx计算平均最短路径长度

less than 1 minute read

代码

import networkx as nx
import matplotlib.pyplot as plt
# 生成一个有向网络
G=nx.DiGraph()
#网络构成
G.add_edges_from([(1, 2), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9), (2, 3), (2, 4), (6, 7)])
#绘制网络
pos=nx.spring_layout(G, iterations=5000) #设置网络的布局
plt.figure()
nx.draw(G, pos)


nx.average_shortest_path_length(G) # 网络平均最短距离0.181


nx.all_pairs_shortest_path_length(G)

Out[29]:
{1: {1: 0, 2: 1, 3: 2, 4: 2, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1},
2: {2: 0, 3: 1, 4: 1},
3: {3: 0},
4: {4: 0},
5: {5: 0},
6: {6: 0, 7: 1},
7: {7: 0},
8: {8: 0},
9: {9: 0}}


nx.shortest_path_length(G, source = 1, target =2)
# 1
nx.shortest_path_length(G, source = 1, target =3)
# 2
nx.shortest_path_length(G, source = 3, target =4)
#error: NetworkXNoPath: No path between 4 and 3.


UG=G.to_undirected()
nx.average_shortest_path_length(UG) #1.93


参考

1. http://networkx.lanl.gov/reference/generated/networkx.algorithms.shortest_paths.generic.average_shortest_path_length.html

Tags:

Updated: