NetworkX提供了4种常见网络的建模方法,分别是:规则图,ER随机图,WS小世界网络和BA无标度网络。
一. 规则图
规则图差不多是最没有复杂性的一类图,random_graphs.random_regular_graph(d, n)方法可以生成一个含有n个节点,每个节点有d个邻居节点的规则图。
下面一段示例代码,生成了包含20个节点、每个节点有3个邻居的规则图:
1 import networkx as nx
2 import matplotlib.pyplot as plt
3
4 # regular graphy
5 # generate a regular graph which has 20 nodes & each node has 3 neghbour nodes.
6 RG = nx.random_graphs.random_regular_graph(3, 20)
7 # the spectral layout
8 pos = nx.spectral_layout(RG)
9 # draw the regular graphy
10 nx.draw(RG, pos, with_labels = False, node_size = 30)
11 plt.show()
二、ER随机图
ER随机图是早期研究得比较多的一类“复杂”网络,模型的基本思想是以概率p连接N个节点中的每一对节点。用random_graphs.erdos_renyi_graph(n,p)方法生成一个含有n个节点、以概率p连接的ER随机图:
1 import networkx as nx
2 import matplotlib.pyplot as plt
3
4 # erdos renyi graph
5 # generate a graph which has n=20 nodes, probablity p = 0.2.
6 ER = nx.random_graphs.erdos_renyi_graph(20, 0.2)
7 # the shell layout
8 pos = nx.shell_layout(ER)
9 nx.draw(ER, pos, with_labels = False, node_size = 30)
10 plt.show()
三、WS小世界网络
用random_graphs.watts_strogatz_graph(n, k, p)方法生成一个含有n个节点、每个节点有k个邻居、以概率p随机化重连边的WS小世界网络。
下面是一个例子:
1 import networkx as nx
2 import matplotlib.pyplot as plt
3
4 # WS network
5
6 # generate a WS network which has 20 nodes,
7 # each node has 4 neighbour nodes,
8 # random reconnection probability was 0.3.
9 WS = nx.random_graphs.watts_strogatz_graph(20, 4, 0.3)
10 # circular layout
11 pos = nx.circular_layout(WS)
12 nx.draw(WS, pos, with_labels = False, node_size = 30)
13 plt.show()
四、BA无标度网络
用random_graphs.barabasi_albert_graph(n, m)方法生成一个含有n个节点、每次加入m条边的BA无标度网络。
下面是一个例子:
1 import networkx as nx
2 import matplotlib.pyplot as plt
3
4 # BA scale-free degree network
5 # generalize BA network which has 20 nodes, m = 1
6 BA = nx.random_graphs.barabasi_albert_graph(20, 1)
7 # spring layout
8 pos = nx.spring_layout(BA)
9 nx.draw(BA, pos, with_labels = False, node_size = 30)
10 plt.show()