我怎样才能用pytorch更新网络中的某些特定张量?

问题描述 投票:3回答:2

例如,我想只在前10个时期更新Resnet中的所有cnn权重并冻结其他时期。 从第11个时代开始,我想改变整个模型。 我怎样才能实现目标?

image-processing machine-learning deep-learning conv-neural-network pytorch
2个回答
5
投票

您可以为每个参数组设置学习速率(以及一些其他元参数)。您只需根据需要对参数进行分组。 例如,为conv层设置不同的学习率:

import torch
import itertools
from torch import nn

conv_params = itertools.chain.from_iterable([m.parameters() for m in model.children()
                                             if isinstance(m, nn.Conv2d)])
other_params = itertools.chain.from_iterable([m.parameters() for m in model.children()
                                              if not isinstance(m, nn.Conv2d)]) 
optimizer = torch.optim.SGD([{'params': other_params},
                             {'params': conv_params, 'lr': 0}],  # set init lr to 0
                            lr=lr_for_model)

您可以稍后访问优化器param_groups并修改学习速率。

有关更多信息,请参阅per-parameter options


0
投票

非常简单,因为PYTORCH在飞行中重新创建计算图。

for p in resnet.parameters():
    p.requires_grad = False # this will freeze the module from training suppose that resnet is one of your module

如果你有多个模块,只需循环它。然后在10个纪元后,你只需打电话

for p in network.parameters():
    p.requires_grad = True # suppose your whole network is the 'network' module
© www.soinside.com 2019 - 2024. All rights reserved.