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

2024-06-08 11:15:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在处理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)

Tags: infromimportnodeforlabelsifglobal
1条回答
网友
1楼 · 发布于 2024-06-08 11:15:20

我想我知道你为什么记错了。保持每个节点所有最短路径的所有长度可以产生一个非常大的列表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))

结果是一样的(我查过了)。在

相关问题 更多 >