pytorch查看模型weight與grad方式
在用pdb debug的時(shí)候,有時(shí)候需要看一下特定layer的權(quán)重以及相應(yīng)的梯度信息,如何查看呢?
1. 首先把你的模型打印出來,像這樣
2. 然后觀察到model下面有module的key,module下面有features的key, features下面有(0)的key,這樣就可以直接打印出weight了,在pdb debug界面輸入p model.module.features[0].weight,就可以看到weight,輸入 p model.module.features[0].weight.grad就可以查看梯度信息
補(bǔ)充知識(shí):查看Pytorch網(wǎng)絡(luò)的各層輸出(feature map)、權(quán)重(weight)、偏置(bias)
BatchNorm2d參數(shù)量
torch.nn.BatchNorm2d(num_features, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) # 卷積層中卷積核的數(shù)量C num_features – C from an expected input of size (N, C, H, W)
>>> import torch >>> m = torch.nn.BatchNorm2d(100) >>> m.weight.shape torch.Size([100]) >>> m.numel() AttributeError: 'BatchNorm2d' object has no attribute 'numel' >>> m.weight.numel() 100 >>> m.parameters().numel() Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'generator' object has no attribute 'numel' >>> [p.numel() for p in m.parameters()] [100, 100]
linear層
>>> import torch >>> m1 = torch.nn.Linear(100,10) # 參數(shù)數(shù)量= (輸入神經(jīng)元+1)*輸出神經(jīng)元 >>> m1.weight.shape torch.Size([10, 100]) >>> m1.bias.shape torch.Size([10]) >>> m1.bias.numel() 10 >>> m1.weight.numel() 1000 >>> m11 = list(m1.parameters()) >>> m11[0].shape # weight torch.Size([10, 100]) >>> m11[1].shape # bias torch.Size([10])
weight and bias
# Method 1 查看Parameters的方式多樣化,直接訪問即可 model = alexnet(pretrained=True).to(device) conv1_weight = model.features[0].weight# Method 2 # 這種方式還適合你想自己參考一個(gè)預(yù)訓(xùn)練模型寫一個(gè)網(wǎng)絡(luò),各層的參數(shù)不變,但網(wǎng)絡(luò)結(jié)構(gòu)上表述有所不同 # 這樣你就可以把param迭代出來,賦給你的網(wǎng)絡(luò)對(duì)應(yīng)層,避免直接load不能匹配的問題! for layer,param in model.state_dict().items(): # param is weight or bias(Tensor) print layer,param
feature map
由于pytorch是動(dòng)態(tài)網(wǎng)絡(luò),不存儲(chǔ)計(jì)算數(shù)據(jù),查看各層輸出的特征圖并不是很方便!分下面兩種情況討論:
1、你想查看的層是獨(dú)立的,那么你在forward時(shí)用變量接收并返回即可?。?/p>
class Net(nn.Module): def __init__(self): self.conv1 = nn.Conv2d(1, 1, 3) self.conv2 = nn.Conv2d(1, 1, 3) self.conv3 = nn.Conv2d(1, 1, 3) def forward(self, x): out1 = F.relu(self.conv1(x)) out2 = F.relu(self.conv2(out1)) out3 = F.relu(self.conv3(out2)) return out1, out2, out3
2、你的想看的層在nn.Sequential()順序容器中,這個(gè)麻煩些,主要有以下幾種思路:
# Method 1 巧用nn.Module.children() # 在模型實(shí)例化之后,利用nn.Module.children()刪除你查看的那層的后面層 import torch import torch.nn as nn from torchvision import modelsmodel = models.alexnet(pretrained=True)# remove last fully-connected layer new_classifier = nn.Sequential(*list(model.classifier.children())[:-1]) model.classifier = new_classifier # Third convolutional layer new_features = nn.Sequential(*list(model.features.children())[:5]) model.features = new_features
# Method 2 巧用hook,推薦使用這種方式,不用改變?cè)心P? # torch.nn.Module.register_forward_hook(hook) # hook(module, input, output) -> Nonemodel = models.alexnet(pretrained=True) # 定義 def hook (module,input,output): print output.size() # 注冊(cè) handle = model.features[0].register_forward_hook(hook) # 刪除句柄 handle.remove()# torch.nn.Module.register_backward_hook(hook) # hook(module, grad_input, grad_output) -> Tensor or None model = alexnet(pretrained=True).to(device) outputs = [] def hook (module,input,output): outputs.append(output) print len(outputs)handle = model.features[0].register_backward_hook(hook)
注:還可以通過定義一個(gè)提取特征的類,甚至是重構(gòu)成各層獨(dú)立相同模型將問題轉(zhuǎn)化成第一種
計(jì)算模型參數(shù)數(shù)量
def count_parameters(model):
return sum(p.numel() for p in model.parameters() if p.requires_grad)
以上這篇pytorch查看模型weight與grad方式就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
用Python實(shí)現(xiàn)批量生成法務(wù)函代碼
大家好,本篇文章主要講的是用Python實(shí)現(xiàn)批量生成法務(wù)函代碼,感興趣的同學(xué)趕快來看一看吧,對(duì)你有幫助的話記得收藏一下2022-02-02Python 線性回歸分析以及評(píng)價(jià)指標(biāo)詳解
這篇文章主要介紹了Python 線性回歸分析以及評(píng)價(jià)指標(biāo)詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-04-04Python線程池thread?pool創(chuàng)建使用及實(shí)例代碼分享
這篇文章主要介紹了Python線程池(thread?pool)創(chuàng)建使用及實(shí)例代碼分享,文章圍繞主題展開詳細(xì)的內(nèi)容介紹具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-06-06使用Python設(shè)計(jì)一個(gè)代碼統(tǒng)計(jì)工具
這篇文章主要介紹了使用Python設(shè)計(jì)一個(gè)代碼統(tǒng)計(jì)工具的相關(guān)資料,包括文件個(gè)數(shù),代碼行數(shù),注釋行數(shù),空行行數(shù)。感興趣的朋友跟隨腳本之家小編一起看看吧2018-04-04基于Python實(shí)現(xiàn)視頻分辨率轉(zhuǎn)換
這篇文章主要介紹了基于Python實(shí)現(xiàn)視頻的分辨率轉(zhuǎn)換的示例代碼,文中的代碼講解詳細(xì),對(duì)學(xué)習(xí)Python有一定的幫助,感興趣的小伙伴可以了解一下2021-12-12python 通過 pybind11 使用Eigen加速代碼的步驟
這篇文章主要介紹了python 通過 pybind11 使用Eigen加速代碼的步驟,幫助大家更好的理解和使用python,感興趣的朋友可以了解下2020-12-12Python 在區(qū)塊鏈智能合約開發(fā)中的應(yīng)用與實(shí)踐小結(jié)
Python作為一種廣泛應(yīng)用的編程語言,在區(qū)塊鏈智能合約開發(fā)中扮演著重要角色,通過使用Python框架如Brownie和Web3.py,開發(fā)者可以輕松編寫和部署智能合約,感興趣的朋友一起看看吧2024-09-09