gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 07:35:00 29 4
gpt4 key购买 nike

我在 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 因为它是一个 参数。然后,我们计算 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)

关于python - 如何在pytorch中获取自定义损失函数的权重?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49816503/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com