zoukankan      html  css  js  c++  java
  • Pytorch固定部分参数(只训练部分层)

    在迁移学习中我们经常会用到预训练模型,并在预训练模型的基础上添加额外层。训练时先将预训练层参数固定,只训练额外添加的部分。完了之后再全部训练微调。

    在pytorch 固定部分参数训练时需要在优化器中施加过滤。

    需要自己过滤

    optimizer.SGD(filter(lambda p: p.requires_grad, model.parameters()), lr=1e-3)

    另外,如果是Variable,则可以初始化时指定

    j = Variable(torch.randn(5,5), requires_grad=True)

    但是如果是(神经网络层)

    m = nn.Linear(10,10)

    是没有requires_grad传入的,m.requires_grad也没有,需要

    for i in m.parameters():
        i.requires_grad=False

    另外一个小技巧就是在nn.Module里,可以在中间插入这个

    for p in self.parameters():
        p.requires_grad=False

    这样前面的参数就是False,而后面的不变

    class Net(nn.Module):
        def __init__(self):
            super(Net, self).__init__()
            self.conv1 = nn.Conv2d(1, 6, 5)
            self.conv2 = nn.Conv2d(6, 16, 5)
    
            for p in self.parameters():
                p.requires_grad=False
    
            self.fc1 = nn.Linear(16 * 5 * 5, 120)
            self.fc2 = nn.Linear(120, 84)
            self.fc3 = nn.Linear(84, 10)
     1 class RESNET_attention(nn.Module):
     2     def __init__(self, model, pretrained):
     3         super(RESNET_attetnion, self).__init__()
     4         self.resnet = model(pretrained)
     5         for p in self.parameters():
     6             p.requires_grad = False
     7         self.f = nn.Conv2d(2048, 512, 1)
     8         self.g = nn.Conv2d(2048, 512, 1)
     9         self.h = nn.Conv2d(2048, 2048, 1)
    10         self.softmax = nn.Softmax(-1)
    11         self.gamma = nn.Parameter(torch.FloatTensor([0.0]))
    12         self.avgpool = nn.AvgPool2d(7, stride=1)
    13         self.resnet.fc = nn.Linear(2048, 10)

    note:以上代码复现SAGAN的Attention部分,这不是主要问题

    这样就将for循环以上的参数固定, 只训练下面的参数(f,g,h,gamma,fc,等), 但是注意需要在optimizer中添加上这样的一句话filter(lambda p: p.requires_grad, model.parameters()
    添加的位置为:
    optimizer = optim.Adam(filter(lambda p: p.requires_grad, model.parameters()), lr=0.0001, betas=(0.9, 0.999), eps=1e-08, weight_decay=1e-5)


    原文:

    [1] https://blog.csdn.net/guotong1988/article/details/79739775

    [2] https://blog.csdn.net/weixin_34261739/article/details/87555871 

  • 相关阅读:
    LCPhash求解
    BSGS
    洛谷—— P1849 [USACO12MAR]拖拉机Tractor
    BZOJ——2101: [Usaco2010 Dec]Treasure Chest 藏宝箱
    洛谷—— P1561 [USACO12JAN]爬山Mountain Climbing
    BZOJ——1601: [Usaco2008 Oct]灌水
    洛谷—— P1342 请柬
    [SDOI2009]Elaxia的路线 SPFA+Topo
    1737 配对
    51Nod 1378 夹克老爷的愤怒
  • 原文地址:https://www.cnblogs.com/jiangkejie/p/11199847.html
Copyright © 2011-2022 走看看