语义切分中的损失定义问题

2024-05-07 23:58:58 发布

您现在位置:Python中文网/ 问答频道 /正文

def loss(y_true, y_pred):
    BG_label = 0.
    FG_label = 1.
    y_pred = K.reshape(y_pred, [-1])
    y_true = K.reshape(y_true, [-1])

    #if GT_VALUE == 0
    idx_0 = tf.where(tf.equal(y_true, tf.constant(BG_label, dtype=tf.float32)))
    y_pred_0 = tf.gather_nd(y_pred, idx_0) 
    y_true_0 = tf.gather_nd(y_true, idx_0)
    loss_0 = K.mean(K.binary_crossentropy(y_true_0, y_pred_0), axis=-1)

    #if GT_VALUE == 1
    idx_1 = tf.where(tf.equal(y_true, tf.constant(FG_label, dtype=tf.float32)))
    y_pred_1 = tf.gather_nd(y_pred, idx_1) 
    y_true_1 = tf.gather_nd(y_true, idx_1)
    loss_1 = K.mean(K.binary_crossentropy(y_true_1, y_pred_1), axis=-1)

    loss_all = tf.add(loss_1, loss_0)

    return loss_all

我在语义切分中有丢失定义问题

如果gt_图像中没有值为1的像素,则输出形式为idx_1 = [](空)

那么我就有问题了loss_1 = nan->;还有loss_all = nan

如果idx_1不存在,我想用loss_0替换loss_all

我曾经

if idx_1 is not None: 
   y_pred_1 = tf.gather_nd(y_pred, idx_1) 
   y_true_1 = tf.gather_nd(y_true, idx_1)
   loss_1 = K.mean(K.binary_crossentropy(y_true_1, y_pred_1), axis=-1)
   loss_all = tf.add(loss_1,loss_0)
else:
   loss_all = loss_0

但它似乎不起作用

还有别的解决办法吗

我需要 if(len(idx_1) > 0): 但我不知道如何在Tensorflow中实现这一点


Tags: trueiftfallmeanlabelbgbinary