【问题标题】:An analog of weighted_cross_entropy_with_logits in PyTorchPyTorch 中的 weighted_cross_entropy_with_logits 的模拟
【发布时间】:2018-03-02 12:52:11
【问题描述】:

我正在尝试使用 PyTorch 训练模型。有没有什么简单的方法可以从 Tensorflow 中创建像 weighted_cross_entropy_with_logits 这样的损失?

weighted_cross_entropy_with_logits 中有 pos_weight 参数可以帮助平衡。但是BCEWithLogitsLoss 的参数列表中只有标签的权重。

【问题讨论】:

  • 顺便说一句,我已经实现了pos_weight,并且相应的拉取请求已合并到 PyTorch 0.4.1 中。见the docs

标签: tensorflow machine-learning pytorch


【解决方案1】:

您可以根据需要编写自己的自定义损失函数。例如,你可以写:

def weighted_cross_entropy_with_logits(logits, target, pos_weight):
    return targets * -logits.sigmoid().log() * pos_weight + 
               (1 - targets) * -(1 - logits.sigmoid()).log()

这是一个基本的实现。您应该按照here 中提到的步骤来确保稳定性并避免溢出。只需使用他们得出的最终公式即可。

【讨论】:

  • 但是对于单个数据点,我希望损失是一个标量。例如 True Label: [0,0,0,1,0,1]predicted outputlogits: [0.01, -2.67, -1.03, -3.67, 0.87,-1.11] 对于这个 weighted_cross_entropy_with_logits 应该返回单个损失值吗?
猜你喜欢
  • 2018-09-30
  • 2018-10-09
  • 2017-07-25
  • 2017-07-17
  • 1970-01-01
  • 1970-01-01
  • 2019-09-11
  • 2021-06-19
相关资源
最近更新 更多