Python: 全局效率内存错误 (networkx)

Python: Memory Error with global efficiency (networkx)

我正在处理一个 100x100 网格网络。我想确定它 global efficiency 以了解其中交换信息的效率。

我正在使用定制函数来计算效率,然后将其应用到我的网络中。

但是,我 运行 变成了 Memory Error ,它指向调用函数的行(最后一行)。 这是否取决于使用了多少 RAM Python?我该如何解决这个问题?

代码如下:

from __future__ import print_function, division
import numpy
from numpy import *
import networkx as nx
import matplotlib.pyplot as plt
import csv
from collections import *
import os
import glob
from collections import OrderedDict 

def global_efficiency(G, weight=None):
    N = len(G)
    if N < 2:
        return 0   
    inv_lengths = []
    for node in G:
        if weight is None:
            lengths = nx.single_source_shortest_path_length(G, node)
        else:
            lengths=nx.single_source_dijkstra_path_length(G,node,weight=weight)

        inv = [1/x for x in lengths.values() if x is not 0]
        inv_lengths.extend(inv)

    return sum(inv_lengths)/(N*(N-1))

N=100
G=nx.grid_2d_graph(N,N)
pos = dict( (n, n) for n in G.nodes() )
labels = dict( ((i, j), i + (N-1-j) * N ) for i, j in G.nodes() )
nx.relabel_nodes(G,labels,False)
inds=labels.keys()
vals=labels.values()
inds.sort()
vals.sort()
pos2=dict(zip(vals,inds))
nx.draw_networkx(G, pos=pos2, with_labels=False, node_size = 10)
eff=global_efficiency(G)

我想我知道你为什么会出现内存错误了。保留每个节点的所有最短路径的所有长度可以产生一个非常巨大的列表inv_lengths

我建议等效修改:

def global_efficiency(G, weight=None):
    N = len(G)
    if N < 2:
        return 0   
    inv_lengths = []
    for node in G:
        if weight is None:
            lengths = nx.single_source_shortest_path_length(G, node)
        else:
            lengths=nx.single_source_dijkstra_path_length(G,node,weight=weight)

        inv = [1/x for x in lengths.values() if x is not 0]

        # Changes here
        inv_sum = sum(inv)
        inv_lengths.append(inv_sum)  # add results, one per node

    return sum(inv_lengths)/(N*(N-1))

它给出了相同的结果(我检查过)。