PyTorch 中 weighted_cross_entropy_with_logits 的模拟
An analog of weighted_cross_entropy_with_logits in PyTorch
我正在尝试使用 PyTorch 训练模型。有什么简单的方法可以从 Tensorflow 中创建像 weighted_cross_entropy_with_logits
这样的损失吗?
weighted_cross_entropy_with_logits
中有 pos_weight
个参数可以帮助平衡。但是 BCEWithLogitsLoss
.
中的参数列表中只有标签的权重
您可以根据需要编写自己的自定义损失函数。例如,你可以这样写:
def weighted_cross_entropy_with_logits(logits, target, pos_weight):
return targets * -logits.sigmoid().log() * pos_weight +
(1 - targets) * -(1 - logits.sigmoid()).log()
这是一个基本的实现。您应该按照 here 中提到的步骤来确保稳定性并避免溢出。只需使用他们得出的最终公式即可。
我正在尝试使用 PyTorch 训练模型。有什么简单的方法可以从 Tensorflow 中创建像 weighted_cross_entropy_with_logits
这样的损失吗?
weighted_cross_entropy_with_logits
中有 pos_weight
个参数可以帮助平衡。但是 BCEWithLogitsLoss
.
您可以根据需要编写自己的自定义损失函数。例如,你可以这样写:
def weighted_cross_entropy_with_logits(logits, target, pos_weight):
return targets * -logits.sigmoid().log() * pos_weight +
(1 - targets) * -(1 - logits.sigmoid()).log()
这是一个基本的实现。您应该按照 here 中提到的步骤来确保稳定性并避免溢出。只需使用他们得出的最终公式即可。