【问题标题】:L1 norm as regularizer in PytorchL1 范数作为 Pytorch 中的正则化器
【发布时间】:2018-03-29 14:32:58
【问题描述】:

我需要添加一个 L1 范数作为正则化器,以在我的神经网络中创建一个稀疏条件。我想训练我的网络进行分类。我尝试自己构建一个 L1 范数,比如 here,但没有成功。

我需要在ConvTranspose2d 之后添加正则化器,类似于这个 Keras 示例:

model.add(Dense(64, input_dim=64,
            kernel_regularizer=regularizers.l2(0.01),
            activity_regularizer=regularizers.l1(0.01)))

但我的网络是在 PyTorch 中创建的,如下所示:

upconv = nn.ConvTranspose2d(inner_nc, outer_nc,
                            kernel_size=4, stride=2,
                            padding=1, bias=use_bias)
down = [downrelu, downconv]
up = [uprelu, upconv, upnorm]
model = down + up

【问题讨论】:

    标签: keras torch pytorch regularized


    【解决方案1】:

    在 pytorch 中,您可以执行以下操作(假设您的网络名为 net):

    def l1_loss(x):
        return torch.abs(x).sum()
    
    to_regularise = []
    for param in net.parameters():
        to_regularise.append(param.view(-1))
    l1 = l1_weight*l1_loss(torch.cat(to_regularise))
    

    【讨论】:

      【解决方案2】:

      你想多了。正如我从您的 Keras 代码中看到的那样,您正试图对层的激活施加 L1 惩罚。最简单的方法就是执行以下操作:

      activations_to_regularise = upconv(input)
      output = remaining_netowrk(activations_to_regularise)
      

      然后使用您的正常损失函数来评估针对目标的输出,并将 L1 损失合并到目标中,这样您就可以得到

      total_loss = criterion(output, target) + 0.01 * activations_to_regularise.abs()
      

      【讨论】:

        猜你喜欢
        • 2017-07-30
        • 2020-06-29
        • 2017-11-22
        • 2017-08-26
        • 2021-05-05
        • 2018-10-07
        • 1970-01-01
        • 2020-01-30
        • 2015-06-30
        相关资源
        最近更新 更多