【问题标题】:How to get weights for custom loss function in pytorch?如何在pytorch中获取自定义损失函数的权重?
【发布时间】:2018-09-23 18:49:33
【问题描述】:

我在 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

【问题讨论】:

    标签: python pytorch loss-function


    【解决方案1】:

    我认为这样的事情可能会奏效:

    我们定义具有layer 作为输入的损失函数。注意torch.norm的输入应该是torch Tensor所以我们需要在层的权重中做.data,因为它是Parameter。然后,我们计算 layer 设置 un p=1 (L1) 的范数。

    def l1_loss(layer):
        return (torch.norm(layer.weight.data, p=1))
    
    lin1 = nn.Linear(8, 64)
    l = l1_loss(lin1)
    

    【讨论】:

      猜你喜欢
      • 2019-05-27
      • 2021-11-13
      • 2020-01-13
      • 1970-01-01
      • 2021-02-20
      • 2021-10-03
      • 2018-09-24
      • 2019-06-25
      • 2020-02-25
      相关资源
      最近更新 更多