1

我需要添加一个 L1 范数作为正则化器,以在我的神经网络中创建一个稀疏条件。我想训练我的网络进行分类。我试图自己构建一个 L1 规范,就像这里一样,但它没有奏效。

我需要在 之后添加正则化器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
4

2 回答 2

1

你多虑了。正如我从您的 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-10-19T19:27:42.423 回答
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))
于 2017-10-20T14:31:52.157 回答