實(shí)際問題
Pytorch有的時(shí)候需要對一些層的參數(shù)進(jìn)行固定,這些層不進(jìn)行參數(shù)的梯度更新
問題解決思路
那么從理論上來說就有兩種辦法
- 優(yōu)化器初始化的時(shí)候不包含這些不想被更新的參數(shù),這樣他們會進(jìn)行梯度回傳,但是不會被更新
- 將這些不會被更新的參數(shù)梯度歸零,或者不計(jì)算它們的梯度
思路就是利用tensor
的requires_grad
,每一個(gè)tensor
都有自己的requires_grad
成員,值只能為True
和False
。我們對不需要參與訓(xùn)練的參數(shù)的requires_grad
設(shè)置為False
。
在optim參數(shù)模型參數(shù)中過濾掉requires_grad為False的參數(shù)。
還是以上面搭建的簡單網(wǎng)絡(luò)為例,我們固定第一個(gè)卷積層的參數(shù),訓(xùn)練其他層的所有參數(shù)。
代碼實(shí)現(xiàn)
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 |
遍歷第一層的參數(shù),然后為其設(shè)置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 ) |
為了驗(yàn)證一下我們的設(shè)置是否正確,我們分別看看model
中的參數(shù)的requires_grad
和optim
中的params_group()
。
1
2
|
for p in model.parameters(): print (p.requires_grad) |
能看出優(yōu)化器僅僅對requires_grad
為True
的參數(shù)進(jìn)行迭代優(yōu)化。
LAST 參考文獻(xiàn)
Pytorch中,動態(tài)調(diào)整學(xué)習(xí)率、不同層設(shè)置不同學(xué)習(xí)率和固定某些層訓(xùn)練的方法_我的博客有點(diǎn)東西-CSDN博客
到此這篇關(guān)于Pytorch實(shí)現(xiàn)網(wǎng)絡(luò)部分層的固定不進(jìn)行回傳更新的文章就介紹到這了,更多相關(guān)Pytorch網(wǎng)絡(luò)部分層內(nèi)容請搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://blog.csdn.net/qq_41554005/article/details/119899140