您好,登錄后才能下訂單哦!
這篇文章主要介紹如何畫pytorch模型圖以及參數(shù)計(jì)算,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!
首先說說,我們?nèi)绾慰梢暬P?。在keras中就一句話,keras.summary(),或者plot_model(),就可以把模型展現(xiàn)的淋漓盡致。
但是pytorch中好像沒有這樣一個(gè)api讓我們直觀的看到模型的樣子。但是有網(wǎng)友提供了一段代碼,可以把模型畫出來,對我來說簡直就是如有神助啊。
話不多說,上代碼吧。
import torch from torch.autograd import Variable import torch.nn as nn from graphviz import Digraph class CNN(nn.Module): def __init__(self): super(CNN, self).__init__() self.conv1 = nn.Sequential( nn.Conv2d(in_channels=1, out_channels=16, kernel_size=5, stride=1, padding=2), nn.ReLU(), nn.MaxPool2d(kernel_size=2) ) self.conv2 = nn.Sequential( nn.Conv2d(in_channels=16, out_channels=32, kernel_size=5, stride=1, padding=2), nn.ReLU(), nn.MaxPool2d(kernel_size=2) ) self.out = nn.Linear(32*7*7, 10) def forward(self, x): x = self.conv1(x) x = self.conv2(x) x = x.view(x.size(0), -1) # (batch, 32*7*7) out = self.out(x) return out 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 if __name__ == '__main__': net = CNN() x = Variable(torch.randn(1, 1, 28, 28)) 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))
模型很簡單,代碼也很簡單。就是conv -> relu -> maxpool -> conv -> relu -> maxpool -> fc
大家在可視化的時(shí)候,直接復(fù)制make_dot那段代碼即可,然后需要初始化一個(gè)net,以及這個(gè)網(wǎng)絡(luò)需要的數(shù)據(jù)規(guī)模,此處就以 這段代碼為例,初始化一個(gè)模型net,準(zhǔn)備這個(gè)模型的輸入數(shù)據(jù)x,shape為(batch,channels,height,width) 然后把數(shù)據(jù)傳入模型得到輸出結(jié)果y。傳入make_dot即可得到下圖。
net = CNN() x = Variable(torch.randn(1, 1, 28, 28)) y = net(x) g = make_dot(y) g.view()
最后輸出該網(wǎng)絡(luò)的各種參數(shù)。
該層的結(jié)構(gòu):[16, 1, 5, 5] 該層參數(shù)和:400 該層的結(jié)構(gòu):[16] 該層參數(shù)和:16 該層的結(jié)構(gòu):[32, 16, 5, 5] 該層參數(shù)和:12800 該層的結(jié)構(gòu):[32] 該層參數(shù)和:32 該層的結(jié)構(gòu):[10, 1568] 該層參數(shù)和:15680 該層的結(jié)構(gòu):[10] 該層參數(shù)和:10 總參數(shù)數(shù)量和:28938
以上是“如何畫pytorch模型圖以及參數(shù)計(jì)算”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。