首页 > 解决方案 > 我的损失自定义函数是否像我认为的那样做?

问题描述

我有一个带有自定义损失函数的 Keras 模型(如下所示)。预期的行为是,当地面实况的第一个数字(第 4 等级)为正时,网络应尝试逼近所有 8 个参数。否则,它应该只尝试近似第一个参数(并为其他参数输出任何内容)。换句话说,当真集的第一个参数为 0 或负数时,其余参数无关紧要。我做对了吗?我可以使用这样的 tf slice 吗?

我注意到参数 1-7 普遍比我预期的更接近 0。好像该功能只是到处做 MSE。

def custom_loss(y_true, y_pred):
    truthiness = tf.greater(y_true[:, :, :, 0], tf.constant(0.0))

    loss = tf.where(
        truthiness,
        tf.keras.losses.MeanSquaredError()(y_true[:, :, :, 0:8], y_pred[:, :, :, 0:8]),
        tf.keras.losses.MeanSquaredError()(y_true[:, :, :, 0], y_pred[:, :, :, 0]),
    )

    return loss

标签: tensorflowkeras

解决方案


答案似乎是 Keras.losses.MeanSquaredError 中的一些意外(至少对我而言)行为。我最终只是在普通的张量流中实现了我的损失。

truthiness = tf.cast(tf.greater(y_true[:, :, :, 0], tf.constant(0.0)), dtype=tf.float32)
falsyness = tf.cast(tf.less_equal(y_true[:, :, :, 0], tf.constant(0.0)), dtype=tf.float32)

loss = tf.reduce_sum(tf.square(y_true[:, :, :, 0] - y_pred[:, :, :, 0])) + \
        tf.multiply(
           truthiness,
           tf.reduce_sum(tf.square(y_true[:, :, :, 1:8] - y_pred[:, :, :, 1:8])),
        )

loss_2 = tf.multiply(truthiness, tf.keras.losses.MeanSquaredError()(y_true[:, :, :, 0:8], y_pred[:, :, :, 0:8])) + \
        tf.multiply(falsyness, tf.keras.losses.MeanSquaredError()(y_true[:, :, :, 0], y_pred[:, :, :, 0]))

我希望 loss 和 loss_2 是等价的,但事实并非如此。重新发明轮子 FTW!


推荐阅读