【发布时间】:2019-09-05 02:43:46
【问题描述】:
如何在 keras 中实现 BCEWithLogitsLoss 并将其用作自定义损失函数,同时使用 Tensorflow 作为后端。
我在PyTorch 中使用了BCEWithLogitsLoss,它在torch 中定义。
如何在 Keras 中实现相同的功能。?
【问题讨论】:
标签: python keras deep-learning loss-function
如何在 keras 中实现 BCEWithLogitsLoss 并将其用作自定义损失函数,同时使用 Tensorflow 作为后端。
我在PyTorch 中使用了BCEWithLogitsLoss,它在torch 中定义。
如何在 Keras 中实现相同的功能。?
【问题讨论】:
标签: python keras deep-learning loss-function
在 TensorFlow 中,您可以直接调用 tf.nn.sigmoid_cross_entropy_with_logits,它在 TensorFlow 1.x 和 2.0 中都可以使用。
如果您想坚持使用 Keras API,请使用 tf.losses.BinaryCrossentropy 并在构造函数调用中设置 from_logits=True。
与 PyTorch 不同,API 中没有明确的每个示例权重。您可以改为将reduction=tf.keras.losses.Reduction.NONE 设置为损失,通过显式乘法进行加权,并使用tf.reduce_mean 减少损失。
xent = tf.losses.BinaryCrossEntropy(
from_logits=True,
reduction=tf.keras.losses.Reduction.NONE)
loss = tf.reduce_mean(xent(targets, pred) * weights))
【讨论】:
def custom_loss(data, targets): bce_loss_1 = nn.BCEWithLogitsLoss(weight=targets[:,1:2])(data[:,:1],targets[:,:1]) bce_loss_2 = nn.BCEWithLogitsLoss()(data[:,1:],targets[:,2:]) return (bce_loss_1 * loss_weight) + bce_loss_2
reduction='NONE',这样损失不会在批次中求和或平均,应用您的权重并使用tf.reduce_mean 显式减少每个示例的损失。
xent = tf.losses.BinaryCrossEntropy(from_logits=True, reduction='NONE'); def custom_loss(data, targets, weights): return tf.reduce_mean(xent(targets[:,:1], data[:,:1]) * weights) + tf.reduce_mean(targets[:,2:], xent(data[:,1:]))
ValueError 和Invalid Reduction Key NONE