【问题标题】:NetworkX average shortest path length and diameter is taking foreverNetworkX 平均最短路径长度和直径需要永远
【发布时间】:2021-05-12 00:57:26
【问题描述】:

我有一个由未加权边构建的图 (A),我想计算我的主图 (A) 中最大连通图 (giantC) 的平均最短路径长度。但是,到目前为止,脚本已经运行了 3 个多小时(在 Colab 和本地尝试过),diameteraverage_shortest_path_length 都没有输出结果。

我正在使用networkx==2.5python==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


【解决方案1】:

对于未来的读者, 如果您想从 NetworkX Graph 中获取最大的连通子图

import networkx as nx
import logging


def fetch_hugest_subgraph(graph_):
    Gcc = max(nx.connected_components(graph_), key=len)
    giantC = graph_.subgraph(Gcc)
    logging.info('Fetched Giant Subgraph')
    return giantC

如果您想计算图表的平均最短路径长度,我们可以通过采样来实现

from statistics import mean
import networkx as nx


def write_nodes_number_and_shortest_paths(graph_, n_samples=10_000,
                                          output_path='graph_info_output.txt'):
    with open(output_path, encoding='utf-8', mode='w+') as f:
        for component in nx.connected_components(graph_):
            component_ = graph_.subgraph(component)
            nodes = component_.nodes()
            lengths = []
            for _ in range(n_samples):
                n1, n2 = random.choices(list(nodes), k=2)
                length = nx.shortest_path_length(component_, source=n1, target=n2)
                lengths.append(length)
            f.write(f'Nodes num: {len(nodes)}, shortest path mean: {mean(lengths)} \n')

根据 Joris Kinable(在 cmets 中)告诉我的计算 avg_shortest_path_length 具有 O(V^3); V = number of nodes 的复杂性。这同样适用于计算你的 grah 的直径

【讨论】:

    【解决方案2】:

    为未来的读者。在NetworkX >= 2.6 中,diameter approximated metric 可用于有向图和无向图。

    例子:

    >>> import timeit
    >>> timeit.timeit("print(nx.diameter(g))",setup="import networkx as nx; g = nx.fast_gnp_random_graph(5000, 0.03, 100)", number=1)
    3
    224.9891120430002
    >>> timeit.timeit("print(nx.approximation.diameter(g))",setup="import networkx as nx; g = nx.fast_gnp_random_graph(5000, 0.03, 100)", number=1)
    3
    0.09284040399961668
    

    请注意,近似度量将计算相对于精确值的下限

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多