我想在随机图中显示节点的平均距离增加log N,其中N是节点数。这里的p是在一对节点之间具有边的概率。我试过的是:
import matplotlib.pyplot as plt
import networkx as nx
%matplotlib inline
def run_experiment(ns, p=0.45, iters=30):
"""
p: probability of having an edge between a pair of nodes
ns: sequence of `number of nodes(n)` to try
iters: number of times to run for each `n`
"""
G = {}
shortestPath={}
res = []
for n in ns:
print(n)
for i in range(iters):
G[i] = nx.gnp_random_graph(n, p)
shortestPath[i] = nx.average_shortest_path_length(G[i], weight=None, method=None)
means = array([shortestPath[k] for k in shortestPath]).mean()
print(means)
res.append(means)
return np.array(res)
我尝试了一些n值:
ns = [1,10, 100, 1000]
res = run_experiment(ns)
然后我绘制它以显示对数曲线,但是我知道了:
dictionary = dict(zip(ns, res))
plt.plot(list(dictionary.keys()),list(dictionary.values()))
plt.yscale('log')
plt.xscale('log')
问题是什么?
看来问题出在随机图的生成上(请参阅创建至少连接一个边的随机图)。通过建议的功能(请参见下面的代码)添加随机生成的图,结果是(该图实际上还有3000的附加ns-entry):
这似乎证实了您的结果。这里的代码:
from itertools import combinations, groupby
import random
from numpy import array
import matplotlib.pyplot as plt
import networkx as nx
%matplotlib inline
# from https://stackoverflow.com/questions/61958360/how-to-create-random-graph-where-each-node-has-at-least-1-edge-using-networkx
def gnp_random_connected_graph(n, p):
"""
Generates a random undirected graph, similarly to an Erdős-Rényi
graph, but enforcing that the resulting graph is conneted
"""
edges = combinations(range(n), 2)
G = nx.Graph()
G.add_nodes_from(range(n))
if p <= 0:
return G
if p >= 1:
return nx.complete_graph(n, create_using=G)
for _, node_edges in groupby(edges, key=lambda x: x[0]):
node_edges = list(node_edges)
random_edge = random.choice(node_edges)
G.add_edge(*random_edge)
for e in node_edges:
if random.random() < p:
G.add_edge(*e)
return G
def run_experiment(ns, p=0.45, iters=30):
"""
p: probability of having an edge between a pair of nodes
ns: sequence of `number of nodes(n)` to try
iters: number of times to run for each `n`
"""
G = {}
shortestPath={}
res = []
for n in ns:
print(n)
for i in range(iters):
#G[i] = nx.gnp_random_graph(n, p)
G[i] = gnp_random_connected_graph(n, p)
shortestPath[i] = nx.average_shortest_path_length(G[i], weight=None, method=None)
means = array([shortestPath[k] for k in shortestPath]).mean()
print(means)
res.append(means)
return np.array(res)
ns = [1,10, 100, 1000]
res = run_experiment(ns)
dictionary = dict(zip(ns, res))
plt.plot(list(dictionary.keys()),list(dictionary.values()))
plt.yscale('log')
plt.xscale('log')
请注意,我刚刚在您的代码中更改了一行,并引用了生成函数。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句