Python复杂网络分析库networkx 看这一篇就够了 - Go语言中文社区

Python复杂网络分析库networkx 看这一篇就够了


1 基础知识

1.1 简介

networkx在2002年5月产生,是一个用Python语言开发的图论与复杂网络建模工具,内置了常用的图与复杂网络分析算法,可以方便的进行复杂网络数据分析、仿真建模等工作。

networkx支持创建简单无向图、有向图和多重图;内置许多标准的图论算法,节点可为任意数据;支持任意的边值维度,功能丰富,简单易用。

  • 可以生成多种随即网络,经典网络等

1.2 Graph

  • Graph是用点和线来刻画离散事物集合中的每对事物间以某种方式相联系的数学模型。
  • 根据Graph的定义,一个Graph包含一个节点集合和一个边集。
  • Graph:指无向图(undirected Graph),即忽略了两节点间边的方向。
  • DiGraph:指有向图(directed Graph),即考虑了边的有向性。
  • MultiGraph:指多重无向图,即两个结点之间的边数多于一条,又允许顶点通过同一条边和自己关联。
  • MultiDiGraph:多重图的有向版本。

添加节点

import networkx as nx
import matplotlib.pyplot as plt
G = nx.Graph()
G.add_node('a')
G.add_node_from(['b','c','d','e'])
nx.draw(G,with_labels=True)
plt.show()

运行结果:
在这里插入图片描述
因为我们只在图中增加了几个点,没有边

访问节点

print('图中所有的节点', G.nodes())
print('图中节点的个数', G.number_of_nodes())

运行结果:
在这里插入图片描述

删除节点

G.remove_node(1)    #删除指定节点
G.remove_nodes_from(['b','c','d','e'])    #删除集合中的节点

添加边

G.add_edge('a','b')
G.add_edges_from([('a','c'),('a','d'),('a','e')])

运行结果:
在这里插入图片描述

访问边

print('图中所有的边', F.edges())
print('图中边的个数', F.number_of_edges()) 

在这里插入图片描述

遍历边

for u,v,d in G.edges(data = 'weight'):
    print((u,v,d))

在这里插入图片描述
无权重的

for n, nbrs in G.adjacency():
    for nbr, eattr in nbrs.items():
        print('({},{})'.format(n,nbr))

在这里插入图片描述
有权重的

for n, nbrs in G.adjacency():
    for nbr, eattr in nbrs.items():
    	data = eattr['weight']
        print('({},{},{})'.format(n,nbr,data))

生成小世界网络

参考小世界网络和复杂网络+python代码实现

import networkx as ne #导入建网络模型包,命名ne
import matplotlib.pyplot as plt #导入科学绘图包,命名mp
#WS network graphy
print('请输入网络节点总数NETWORK_SIZE:')
NETWORK_SIZE=int(input())
print('请输入规则网络要连的邻接个数k:')
k=int(input())
print('请输入重连概率p:')
p=float(input())
ws=ne.watts_strogatz_graph(NETWORK_SIZE,k,p)
ps=ne.circular_layout(ws)#布置框架
ne.draw(ws,ps,with_labels=False,node_size=30)
plt.show()

在这里插入图片描述

生成规则网络

如果把重练概率改为0,则为规则网络
代码同上
在这里插入图片描述

另一种规则图

生成含有20个节点,每个节点包含3个邻居的规则图

import networkx as nx
import matplotlib.pyplot as plt
RG = nx.random_graphs.random_regular_graph(3,20)
# pos = nx.spectral_layout(RG)
pos = nx.circular_layout(RG)
nx.draw(RG,pos,with_labels=False,node_size = 30)
plt.show()

ER随即图

以概率p生成N个节点中的每一对节点

import networkx as nx
import matplotlib.pyplot as plt
ER = nx.random_graphs.erdos_renyi_graph(20,0.2)
pos = nx.shell_layout(ER)
nx.draw(ER,pos,with_labels = False,node_size = 30)
plt.show()

BA无标度网络

涩会给你成n个节点,每次加入m条边的BA无标度网络

import networkx as nx
import matplotlib.pyplot as plt
BA = nx.random_graphs.barabasi_albert_graph(20,1)
pos = nx.spring_layout(BA)
nx.draw(BA,pos,with_labels=False,node_size=30)
plt.show()

在这里插入图片描述

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/qq_34107425/article/details/104085551
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢