如何使用PyTorch冻结特定层的参数设置?
- 内容介绍
- 文章标签
- 相关推荐
本文共计474个文字,预计阅读时间需要2分钟。
在迁移学习进行finetune时,我们通常需要冻结前几层的参数,不参与训练。在PyTorch中的实现如下:
pythonclass Model(nn.Module): def __init__(self): super(Transfer_model, self).__init__() self.linear1=nn.Linear(20, 50)
在迁移学习finetune时我们通常需要冻结前几层的参数不参与训练,在Pytorch中的实现如下:
class Model(nn.Module): def __init__(self): super(Transfer_model, self).__init__() self.linear1 = nn.Linear(20, 50) self.linear2 = nn.Linear(50, 20) self.linear3 = nn.Linear(20, 2) def forward(self, x): pass
假如我们想要冻结linear1层,需要做如下操作:
model = Model() # 这里是一般情况,共享层往往不止一层,所以做一个for循环 for para in model.linear1.parameters(): para.requires_grad = False # 假如真的只有一层也可以这样操作: # model.linear1.weight.requires_grad = False
最后我们需要将需要优化的参数传入优化器,不需要传入的参数过滤掉,所以要用到filter()函数。
本文共计474个文字,预计阅读时间需要2分钟。
在迁移学习进行finetune时,我们通常需要冻结前几层的参数,不参与训练。在PyTorch中的实现如下:
pythonclass Model(nn.Module): def __init__(self): super(Transfer_model, self).__init__() self.linear1=nn.Linear(20, 50)
在迁移学习finetune时我们通常需要冻结前几层的参数不参与训练,在Pytorch中的实现如下:
class Model(nn.Module): def __init__(self): super(Transfer_model, self).__init__() self.linear1 = nn.Linear(20, 50) self.linear2 = nn.Linear(50, 20) self.linear3 = nn.Linear(20, 2) def forward(self, x): pass
假如我们想要冻结linear1层,需要做如下操作:
model = Model() # 这里是一般情况,共享层往往不止一层,所以做一个for循环 for para in model.linear1.parameters(): para.requires_grad = False # 假如真的只有一层也可以这样操作: # model.linear1.weight.requires_grad = False
最后我们需要将需要优化的参数传入优化器,不需要传入的参数过滤掉,所以要用到filter()函数。

