【发布时间】:2021-05-12 00:57:26
【问题描述】:
我有一个由未加权边构建的图 (A),我想计算我的主图 (A) 中最大连通图 (giantC) 的平均最短路径长度。但是,到目前为止,脚本已经运行了 3 个多小时(在 Colab 和本地尝试过),diameter 和 average_shortest_path_length 都没有输出结果。
我正在使用networkx==2.5,python==3.6.9
这是我的脚本
import logging
import networkx as nx
from networkx.algorithms.distance_measures import diameter
from networkx.algorithms.shortest_paths.generic import average_shortest_path_length
# graph is built from a json file as follows
with open('graph.json') as f:
graph_dict = json.load(f)
_indices = graph_dict['indices']
s_lst, rs_lst= _indices[0], _indices[1]
graph_ = nx.Graph()
for i in range(len(s_lst)):
graph_.add_edge(s_lst[i], rs_lst[i])
# fetch the hugest graph of all graphs
connected_subgraphs = [graph_.subgraph(cc) for cc in
nx.connected_components(graph_)]
logging.info('connected subgraphs fetched.')
Gcc = max(nx.connected_components(graph_), key=len)
giantC = graph_.subgraph(Gcc)
logging.info('Fetched Giant Subgraph')
n_nodes = giantC.number_of_nodes()
print(f'Number of nodes: {n_nodes}') # output is 106088
avg_shortest_path = average_shortest_path_length(giantC)
print(f'Avg Shortest path len: {avg_shortest_path}')
dia = diameter(giantC)
print(f'Diameter: {dia}')
有什么方法可以加快速度吗?还是计算 GiantC 图的直径和最短路径长度的替代方法?
【问题讨论】:
-
一些附加信息会有所帮助,例如最大组件(giantC)的顶点和边数是多少?计算大型图的全对最短路径并不便宜。
-
docs 中给出了用于计算平均最短路径长度的公式。该公式要求输入所有顶点对的最短路径长度。在您的情况下,组件有 106088 个顶点。计算所有对最短路径的计算复杂度为 O(n^3) (给或取,取决于您使用的算法)。 106088^3 是一个巨大的数字,你永远无法计算。
-
计算图直径有时间计算复杂度,所以不会更快。因此,总而言之,您不太可能准确计算出所需的数字。您可能希望查看更易于计算的替代指标,或尝试估计确切指标的近似指标。
-
直径很棘手,但平均最短路径长度通常可以通过采样很好地估计,即随机选择 2 个节点并计算它们之间的最短路径。重复 1000 次。
-
Here 是一篇关于估计直径的论文,但它是一项更复杂的任务。
标签: python-3.x graph networkx