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_image中没有像素值为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中实现这一点。