【问题标题】:Custom loss function in Keras/Tensorflow with if statement带有 if 语句的 Keras/Tensorflow 中的自定义损失函数
【发布时间】:2018-07-12 18:12:56
【问题描述】:

我需要在 Keras 中创建一个自定义损失函数,并根据条件返回两个不同的损失值的结果。我无法让 if 语句正常运行。

我需要做类似的事情:

def custom_loss(y_true, y_pred):
    sees = tf.Session()
    const = 2
    if (sees.run(tf.keras.backend.less(y_pred, y_true))): #i.e. y_pred - y_true < 0
        return const * mean_squared_error(y_true, y_pred)
    else:
        return mean_squared_error(y_true, y_pred)

尝试运行此程序时,我不断收到张量错误(见下文)。任何帮助/建议将不胜感激!

InvalidArgumentError: You must feed a value for placeholder tensor 'dense_63_target' with dtype float and shape [?,?]
 [[Node: dense_63_target = Placeholder[dtype=DT_FLOAT, shape=[?,?], _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]

【问题讨论】:

  • 顺便说一句,我已经编辑了我的答案,以包含超出您要求的建议。

标签: python tensorflow machine-learning keras


【解决方案1】:

你应该简单地乘以一个掩码以获得你想要的功能

import keras.backend as K
def custom_1loss(y_true, y_pred):
    const = 2
    mask = K.less(y_pred, y_true) #i.e. y_pred - y_true < 0
    return (const - 1) * mask * mean_squared_error(y_true, y_pred) + mean_squared_error(y_true, y_pred)

y_pred 是一个预测不足时,它具有相同的期望输出,另一个MSE 术语被添加。您可能必须将掩码转换为整数张量 - 我不记得具体是什么类型 - 但这是一个小改动。

通常也作为对您的方法的不请自来的建议。我认为使用不同的损失方法可以获得更好的结果。

import keras.backend as K
def custom_loss2(y_true, y_pred):
    beta = 0.1
    return mean_squared_error(y_true, y_pred) + beta*K.mean(y_true - y_pred)

观察渐变行为的差异:

https://www.desmos.com/calculator/uubwgdhpi6

我向您展示的第二个损失函数将局部最小值的时刻转变为轻微的过度预测而不是预测不足(基于您想要的)。您给出的损失函数仍然局部优化为 0,但具有不同的强度梯度。这很可能会导致与 MSE 相同结果的收敛速度较慢,而不是需要一个宁愿过度预测而不是预测不足的模型。我希望这是有道理的。

【讨论】:

    猜你喜欢
    • 2021-09-26
    • 2018-10-28
    • 2017-12-29
    • 2017-12-01
    • 2017-04-21
    • 2020-10-21
    • 1970-01-01
    • 2020-10-05
    • 2019-06-06
    相关资源
    最近更新 更多