[英]How to get weights for custom loss function in pytorch?
我在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
我认为这样可以工作:
我们定义了将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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.