如何在pytorch中获取自定义损失函数的权重?

3

我有一个在pytorch中的模型,想在loss_function中添加L1正则化。但是我不想将权重传递给loss_function() - 有更好的方法吗?具体请参见下面的loss_function()。

class AutoEncoder(nn.Module):
    def __init__(self, inp_size, hid_size):
        super(AutoEncoder, self).__init__(

        self.lambd = 1. 

        # Encoder
        self.e1 = nn.Linear(inp_size, hid_size)

        # Decoder
        self.d1 = nn.Linear(hid_size, inp_size)
        self.sigmoid = nn.Sigmoid()    

        pass

   def forward(self,x):
       encode = self.e1(x)
       decode = self.sigmoid(self.d1(encode))
       return decode

   def loss_function(self, recon_x, x):
       l2_loss = nn.MSELoss()

       # Here I would like to compute the L1 regularization of the weight parameters
       loss = l2_loss(recon_x, x) + self.lambd(l1_loss(self.e1) + l1_loss(self.e2))
       return loss
1个回答

0

我认为这样做可能有效:

我们定义损失函数,其中一个作为输入。请注意,torch.norm的输入应该是torch Tensor,因此我们需要在层的权重中进行.data,因为它是一个Parameter。然后,我们计算layer的范数,将p=1(L1)设置为不变。

def l1_loss(layer):
    return (torch.norm(layer.weight.data, p=1))

lin1 = nn.Linear(8, 64)
l = l1_loss(lin1)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接