pytorch - 如何将 L2 正则化添加到成本函数 pytorch?
问题描述
我尝试在我的损失函数中添加 L1 和 L2 调整。但我失败了。
我的代码:
criterion = nn.NLLLoss() + nn.L1Loss()
它应该非常适合这样的事情:
criterion = nn.NLLLoss() + _lambda * nn.L1Loss()
我该怎么做?
解决方案
您需要先将它们都实例化,然后再添加它们。他们都期望两个论点:
nll_loss = nn.NLLLoss()
l1_loss = nn.L1Loss()
loss = nll_loss(x, y) + _lambda * l1_loss(x, y)
推荐阅读
- python - TypeError:在 EarlyStopping keras 中使用 restore_best_weights=True 时,类型为“NoneType”的对象没有 len()
- java - 这是将 MVVM 结构与 ViewModel 和 RecyclerView 一起使用而没有任何问题的正确方法吗?
- c++ - 在 SetConsoleTitle() 函数中传递 std::string
- kotlin - Kotlin 中的动态编程风格
- asp.net-mvc - 使用 Where Throws NotSupportedException 测试最小起订量
- javascript - 当 csv 列的名称在 Angular 中包含空格时,有没有办法读取它?
- node.js - 未从 mongo 数据库中获取数据。收到一个空错误。尽管 mongo 云中存在集合
- java - 使用 Gson 反序列化 LocalDate 的问题
- apache-spark - Apache Spark 中的自动批处理
- python - 具有默认属性工厂的 Python 类