TensorFlow 2 自定义损失:“没有为任何变量提供梯度”错误

rtr*_*trt 5 python image-segmentation tensorflow loss-function tensorflow2.0

我有一个图像分割问题,我必须在 TensorFlow 2 中解决。

特别是我有一个由航拍图像与各自的面具配对组成的训练集。在面具中,地形为黑色,建筑物为白色。目的是预测测试集中图像的掩码。

我使用带有最终 Conv2DTranspose 的 UNet,带有 1 个过滤器和一个 sigmoid 激活函数。对最终 sigmoid 层的输出按以下方式进行预测:如果 y_pred>0.5,则为建筑物,否则为背景。

我想实现一个骰子的损失,所以我写了下面的函数

def dice_loss(y_true, y_pred):
    print("[dice_loss] y_pred=",y_pred,"y_true=",y_true)
    y_pred = tf.cast(y_pred > 0.5, tf.float32)
    y_true = tf.cast(y_true, tf.float32)
    numerator = 2 * tf.reduce_sum(y_true * y_pred)
    denominator = tf.reduce_sum(y_true + y_pred)

    return 1 - numerator / denominator
Run Code Online (Sandbox Code Playgroud)

我通过以下方式传递给 TensorFlow:

loss = dice_loss
optimizer = tf.keras.optimizers.Adam(learning_rate=config.learning_rate)
metrics = [my_IoU, 'acc']
model.compile(optimizer=optimizer, loss=loss, metrics=metrics)
Run Code Online (Sandbox Code Playgroud)

但在训练时 TensorFlow 抛出以下错误:

ValueError:没有为任何变量提供梯度:

thu*_*v89 5

问题在于您的损失函数(显然)。具体操作如下。

y_pred = tf.cast(y_pred > 0.5, tf.float32)

这不是可微分操作。这导致梯度为无。将您的损失函数更改为以下内容,它将起作用。

def dice_loss(y_true, y_pred):
    print("[dice_loss] y_pred=",y_pred,"y_true=",y_true)
    y_true = tf.cast(y_true, tf.float32)
    numerator = 2 * tf.reduce_sum(y_true * y_pred)
    denominator = tf.reduce_sum(y_true + y_pred)

    return 1 - numerator / denominator
Run Code Online (Sandbox Code Playgroud)