實際問題
Pytorch有的時候需要對一些層的參數進行固定,這些層不進行參數的梯度更新
問題解決思路
那么從理論上來說就有兩種辦法
- 優化器初始化的時候不包含這些不想被更新的參數,這樣他們會進行梯度回傳,但是不會被更新
- 將這些不會被更新的參數梯度歸零,或者不計算它們的梯度
思路就是利用tensor
的requires_grad
,每一個tensor
都有自己的requires_grad
成員,值只能為True
和False
。我們對不需要參與訓練的參數的requires_grad
設置為False
。
在optim參數模型參數中過濾掉requires_grad為False的參數。
還是以上面搭建的簡單網絡為例,我們固定第一個卷積層的參數,訓練其他層的所有參數。
代碼實現
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
class Net(nn.Module): def __init__( self ): super (Net, self ).__init__() self .conv1 = nn.Conv2d( 3 , 32 , 3 ) self .conv2 = nn.Conv2d( 32 , 24 , 3 ) self .prelu = nn.PReLU() for m in self .modules(): if isinstance (m,nn.Conv2d): nn.init.xavier_normal_(m.weight.data) nn.init.constant_(m.bias.data, 0 ) if isinstance (m,nn.Linear): m.weight.data.normal_( 0.01 , 0 , 1 ) m.bias.data.zero_() def forward( self , input ): out = self .conv1( input ) out = self .conv2(out) out = self .prelu(out) return out |
遍歷第一層的參數,然后為其設置requires_grad
1
2
3
4
5
6
|
model = Net() for name, p in model.named_parameters(): if name.startswith( 'conv1' ): p.requires_grad = False optimizer = torch.optim.Adam( filter ( lambda x: x.requires_grad is not False ,model.parameters()),lr = 0.2 ) |
為了驗證一下我們的設置是否正確,我們分別看看model
中的參數的requires_grad
和optim
中的params_group()
。
1
2
|
for p in model.parameters(): print (p.requires_grad) |
能看出優化器僅僅對requires_grad
為True
的參數進行迭代優化。
LAST 參考文獻
Pytorch中,動態調整學習率、不同層設置不同學習率和固定某些層訓練的方法_我的博客有點東西-CSDN博客
到此這篇關于Pytorch實現網絡部分層的固定不進行回傳更新的文章就介紹到這了,更多相關Pytorch網絡部分層內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://blog.csdn.net/qq_41554005/article/details/119899140