这在PyTorch的文档中提供。看看http://pytorch.org/docs/optim.html#torch.optim.Adagrad 。您可以使用权重衰减参数将L2损失添加到“优化”函数中。

在PyTorch中添加L1 / L2正则化?

共 4 个回答
高赞
时间
活跃
0

0

以下应该有助于L2正则化:
optimizer = torch.optim.Adam(model.parameters(), lr=1e-4, weight_decay=1e-5)
0

与直接方法相比,有趣的torch.norm
在CPU上更慢,在GPU上更快。
import torch
x = torch.randn(1024,100)
y = torch.randn(1024,100)
%timeit torch.sqrt((x - y).pow(2).sum(1))
%timeit torch.norm(x - y, 2, 1)
出:
1000 loops, best of 3: 910 µs per loop
1000 loops, best of 3: 1.76 ms per loop
另一方面:
import torch
x = torch.randn(1024,100).cuda()
y = torch.randn(1024,100).cuda()
%timeit torch.sqrt((x - y).pow(2).sum(1))
%timeit torch.norm(x - y, 2, 1)
出:
10000 loops, best of 3: 50 µs per loop
10000 loops, best of 3: 26 µs per loop
0

对于L2正则化,
lambda = torch.tensor(1.)
l2_reg = torch.tensor(0.)
for param in model.parameters():
l2_reg += torch.norm(param)
loss += lambda * l2_reg
参考文献:
新手导航
- 社区规范
- 提出问题
- 进行投票
- 个人资料
- 优化问题
- 回答问题
0
有什么办法可以在PyTorch中添加简单的L1 / L2正则化吗?我们可以通过简单地将
data_loss
与reg_loss
相加来计算正则损失,但是有没有任何明确的方法,PyTorch库提供的任何支持可以更轻松地完成它,而无需手动进行?