【发布时间】: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