首页 > 解决方案 > Keras中带有掩码矩阵的自定义损失

问题描述

我正在尝试在 Keras 中使用我自己的损失函数。特别是,作为 y_pred 预测向量和 y_true 真实向量,我想要:

y_pred[i] = y_pred[i] if y_true[i] != 0
y_pred[i] = 0 if y_true[i] == 0

所以我尝试了以下方法:

def myloss(y_true, y_pred):
        mask = K.not_equal(y_true, 0)
        mask = K.cast(mask, dtype = 'float32')
        loss_value = K.mean(K.square(mask*y_pred - y_true), axis = 1)
        return loss_value

但我收到此错误:

TypeError:传递给参数“x”的值的 DataType bool 不在允许值列表中:bfloat16、float16、float32、float64、uint8、int8、uint16、int16、int32、int64、complex64、complex128

有人知道如何帮助我吗?

标签: pythontensorflowkerasloss-function

解决方案


您可以尝试使用tf.boolean_mask

def myloss(y_true, y_pred):
        mask = K.not_equal(y_true, 0)
        pred_masked = tf.boolean_mask(y_pred - y_true, mask)
        loss_value = K.mean(K.square(pred_masked), axis = 1)
        return loss_value

推荐阅读