While using the NetworkX
package I was tasked with creating multiple random graphs with a given n number of nodes and p probability, this is my code:
def random_networks_generator(n,p,num_networks=1, directed=False,seed=30030390): Graph_list=[] for num in range (0,num_networks): G=nx.gnp_random_graph(n,p,seed,directed) Graph_list.append(G) return Graph_list
But, every iteration creates the same exact graph (even the edges are completely the same)
Does anyone have a clue what might be wrong?
Update:
After trying to use the function without the “seed” parameter the graphs are random, but is there a way to sort the problem while still using the “seed” parameter?
Advertisement
Answer
Currently you make all the calls in the loop with the same fixed seed. According to the documentation of gnp_random_graph
or more general Randomness by fixing the seed you make sure that you always receive the exactly same random graph.
For example:
G_1=nx.gnp_random_graph(100, .5, 42) G_2=nx.gnp_random_graph(100, .5, 42) G_3=nx.gnp_random_graph(100, .5, 43)
The graphs G_1
and G_2
will have exactly the same edges, whereas G_3
got a different seed and with high likelihood is different (as it is in this example).
You can get the desired behaviour of retrieving the same list of graphs (determined by the initial seed) via the following code:
def random_networks_generator(n, p, num_networks=1, directed=False, seed=30030390): Graph_list=[] for num in range (0,num_networks): G=nx.gnp_random_graph(n, p, seed + num, directed) Graph_list.append(G) return Graph_list
More background on seed: