【发布时间】:2021-08-01 03:43:12
【问题描述】:
TL;DR:生成静态网络列表比将这些静态网络合并为单个动态网络快十倍。为什么会这样?
在this answer 之后,我尝试使用 NetworkX 和 DyNetx 生成随机动态图。
在处理中型网络(大约 1000 个节点和 1000 个时间戳)时会出现问题 - 内存崩溃。同样在较小的规模(大约 100 个节点和 300 个时间戳)上,该过程非常缓慢。我相信我已经确定了障碍,但我不确定如何处理它。
以下是生成随机时间网络的简单代码示例:
import dynetx as dnx
import networkx as nx
import itertools
from random import random
def dynamic_random_graph(n, steps, up_rate, seed=42):
# Create list of static graphs
list_of_snapshots = list()
for t in range(0, steps):
G_t = nx.Graph()
edges = itertools.combinations(range(n), 2)
G_t.add_nodes_from(range(n))
for e in edges:
if random() < up_rate:
G_t.add_edge(*e)
list_of_snapshots.append(G_t)
# Merge the static graphs into dynamic one
dynamic_graph = dnx.DynGraph()
for t, graph in enumerate(list_of_snapshots):
dynamic_graph.add_interactions_from(graph.edges(data=False), t=t)
return dynamic_graph
如果我们运行以下命令:
%timeit dynamic_random_graph(300, 100, 0.5) # Memory was crahsed on larger networks.
>> 1 loop, best of 5: 15.1 s per loop
相比之下,如果我们在没有网络合并的情况下运行代码,我们将获得明显更好的结果:
%timeit dynamic_random_graph_without_merge(300, 100, 0.5) # Ignore the merge part in the function
>> 1 loop, best of 5: 15.1 s per loop
如果我们在没有合并部分的情况下运行该函数,我们可以在具有 1000 个节点的网络上工作而不会发生内存崩溃。
所以,我想看看DyNetx source code 并尝试找出add_interactions_from 方法有什么问题。
这个功能很短很简单,但我很好奇为什么它需要这么多时间和内存,以及如何改进它。你有什么想法?
这是source code:
def add_interactions_from(self, ebunch, t=None, e=None):
"""Add all the interaction in ebunch at time t.
Parameters
----------
ebunch : container of interaction
Each interaction given in the container will be added to the
graph. The interaction must be given as as 2-tuples (u,v) or
3-tuples (u,v,d) where d is a dictionary containing interaction
data.
t : appearance snapshot id, mandatory
e : vanishing snapshot id, optional
See Also
--------
add_edge : add a single interaction
Examples
--------
>>> import dynetx as dn
>>> G = dn.DynGraph()
>>> G.add_edges_from([(0,1),(1,2)], t=0)
"""
# set up attribute dict
if t is None:
raise nx.NetworkXError(
"The t argument must be a specified.")
# process ebunch
for ed in ebunch:
self.add_interaction(ed[0], ed[1], t, e)
我想最后的循环是所有问题的根源。
Link 到 add_interaction 实现。
【问题讨论】:
-
AFAIK,networkx 不是一个非常有效的软件包。我认为它是为非常小的图表设计的。您可能对 neo4j 或 snap 等替代软件包感兴趣。
标签: python performance networkx