Pytorch知识点

291 阅读1分钟

如何冻结参数

参考链接:blog.csdn.net/weixin_4299…

方法一: requires_grad = False

for p in net.XXX.parameters(): 
    p.requires_grad = False

方法二: With torch.no_grad()

class xxnet(nn.Module):
    def __init__():
        ....
        self.layer1 = xx
        self.layer2 = xx
        self.fc = xx

    def forward(self.x):
        with torch.no_grad():
            x = self.layer1(x)
            x = self.layer2(x)
        x = self.fc(x)
        return x

如何调整某些层的学习率

参考链接:zhuanlan.zhihu.com/p/59780798

使用filter从parameters中取出自己要的参数 在优化器中指定不同参数的学习率

例子:

ignored_params = list(map(id, net.fc3.parameters())) # 返回的是parameters的 内存地址
base_params = filter(lambda p: id(p) not in ignored_params, net.parameters()) 
optimizer = optim.SGD([
{'params': base_params},
{'params': net.fc3.parameters(), 'lr': 0.001*10}], 0.001, momentum=0.9, weight_decay=1e-4)

想起来再补充