我正在处理100x100
网格网络。我想确定其global efficiency,以了解信息在其中的交换效率。
我正在使用定制函数来计算效率,然后将其应用到我的网络中。
但是,我遇到Memory Error
,它指向调用函数的行(最后一行)。 这取决于Python使用多少RAM?我该如何解决这个问题?
代码如下:
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)
答案 0 :(得分:2)
我想我知道你为什么会有内存错误。保持每个节点的所有最短路径的所有长度可以产生非常大的列表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))
它给出了相同的结果(我检查过)。