pytorch 查看当前学习率_如何在Pytorch中应用分层学习率?

bd96500e110b49cbb3cd949968f18be7.png

I know that it is possible to freeze single layers in a network for example to train only the last layers of a pre-trained model. What I’m looking for is a way to apply certain learning rates to different layers.

So for example a very low learning rate of 0.000001 for the first layer and then increasing the learning rate gradually for each of the following layers. So that the last layer then ends up with a learning rate of 0.01 or so.

Is this possible in pytorch? Any idea how I can archive this?

解决方案

Here is the solution:

from torch.optim import Adam

model = Net()

optim = Adam(

[

{"params": model.fc.parameters(), "lr": 1e-3},

{"params": model.agroupoflayer.parameters()},

{"params": model.lastlayer.parameters(), "lr": 4e-2},

],

lr=5e-4,

)

Other parameters that are didn't specify in optimizer will not optimize. So you should state all layers or groups(OR the layers you want to optimize). and if you didn't specify the learning rate it will take the global learning rate(5e-4).

The trick is when you create the model you should give names to the layers or you can group it.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
PyTorch ,可以通过访问优化器对象(optimizer object)来查看当前学习率。优化器对象通常在训练循环使用,用于更新模型参数。以下是一个查看当前学习率的示例代码: ```python import torch.optim as optim # 定义一个模型和一个优化器 model = MyModel() optimizer = optim.Adam(model.parameters(), lr=0.001) # 查看当前学习率 print(optimizer.param_groups[0]['lr']) ``` 在上面的示例代码,`optimizer.param_groups` 是一个列表,其的每个元素都代表一个参数组,包含了该参数组对应的学习率等信息。由于我们只有一个参数组,因此我们可以通过访问 `optimizer.param_groups[0]` 来获取该参数组的信息,然后通过 `'lr'` 键来获取当前学习率。 要调整模型训练的学习率,可以通过修改优化器对象学习率来实现。以下是一个调整学习率的示例代码: ```python import torch.optim as optim # 定义一个模型和一个优化器 model = MyModel() optimizer = optim.Adam(model.parameters(), lr=0.001) # 调整学习率 new_lr = 0.0001 for param_group in optimizer.param_groups: param_group['lr'] = new_lr ``` 在上面的示例代码,我们首先定义了一个模型和一个优化器,并将学习率设置为 0.001。然后,我们通过遍历优化器对象的参数组,并修改 `'lr'` 键来将学习率调整为 0.0001。需要注意的是,由于优化器对象可能包含多个参数组,因此我们需要遍历所有的参数组才能将学习率调整到我们希望的值。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值