首页 > 解决方案 > 如何将 L2 正则化添加到成本函数 pytorch?

问题描述

我尝试在我的损失函数中添加 L1 和 L2 调整。但我失败了。

我的代码:

criterion = nn.NLLLoss() + nn.L1Loss()

它应该非常适合这样的事情:

criterion = nn.NLLLoss() + _lambda * nn.L1Loss()

我该怎么做?

标签: pytorch

解决方案


您需要先将它们都实例化,然后再添加它们。他们都期望两个论点:


nll_loss = nn.NLLLoss()
l1_loss = nn.L1Loss()
loss = nll_loss(x, y) + _lambda * l1_loss(x, y) 

推荐阅读