pytorch固定网络参数

        在微调的时候,特征提取层可能已经收敛不再需要backward更新,这个时候我们需要去固定它的参数,可以使用requires_grad_(False)、detach_()来实现。

结论:

        requires_grad_(False)只会将当前层的参数固定,对梯度往前传播不造成影响,从结果上看除了第二层的grad为None,与不固定参数来比其他层grad是相同的。detach_()直接从当前层把梯度截断了。显然,requires_grad_(False)更加灵活,可以把任意层的参数固定,而使用detach_(),当前层和之前的所以层的参数都固定,但是如果需求是一样的话detach_()的性能更好一些。

具体代码和结果:

1.requires_grad_(False),具体代码如下:

import torch
def init_weights(m):
    if type(m) == torch.nn.Linear :
        m.weight.data=torch.ones_like(m.weight)
        m.bias.data = torch.ones_like(m.bias)
class Net(torch.nn.Module):
    def __init__(self):
        super(Net,self).__init__()
        self.f1=torch.nn.Linear(1,2)
        self.f2=torch.nn.Linear(2,3)
        self.f3 = torch.nn.Linear(3, 2)
    def forward(self,x):
        a1=self.f1(x)
        a2=self.f2(a1)
        a3=self.f3(a2)
        return a3
net=Net()
net.apply(init_weights)    #为了固定住网络的初始参数
print(net.f1.weight.grad,net.f2.weight.grad,net.f3.weight.grad,sep="\n")
print("-------------")
net.f2.requires_grad_(False)
x=torch.tensor([1],dtype=torch.float32).reshape(1,1)
y=net(x)
y.sum().backward()
print(net.f1.weight.grad,net.f2.weight.grad,net.f3.weight.grad,sep="\n")

结果:

 如果将 net.f2.requires_grad_(False)注释得到的结果为:

2.detach_(),具体代码如下:

import torch
def init_weights(m):
    if type(m) == torch.nn.Linear :
        m.weight.data=torch.ones_like(m.weight)
        m.bias.data = torch.ones_like(m.bias)
class Net(torch.nn.Module):
    def __init__(self):
        super(Net,self).__init__()
        self.f1=torch.nn.Linear(1,2)
        self.f2=torch.nn.Linear(2,3)
        self.f3 = torch.nn.Linear(3, 2)
    def forward(self,x):
        a1=self.f1(x)
        a2=self.f2(a1)
        a2.detach_()
        a3=self.f3(a2)
        return a3
net=Net()
net.apply(init_weights)
print(net.f1.weight.grad,net.f2.weight.grad,net.f3.weight.grad,sep="\n")
print("-------------")
x=torch.tensor([1],dtype=torch.float32).reshape(1,1)
y=net(x)
y.sum().backward()
print(net.f1.weight.grad,net.f2.weight.grad,net.f3.weight.grad,sep="\n")

结果:

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值