【问题标题】:BCEWithLogitsLoss in KerasKeras 中的 BCEWithLogitsLoss
【发布时间】:2019-09-05 02:43:46
【问题描述】:

如何在 keras 中实现 BCEWithLogitsLoss 并将其用作自定义损失函数,同时使用 Tensorflow 作为后端。

我在PyTorch 中使用了BCEWithLogitsLoss,它在torch 中定义。

如何在 Keras 中实现相同的功能。?

【问题讨论】:

    标签: python keras deep-learning loss-function


    【解决方案1】:

    在 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
    • Keras 损失没有像 PyTorch 那样明确的权重。您可以在损失构造中设置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:]))
    • 我收到了ValueErrorInvalid Reduction Key NONE
    猜你喜欢
    • 2020-04-27
    • 2021-06-14
    • 1970-01-01
    • 1970-01-01
    • 2019-11-23
    • 2022-07-29
    • 2020-10-20
    • 2021-03-08
    • 1970-01-01
    相关资源
    最近更新 更多