您好,登錄后才能下訂單哦!
最簡(jiǎn)單的方法當(dāng)然可以直接print(net),但是這樣網(wǎng)絡(luò)比較復(fù)雜的時(shí)候效果不太好,看著比較亂;以前使用caffe的時(shí)候有一個(gè)網(wǎng)站可以在線生成網(wǎng)絡(luò)框圖,tensorflow可以用tensor board,keras中可以用model.summary()、或者plot_model()。pytorch沒(méi)有這樣的API,但是可以用代碼來(lái)完成。
(1)安裝環(huán)境:graphviz
conda install -n pytorch python-graphviz
或:
sudo apt-get install graphviz
或者從官網(wǎng)下載,按此教程。
(2)生成網(wǎng)絡(luò)結(jié)構(gòu)的代碼:
def make_dot(var, params=None): """ Produces Graphviz representation of PyTorch autograd graph Blue nodes are the Variables that require grad, orange are Tensors saved for backward in torch.autograd.Function Args: var: output Variable params: dict of (name, Variable) to add names to node that require grad (TODO: make optional) """ if params is not None: assert isinstance(params.values()[0], Variable) param_map = {id(v): k for k, v in params.items()} node_attr = dict(style='filled', shape='box', align='left', fontsize='12', ranksep='0.1', height='0.2') dot = Digraph(node_attr=node_attr, graph_attr=dict(size="12,12")) seen = set() def size_to_str(size): return '('+(', ').join(['%d' % v for v in size])+')' def add_nodes(var): if var not in seen: if torch.is_tensor(var): dot.node(str(id(var)), size_to_str(var.size()), fillcolor='orange') elif hasattr(var, 'variable'): u = var.variable name = param_map[id(u)] if params is not None else '' node_name = '%s\n %s' % (name, size_to_str(u.size())) dot.node(str(id(var)), node_name, fillcolor='lightblue') else: dot.node(str(id(var)), str(type(var).__name__)) seen.add(var) if hasattr(var, 'next_functions'): for u in var.next_functions: if u[0] is not None: dot.edge(str(id(u[0])), str(id(var))) add_nodes(u[0]) if hasattr(var, 'saved_tensors'): for t in var.saved_tensors: dot.edge(str(id(t)), str(id(var))) add_nodes(t) add_nodes(var.grad_fn) return dot
(3)打印網(wǎng)絡(luò)結(jié)構(gòu):
import torch from torch.autograd import Variable import torch.nn as nn from graphviz import Digraph class CNN(nn.module): def __init__(self): ****** def forward(self,x): ****** return out ***************************** def make_dot(): #復(fù)制上面的代碼 ***************************** if __name__ == '__main__': net = CNN() x = Variable(torch.randn(1, 1, 1024,1024)) y = net(x) g = make_dot(y) g.view() params = list(net.parameters()) k = 0 for i in params: l = 1 print("該層的結(jié)構(gòu):" + str(list(i.size()))) for j in i.size(): l *= j print("該層參數(shù)和:" + str(l)) k = k + l print("總參數(shù)數(shù)量和:" + str(k))
(4)結(jié)果展示(例如這是一個(gè)resnet block類型的網(wǎng)絡(luò)):
以上這篇pytorch打印網(wǎng)絡(luò)結(jié)構(gòu)的實(shí)例就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。