python复杂网络分析库networkx
文章目錄
- 1 簡介
- 安裝
- 支持四種圖
- 繪制網絡圖基本流程
- 2 Graph-無向圖
- 節點
- 邊
- 屬性
- 有向圖和無向圖互轉
- 3 DiGraph-有向圖
- 一些精美的圖例子
- 環形樹狀圖
- 權重圖
- Giant Component
- Random Geometric Graph 隨機幾何圖
- 節點顏色漸變
- 邊的顏色漸變
- Atlas
- 畫個五角星
- Club
- 畫一個多層感知機
- 繪制一個DNN結構圖
- 一些圖論算法
- 最短路徑
- 問題
- 一些其他神經網絡繪制工具列表
- 參考
1 簡介
networkx是一個用Python語言開發的圖論與復雜網絡建模工具,內置了常用的圖與復雜網絡分析算法,可以方便的進行復雜網絡數據分析、仿真建模等工作。
利用networkx可以以標準化和非標準化的數據格式存儲網絡、生成多種隨機網絡和經典網絡、分析網絡結構、建立網絡模型、設計新的網絡算法、進行網絡繪制等。
networkx支持創建簡單無向圖、有向圖和多重圖(multigraph);內置許多標準的圖論算法,節點可為任意數據;支持任意的邊值維度,功能豐富,簡單易用。
networkx以圖(graph)為基本數據結構。圖既可以由程序生成,也可以來自在線數據源,還可以從文件與數據庫中讀取。
安裝
安裝的話,跟其他包的安裝差不多,用的是anaconda就不用裝了。其他就用pip install networkx。
查看版本:
>>> import networkx >>> networkx.__version__ '1.11'升級
pip install --upgrade networkx下面配合使用的一些庫,可以選擇性安裝:
后面可能用到pygraphviz,安裝方法如下(親測有效):
windows的安裝參考這篇博客:
https://blog.csdn.net/fadai1993/article/details/82491657#2____linux_9
安裝cv2:
pip install opencv-python #安裝非常慢,用下面的方式,從清華源下載 pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple opencv-python支持四種圖
- Graph:無多重邊無向圖
- DiGraph:無多重邊有向圖
- MultiGraph:有多重邊無向圖
- MultiDiGraph:有多重邊有向圖
空圖對象的創建方式
import networkx as nx G=nx.Graph() G=nx.DiGraph() G=nx.MultiGraph() G=nx.MultiDiGraph() G.clear() #清空圖繪制網絡圖基本流程
- 導入networkx,matplotlib包
- 建立網絡
- 繪制網絡 nx.draw()
- 建立布局 pos = nx.spring_layout美化作用
networkx 提供畫圖的函數
- draw(G,[pos,ax,hold])
- draw_networkx(G,[pos,with_labels])
- draw_networkx_nodes(G,pos,[nodelist])繪制網絡G的節點圖
- draw_networkx_edges(G,pos[edgelist])繪制網絡G的邊圖
- draw_networkx_edge_labels(G, pos[, …]) 繪制網絡G的邊圖,邊有label
—有layout 布局畫圖函數的分界線— - draw_circular(G, **kwargs) Draw the graph G with a circular layout.
- draw_random(G, **kwargs) Draw the graph G with a random layout.
- draw_spectral(G, **kwargs)Draw the graph G with a spectral layout.
- draw_spring(G, **kwargs)Draw the graph G with a spring layout.
- draw_shell(G, **kwargs) Draw networkx graph with shell layout.
- draw_graphviz(G[, prog])Draw networkx graph with graphviz layout.
networkx 畫圖函數里的一些參數
- pos(dictionary, optional): 圖像的布局,可選擇參數;如果是字典元素,則節點是關鍵字,位置是對應的值。如果沒有指明,則會是spring的布局;也可以使用其他類型的布局,具體可以查閱networkx.layout
- arrows :布爾值,默認True; 對于有向圖,如果是True則會畫出箭頭
- with_labels: 節點是否帶標簽(默認為True)
- ax:坐標設置,可選擇參數;依照設置好的Matplotlib坐標畫圖
- nodelist:一個列表,默認G.nodes(); 給定節點
- edgelist:一個列表,默認G.edges();給定邊
- node_size: 指定節點的尺寸大小(默認是300,單位未知,就是上圖中那么大的點)
- node_color: 指定節點的顏色 (默認是紅色,可以用字符串簡單標識顏色,例如’r’為紅色,'b’為綠色等,具體可查看手冊),用“數據字典”賦值的時候必須對字典取值(.values())后再賦值
- node_shape: 節點的形狀(默認是圓形,用字符串’o’標識,具體可查看手冊)
- alpha: 透明度 (默認是1.0,不透明,0為完全透明)
- cmap:Matplotlib的顏色映射,默認None; 用來表示節點對應的強度
- vmin,vmax:浮點數,默認None;節點顏色映射尺度的最大和最小值
- linewidths:[None|標量|一列值];圖像邊界的線寬
- width: 邊的寬度 (默認為1.0)
- edge_color: 邊的顏色(默認為黑色)
- edge_cmap:Matplotlib的顏色映射,默認None; 用來表示邊對應的強度
- edge_vmin,edge_vmax:浮點數,默認None;邊的顏色映射尺度的最大和最小值
- style: 邊的樣式(默認為實現,可選: solid|dashed|dotted,dashdot)
- labels:字典元素,默認None;文本形式的節點標簽
- font_size: 節點標簽字體大小 (默認為12)
- font_color: 節點標簽字體顏色(默認為黑色)
- node_size:節點大小
- font_weight:字符串,默認’normal’
- font_family:字符串,默認’sans-serif’
布局指定節點排列形式
- circular_layout:節點在一個圓環上均勻分布
- random_layout:節點隨機分布
- shell_layout:節點在同心圓上分布
- spring_layout: 用Fruchterman-Reingold算法排列節點,中心放射狀分布
- spectral_layout:根據圖的拉普拉斯特征向量排列節點
布局也可用pos參數指定,例如,nx.draw(G, pos = spring_layout(G)) 這樣指定了networkx上以中心放射狀分布.
2 Graph-無向圖
如果添加的節點和邊是已經存在的,是不會報錯的,NetworkX會自動忽略掉已經存在的邊和節點的添加。
節點
常用函數
- nodes(G):在圖節點上返回一個迭代器
- number_of_nodes(G):返回圖中節點的數量
- all_neighbors(graph, node):返回圖中節點的所有鄰居
- non_neighbors(graph, node):返回圖中沒有鄰居的節點
- common_neighbors(G, u, v):返回圖中兩個節點的公共鄰居
邊
常用函數
- edges(G[, nbunch]):返回與nbunch中的節點相關的邊的視圖
- number_of_edges(G):返回圖中邊的數目
- non_edges(graph):返回圖中不存在的邊
使用鄰接迭代器遍歷每一條邊
import networkx as nx import matplotlib.pyplot as plt#快速遍歷每一條邊,可以使用鄰接迭代器實現,對于無向圖,每一條邊相當于兩條有向邊 FG = nx.Graph() FG.add_weighted_edges_from([(1,2,0.125), (1,3,0.75), (2,4,1.2), (3,4,0.275)]) for n, nbrs in FG.adjacency_iter():for nbr, eattr in nbrs.items():data = eattr['weight']print('(%d, %d, %0.3f)' % (n,nbr,data))# (1, 2, 0.125)# (1, 3, 0.750)# (2, 1, 0.125)# (2, 4, 1.200)# (3, 1, 0.750)# (3, 4, 0.275)# (4, 2, 1.200)# (4, 3, 0.275)print('***********************************')#篩選weight小于0.5的邊: FG = nx.Graph() FG.add_weighted_edges_from([(1,2,0.125), (1,3,0.75), (2,4,1.2), (3,4,0.275)]) for n, nbrs in FG.adjacency_iter():for nbr, eattr in nbrs.items():data = eattr['weight']if data < 0.5:print('(%d, %d, %0.3f)' % (n,nbr,data))# (1, 2, 0.125)# (2, 1, 0.125)# (3, 4, 0.275)# (4, 3, 0.275)print('***********************************')#一種方便的訪問所有邊的方法: for u,v,d in FG.edges(data = 'weight'):print((u,v,d))# (1, 2, 0.125)# (1, 3, 0.75)# (2, 4, 1.2)# (3, 4, 0.275)屬性
- 屬性諸如weight,labels,colors,或者任何對象,都可以附加到圖、節點或邊上。
- 對于每一個圖、節點和邊都可以在關聯的屬性字典中保存一個(多個)鍵-值對。
- 默認情況下這些是一個空的字典,但是可以增加或者是改變這些屬性。
圖的屬性
#圖的屬性import networkx as nxG = nx.Graph(day='Monday') #可以在創建圖時分配圖的屬性 print(G.graph)G.graph['day'] = 'Friday' #也可以修改已有的屬性 print(G.graph)G.graph['name'] = 'time' #可以隨時添加新的屬性到圖中 print(G.graph)輸出: {'day': 'Monday'} {'day': 'Friday'} {'day': 'Friday', 'name': 'time'}節點的屬性
#節點的屬性 import networkx as nxG = nx.Graph(day='Monday') G.add_node(1, index='1th') #在添加節點時分配節點屬性 # print(G.node(data=True)) #TypeError: 'dict' object is not callable print(G.node) #{1: {'index': '1th'}}G.node[1]['index'] = '0th' #通過G.node[][]來添加或修改屬性 print(G.node) # {1: {'index': '0th'}}G.add_nodes_from([2,3], index='2/3th') #從集合中添加節點時分配屬性 print(G.node) # {1: {'index': '0th'}, 2: {'index': '2/3th'}, 3: {'index': '2/3th'}}邊的屬性
#邊的屬性 import networkx as nxG = nx.Graph(day='manday') G.add_edge(1,2,weight=10) #在添加邊時分配屬性 print(G.edges(data=True)) #[(1, 2, {'weight': 10})]G.add_edges_from([(1,3), (4,5)], len=22) #從集合中添加邊時分配屬性 print(G.edges(data='len')) # [(1, 2, None), (1, 3, 22), (4, 5, 22)]G.add_edges_from([(3,4,{'hight':10}),(1,4,{'high':'unknow'})]) print(G.edges(data=True)) # [(1, 2, {'weight': 10}), (1, 3, {'len': 22}), (1, 4, {'high': 'unknow'}), (3, 4, {'hight': 10}), (4, 5, {'len': 22})]G[1][2]['weight'] = 100000 #通過G[][][]來添加或修改屬性 print(G.edges(data=True)) # [(1, 2, {'weight': 100000}), (1, 3, {'len': 22}), (1, 4, {'high': 'unknow'}), (3, 4, {'hight': 10}), (4, 5, {'len': 22})]有向圖和無向圖互轉
有向圖和多重圖的基本操作與無向圖一致。
無向圖與有向圖之間可以相互轉換,轉化方法如下:
3 DiGraph-有向圖
import networkx as nx import matplotlib.pyplot as pltG = nx.DiGraph() G.add_node(1) G.add_node(2) G.add_nodes_from([3,4,5,6]) G.add_cycle([1,2,3,4]) G.add_edge(1,3) G.add_edges_from([(3,5),(3,6),(6,7)]) nx.draw(G,node_color = 'red') plt.savefig("youxiangtu.png") plt.show() from __future__ import division import matplotlib.pyplot as plt import networkx as nxG = nx.generators.directed.random_k_out_graph(10, 3, 0.5) pos = nx.layout.spring_layout(G)node_sizes = [3 + 10 * i for i in range(len(G))] M = G.number_of_edges() edge_colors = range(2, M + 2) edge_alphas = [(5 + i) / (M + 4) for i in range(M)]nodes = nx.draw_networkx_nodes(G, pos, node_size=node_sizes, node_color='blue') edges = nx.draw_networkx_edges(G, pos, node_size=node_sizes, arrowstyle='->',arrowsize=10, edge_color=edge_colors,edge_cmap=plt.cm.Blues, width=2) # set alpha value for each edge for i in range(M):edges[i].set_alpha(edge_alphas[i])ax = plt.gca() ax.set_axis_off() plt.savefig("directed.jpg") plt.show()一些精美的圖例子
環形樹狀圖
import matplotlib.pyplot as plt import networkx as nxtry:import pygraphvizfrom networkx.drawing.nx_agraph import graphviz_layout except ImportError:try:import pydotfrom networkx.drawing.nx_pydot import graphviz_layoutexcept ImportError:raise ImportError("This example needs Graphviz and either ""PyGraphviz or pydot")G = nx.balanced_tree(3, 5) pos = graphviz_layout(G, prog='twopi', args='') plt.figure(figsize=(8, 8)) nx.draw(G, pos, node_size=20, alpha=0.5, node_color="blue", with_labels=False) plt.axis('equal') plt.show()權重圖
import matplotlib.pyplot as plt import networkx as nxG = nx.Graph()G.add_edge('a', 'b', weight=0.6) G.add_edge('a', 'c', weight=0.2) G.add_edge('c', 'd', weight=0.1) G.add_edge('c', 'e', weight=0.7) G.add_edge('c', 'f', weight=0.9) G.add_edge('a', 'd', weight=0.3)elarge = [(u, v) for (u, v, d) in G.edges(data=True) if d['weight'] > 0.5] esmall = [(u, v) for (u, v, d) in G.edges(data=True) if d['weight'] <= 0.5]pos = nx.spring_layout(G) # positions for all nodes# nodes nx.draw_networkx_nodes(G, pos, node_size=700)# edges nx.draw_networkx_edges(G, pos, edgelist=elarge,width=6) nx.draw_networkx_edges(G, pos, edgelist=esmall,width=6, alpha=0.5, edge_color='b', style='dashed')# labels nx.draw_networkx_labels(G, pos, font_size=20, font_family='sans-serif')plt.axis('off') plt.savefig("weight.jpg") plt.show()Giant Component
import mathimport matplotlib.pyplot as plt import networkx as nxtry:import pygraphvizfrom networkx.drawing.nx_agraph import graphviz_layoutlayout = graphviz_layout except ImportError:try:import pydotfrom networkx.drawing.nx_pydot import graphviz_layoutlayout = graphviz_layoutexcept ImportError:print("PyGraphviz and pydot not found;\n""drawing with spring layout;\n""will be slow.")layout = nx.spring_layoutn = 150 # 150 nodes # p value at which giant component (of size log(n) nodes) is expected p_giant = 1.0 / (n - 1) # p value at which graph is expected to become completely connected p_conn = math.log(n) / float(n)# the following range of p values should be close to the threshold pvals = [0.003, 0.006, 0.008, 0.015]region = 220 # for pylab 2x2 subplot layout plt.subplots_adjust(left=0, right=1, bottom=0, top=0.95, wspace=0.01, hspace=0.01) for p in pvals:G = nx.binomial_graph(n, p)pos = layout(G)region += 1plt.subplot(region)plt.title("p = %6.3f" % (p))nx.draw(G, pos,with_labels=False,node_size=10)# identify largest connected componentGcc = sorted(nx.connected_component_subgraphs(G), key=len, reverse=True)G0 = Gcc[0]nx.draw_networkx_edges(G0, pos,with_labels=False,edge_color='r',width=6.0)# show other connected componentsfor Gi in Gcc[1:]:if len(Gi) > 1:nx.draw_networkx_edges(Gi, pos,with_labels=False,edge_color='r',alpha=0.3,width=5.0) plt.show()Random Geometric Graph 隨機幾何圖
import matplotlib.pyplot as plt import networkx as nxG = nx.random_geometric_graph(200, 0.125) # position is stored as node attribute data for random_geometric_graph pos = nx.get_node_attributes(G, 'pos')# find node near center (0.5,0.5) dmin = 1 ncenter = 0 for n in pos:x, y = pos[n]d = (x - 0.5)**2 + (y - 0.5)**2if d < dmin:ncenter = ndmin = d# color by path length from node near center p = dict(nx.single_source_shortest_path_length(G, ncenter))plt.figure(figsize=(8, 8)) nx.draw_networkx_edges(G, pos, nodelist=[ncenter], alpha=0.4) nx.draw_networkx_nodes(G, pos, nodelist=list(p.keys()),node_size=80,node_color=list(p.values()),cmap=plt.cm.Reds_r)plt.xlim(-0.05, 1.05) plt.ylim(-0.05, 1.05) #plt.axis('off') plt.show()節點顏色漸變
import networkx as nx import matplotlib.pyplot as plt G = nx.cycle_graph(24) pos = nx.spring_layout(G, iterations=200) nx.draw(G, pos, node_color=range(24), node_size=800, cmap=plt.cm.Blues) plt.savefig("node.jpg") plt.show()邊的顏色漸變
import matplotlib.pyplot as plt import networkx as nxG = nx.star_graph(20) pos = nx.spring_layout(G) #布局為中心放射狀 colors = range(20) nx.draw(G, pos, node_color='#A0CBE2', edge_color=colors,width=4, edge_cmap=plt.cm.Blues, with_labels=False) plt.show()Atlas
import randomtry:import pygraphvizfrom networkx.drawing.nx_agraph import graphviz_layout except ImportError:try:import pydotfrom networkx.drawing.nx_pydot import graphviz_layoutexcept ImportError:raise ImportError("This example needs Graphviz and either ""PyGraphviz or pydot.")import matplotlib.pyplot as pltimport networkx as nx from networkx.algorithms.isomorphism.isomorph import graph_could_be_isomorphic as isomorphic from networkx.generators.atlas import graph_atlas_gdef atlas6():""" Return the atlas of all connected graphs of 6 nodes or less.Attempt to check for isomorphisms and remove."""Atlas = graph_atlas_g()[0:208] # 208# remove isolated nodes, only connected graphs are leftU = nx.Graph() # graph for union of all graphs in atlasfor G in Atlas:zerodegree = [n for n in G if G.degree(n) == 0]for n in zerodegree:G.remove_node(n)U = nx.disjoint_union(U, G)# iterator of graphs of all connected componentsC = (U.subgraph(c) for c in nx.connected_components(U))UU = nx.Graph()# do quick isomorphic-like check, not a true isomorphism checkernlist = [] # list of nonisomorphic graphsfor G in C:# check against all nonisomorphic graphs so farif not iso(G, nlist):nlist.append(G)UU = nx.disjoint_union(UU, G) # union the nonisomorphic graphsreturn UUdef iso(G1, glist):"""Quick and dirty nonisomorphism checker used to check isomorphisms."""for G2 in glist:if isomorphic(G1, G2):return Truereturn Falseif __name__ == '__main__':G = atlas6()print("graph has %d nodes with %d edges"% (nx.number_of_nodes(G), nx.number_of_edges(G)))print(nx.number_connected_components(G), "connected components")plt.figure(1, figsize=(8, 8))# layout graphs with positions using graphviz neatopos = graphviz_layout(G, prog="neato")# color nodes the same in each connected subgraphC = (G.subgraph(c) for c in nx.connected_components(G))for g in C:c = [random.random()] * nx.number_of_nodes(g) # random color...nx.draw(g,pos,node_size=40,node_color=c,vmin=0.0,vmax=1.0,with_labels=False)plt.show()畫個五角星
import networkx as nx import matplotlib.pyplot as plt #畫圖! G=nx.Graph() G.add_node(1) G.add_nodes_from([2,3,4,5]) for i in range(5):for j in range(i):if (abs(i-j) not in (1,4)):G.add_edge(i+1, j+1) nx.draw(G,with_labels=True, #這個選項讓節點有名稱edge_color='b', # b stands for blue!pos=nx.circular_layout(G), # 這個是選項選擇點的排列方式,具體可以用 help(nx.drawing.layout) 查看# 主要有spring_layout (default), random_layout, circle_layout, shell_layout# 這里是環形排布,還有隨機排列等其他方式node_color='r', # r = rednode_size=1000, # 節點大小width=3, # 邊的寬度) plt.savefig("star.jpg") plt.show()Club
import matplotlib.pyplot as plt import networkx as nx import networkx.algorithms.bipartite as bipartiteG = nx.davis_southern_women_graph() women = G.graph['top'] clubs = G.graph['bottom']print("Biadjacency matrix") print(bipartite.biadjacency_matrix(G, women, clubs))# project bipartite graph onto women nodes W = bipartite.projected_graph(G, women) print('') print("#Friends, Member") for w in women:print('%d %s' % (W.degree(w), w))# project bipartite graph onto women nodes keeping number of co-occurence # the degree computed is weighted and counts the total number of shared contacts W = bipartite.weighted_projected_graph(G, women) print('') print("#Friend meetings, Member") for w in women:print('%d %s' % (W.degree(w, weight='weight'), w))nx.draw(G,node_color="red") plt.savefig("club.jpg") plt.show()畫一個多層感知機
import matplotlib.pyplot as plt import networkx as nx left, right, bottom, top, layer_sizes = .1, .9, .1, .9, [4, 7, 7, 2] # 網絡離上下左右的距離 # layter_sizes可以自己調整 import random G = nx.Graph() v_spacing = (top - bottom)/float(max(layer_sizes)) h_spacing = (right - left)/float(len(layer_sizes) - 1) node_count = 0 for i, v in enumerate(layer_sizes):layer_top = v_spacing*(v-1)/2. + (top + bottom)/2.for j in range(v):G.add_node(node_count, pos=(left + i*h_spacing, layer_top - j*v_spacing))node_count += 1 # 這上面的數字調整我想了好半天,汗 for x, (left_nodes, right_nodes) in enumerate(zip(layer_sizes[:-1], layer_sizes[1:])):for i in range(left_nodes):for j in range(right_nodes):G.add_edge(i+sum(layer_sizes[:x]), j+sum(layer_sizes[:x+1]))pos=nx.get_node_attributes(G,'pos') # 把每個節點中的位置pos信息導出來 nx.draw(G, pos,node_color=range(node_count),with_labels=True,node_size=200,edge_color=[random.random() for i in range(len(G.edges))],width=3,cmap=plt.cm.Dark2, # matplotlib的調色板,可以搜搜,很多顏色edge_cmap=plt.cm.Blues) plt.savefig("mlp.jpg") plt.show()繪制一個DNN結構圖
# -*- coding:utf-8 -*- import networkx as nx import matplotlib.pyplot as plt# 創建DAG G = nx.DiGraph()# 頂點列表 vertex_list = ['v'+str(i) for i in range(1, 22)] # 添加頂點 G.add_nodes_from(vertex_list)# 邊列表 edge_list = [('v1', 'v5'), ('v1', 'v6'), ('v1', 'v7'),('v1', 'v8'),('v1', 'v9'),('v2', 'v5'), ('v2', 'v6'), ('v2', 'v7'),('v2', 'v8'),('v2', 'v9'),('v3', 'v5'), ('v3', 'v6'), ('v3', 'v7'),('v3', 'v8'),('v3', 'v9'),('v4', 'v5'), ('v4', 'v6'), ('v4', 'v7'),('v4', 'v8'),('v4', 'v9'),('v5','v10'),('v5','v11'),('v5','v12'),('v5','v13'),('v5','v14'),('v5','v15'),('v6','v10'),('v6','v11'),('v6','v12'),('v6','v13'),('v6','v14'),('v6','v15'),('v7','v10'),('v7','v11'),('v7','v12'),('v7','v13'),('v7','v14'),('v7','v15'),('v8','v10'),('v8','v11'),('v8','v12'),('v8','v13'),('v8','v14'),('v8','v15'),('v9','v10'),('v9','v11'),('v9','v12'),('v9','v13'),('v9','v14'),('v9','v15'),('v10','v16'),('v10','v17'),('v10','v18'),('v11','v16'),('v11','v17'),('v11','v18'),('v12','v16'),('v12','v17'),('v12','v18'),('v13','v16'),('v13','v17'),('v13','v18'),('v14','v16'),('v14','v17'),('v14','v18'),('v15','v16'),('v15','v17'),('v15','v18'),('v16','v19'),('v17','v20'),('v18','v21')] # 通過列表形式來添加邊 G.add_edges_from(edge_list)# 繪制DAG圖 plt.title('DNN for iris') #圖片標題nx.draw(G,node_color = 'red', # 頂點顏色edge_color = 'black', # 邊的顏色with_labels = True, # 顯示頂點標簽font_size =10, # 文字大小node_size =300 # 頂點大小) # 顯示圖片 plt.show()可以看到,在代碼中已經設置好了這22個神經元以及它們之間的連接情況,但繪制出來的結構如卻是這樣的:
這顯然不是想要的結果,因為各神經的連接情況不明朗,而且很多神經都擠在了一起,看不清楚。之所以出現這種情況,是因為沒有給神經元設置坐標,導致每個神經元都是隨機放置的。
接下來,引入坐標機制,即設置好每個神經元節點的坐標,使得它們的位置能夠按照事先設置好的來放置,其Python代碼如下:
可以看到,在代碼中,通過pos字典已經規定好了每個神經元節點的位置。
接下來,需要對這個框架圖進行更為細致地修改,需要修改的地方為:
- 去掉神經元節點的標簽;
- 添加模型層的文字注釋(比如Input layer)
其中,第二步的文字注釋,我們借助opencv來完成。完整的Python代碼如下:
# -*- coding:utf-8 -*- import cv2 import networkx as nx import matplotlib.pyplot as plt# 創建DAG G = nx.DiGraph()# 頂點列表 vertex_list = ['v'+str(i) for i in range(1, 22)] # 添加頂點 G.add_nodes_from(vertex_list)# 邊列表 edge_list = [('v1', 'v5'), ('v1', 'v6'), ('v1', 'v7'),('v1', 'v8'),('v1', 'v9'),('v2', 'v5'), ('v2', 'v6'), ('v2', 'v7'),('v2', 'v8'),('v2', 'v9'),('v3', 'v5'), ('v3', 'v6'), ('v3', 'v7'),('v3', 'v8'),('v3', 'v9'),('v4', 'v5'), ('v4', 'v6'), ('v4', 'v7'),('v4', 'v8'),('v4', 'v9'),('v5','v10'),('v5','v11'),('v5','v12'),('v5','v13'),('v5','v14'),('v5','v15'),('v6','v10'),('v6','v11'),('v6','v12'),('v6','v13'),('v6','v14'),('v6','v15'),('v7','v10'),('v7','v11'),('v7','v12'),('v7','v13'),('v7','v14'),('v7','v15'),('v8','v10'),('v8','v11'),('v8','v12'),('v8','v13'),('v8','v14'),('v8','v15'),('v9','v10'),('v9','v11'),('v9','v12'),('v9','v13'),('v9','v14'),('v9','v15'),('v10','v16'),('v10','v17'),('v10','v18'),('v11','v16'),('v11','v17'),('v11','v18'),('v12','v16'),('v12','v17'),('v12','v18'),('v13','v16'),('v13','v17'),('v13','v18'),('v14','v16'),('v14','v17'),('v14','v18'),('v15','v16'),('v15','v17'),('v15','v18'),('v16','v19'),('v17','v20'),('v18','v21')] # 通過列表形式來添加邊 G.add_edges_from(edge_list)# 指定繪制DAG圖時每個頂點的位置 pos = {'v1':(-2,1.5),'v2':(-2,0.5),'v3':(-2,-0.5),'v4':(-2,-1.5),'v5':(-1,2),'v6': (-1,1),'v7':(-1,0),'v8':(-1,-1),'v9':(-1,-2),'v10':(0,2.5),'v11':(0,1.5),'v12':(0,0.5),'v13':(0,-0.5),'v14':(0,-1.5),'v15':(0,-2.5),'v16':(1,1),'v17':(1,0),'v18':(1,-1),'v19':(2,1),'v20':(2,0),'v21':(2,-1)} # 繪制DAG圖 plt.title('DNN for iris') #圖片標題 plt.xlim(-2.2, 2.2) #設置X軸坐標范圍 plt.ylim(-3, 3) #設置Y軸坐標范圍 nx.draw(G,pos = pos, # 點的位置node_color = 'red', # 頂點顏色edge_color = 'black', # 邊的顏色font_size =10, # 文字大小node_size =300 # 頂點大小)# 保存圖片,圖片大小為640*480 plt.savefig('DNN_sketch.png')# 利用opencv模塊對DNN框架添加文字注釋# 讀取圖片 imagepath = 'DNN_sketch.png' image = cv2.imread(imagepath, 1)# 輸入層 cv2.rectangle(image, (85, 130), (120, 360), (255,0,0), 2) cv2.putText(image, "Input Layer", (15, 390), 1, 1.5, (0, 255, 0), 2, 1)# 隱藏層 cv2.rectangle(image, (190, 70), (360, 420), (255,0,0), 2) cv2.putText(image, "Hidden Layer", (210, 450), 1, 1.5, (0, 255, 0), 2, 1)# 輸出層 cv2.rectangle(image, (420, 150), (460, 330), (255,0,0), 2) cv2.putText(image, "Output Layer", (380, 360), 1, 1.5, (0, 255, 0), 2, 1)# sofrmax層 cv2.rectangle(image, (530, 150), (570, 330), (255,0,0), 2) cv2.putText(image, "Softmax Func", (450, 130), 1, 1.5, (0, 0, 255), 2, 1)# 保存修改后的圖片 cv2.imwrite('DNN.png', image)一些圖論算法
最短路徑
函數調用:
dijkstra_path(G, source, target, weight=‘weight’) ————求最短路徑
dijkstra_path_length(G, source, target, weight=‘weight’) ————求最短距離
輸出:
生成一個空的有向圖 為這個網絡添加節點... 在網絡中添加帶權中的邊... 給網路設置布局... 畫出網絡圖像: dijkstra方法尋找最短路徑: 節點0到7的路徑: [0, 3, 6, 7] dijkstra方法尋找最短距離: 節點0到7的距離為: 9問題
本人在pycharm中運行下列程序:
import networkx as nx import matplotlib.pyplot as pltG = nx.Graph() # 建立一個空的無向圖G G.add_node('a') # 添加一個節點1 G.add_nodes_from(['b', 'c', 'd', 'e']) # 加點集合 G.add_cycle(['f', 'g', 'h', 'j']) # 加環 H = nx.path_graph(10) # 返回由10個節點挨個連接的無向圖,所以有9條邊 G.add_nodes_from(H) # 創建一個子圖H加入G G.add_node(H) # 直接將圖作為節點nx.draw(G, with_labels=True) plt.show()發現在Pycharm下使用matploylib庫繪制3D圖的時候,在最后需要顯示圖像的時候,每當輸入plt.show() 都會報錯
plt.show() /yyl/Python/3.6/lib/python/site-packages/matplotlib/figure.py:1743: UserWarning: This figure includes Axes that are not compatible with tight_layout, so its results might be incorrect. warnings.warn("This figure includes Axes that are not " ... ValueError: max() arg is an empty sequence網上的解決方案:
File -> Setting -> Tools -> Python Scientific中去掉對Show plots in tool window的勾選就好了
一些其他神經網絡繪制工具列表
| Python+Graphviz | graphviz的python版本(親測) | **** |
| PlotNeuralNet | 第一步生成tex文件,然后調用LaTeX命令行生成圖形(親測) | **** |
| NetworkX | 這是個專門的復雜網絡圖的Python包 | **** |
| Matplotlib’s Viznet | 利用Matplotlib的Viznet | **** |
| LaTeX tikz | 繪制網絡結點圖的tikz庫 | *** |
| Graphviz | 專業繪圖軟件,dot描述語言 | *** |
| Inkscape | 屬于繪圖軟件 | *** |
| Omnigraffle | 由The Omni Group制作的一款繪圖軟件 | *** |
| netron | 支持ONNX (.onnx, .pb, .pbtxt), Keras (.h5, .keras), CoreML (.mlmodel), Caffe2 (predict_net.pb, predict_net.pbtxt), MXNet (.model, -symbol.json) and TensorFlow Lite (.tflite),在前面鏈接處下載文件,在這里演示 | *** |
| TensorBoard | 配合Tensorflow一起使用的 | *** |
| Keras | 自帶plot方法,例子,也需要安裝graphviz,pydot等 | *** |
| Netscope for Caffe | 只支持Caffe格式,例子 | *** |
| draw_convnet | 這個其實是利用Matplotlib的繪圖功能寫了一個Python腳本 | ** |
| dnngraph | 僅使用于Caffe框架 | ** |
| ConvNetDraw | 靈活性差,沒有更新了 | ** |
上面都是一些這個網絡庫使用的一點總結,更多內容可以參考下面的官方鏈接。
參考
- 官方教程:https://networkx.github.io/documentation/stable/_downloads/networkx_reference.pdf
- 官方網站:https://networkx.github.io/documentation/latest/index.html
- 官方githu博客:http://networkx.github.io/
- 用Python的networkx繪制精美網絡圖
- networkx整理
- Networkx使用指南
- 論文中繪制神經網絡工具匯總
- networkx + Cytoscape 構建及可視化網絡圖
- 用python+graphviz/networkx畫目錄結構樹狀圖
總結
以上是生活随笔為你收集整理的python复杂网络分析库networkx的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 邬先生及时功成身退,是明哲保身的聪明做法
- 下一篇: JSON字符串如何转化成对象?