简体   繁体   English

加快networkx中的随机最小生成树?

[英]Speeding up random minimum spanning tree in networkx?

Here's a bit of code whose goal is to build a random spanning tree using greedy and random edge weights. 以下是一些代码,其目标是使用贪婪和随机边缘权重构建随机生成树。 It runs much slower than I would like it to. 它的运行速度比我想要的慢得多。 Any tips for ways to speed it up? 有什么技巧可以加快速度吗?

Both the randomly generating weights and the sampling of a minimum spanning tree are slow... the first is especially weird to me, because there are only 179400 edges and np.random.uniform(0,1,179400) executes very quickly. 随机生成的权重最小生成树的采样速度都很慢...第一个对我来说尤其奇怪,因为只有179400条边并且np.random.uniform(0,1,179400)执行得非常快。

(Here slow means on the order of seconds.) (这里的慢速意味着大约几秒钟。)

(I'm happy to use something other than networkx,but it's not preferable.) (我很高兴使用networkx以外的其他工具,但这不是可取的。)

import numpy as np
import networkx as nx

graph = nx.grid_graph([300, 300])

for edge in graph.edges():
    graph.edges[edge]["weight"] = np.random.uniform(0, 1)

tree = nx.minimum_spanning_tree(graph)

If bulk production of random numbers is quicker in your tests, then just do that. 如果在测试中更快地批量生成随机数,则只需这样做。

rand = np.random.uniform(0, 1, graph.edges.size())
i = 0
for edge in graph.edges():
    graph.edges[edge]["weight"] = rand[i]
    i += 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM