【问题标题】:Handling and Combining two loss function in Keras TF在 Keras TF 中处理和组合两个损失函数
【发布时间】:2023-04-03 12:01:01
【问题描述】:

有没有办法在 Keras 中有两个损失函数,其中第二个损失函数从第一个损失函数中获取输出?

我正在使用 Keras 开发神经网络,我想在 model.compile() 中的 Loss 项中添加另一个自定义函数以对其进行正则化并以某种方式对其进行惩罚,其形式如下:

model.compile(loss_1='mean_squared_error', optimizer=Adam(lr=learning_rate), metrics=['mae'])

我想添加另一个损失函数作为来自 Loss_1 输出的预测值的总和,以便我可以告诉神经网络最小化来自 Loss_1 模型的预测值的总和。我该怎么做(loss_2)?

类似:

model.compile(loss_1='mean_squared_error', loss_2= np.sum(****PREDICTED_OUTPUT_FROM_LOSS_FUNCTION_1****), optimizer=Adam(lr=learning_rate), metrics=['mae'])

如何实现?

【问题讨论】:

    标签: python tensorflow machine-learning keras deep-learning


    【解决方案1】:

    你应该定义一个自定义的损失函数

    def custom_loss_function(y_true, y_pred):
       squared_difference = tf.square(y_true - y_pred)
       absolute_difference = tf.abs(y_true - y_pred)
       
       loss = tf.reduce_mean(squared_difference, axis=-1) + tf.reduce_mean(absolute_difference, axis=-1)
    
       return loss
    
    model.compile(optimizer='adam', loss=custom_loss_function)
    

    我相信这会解决你的问题

    【讨论】:

    • 它如何知道 y_true 和 y_pred 是什么?是否应该在此步骤之前定义它们,因为我还没有 y_pred
    • 它们只是“custom_loss_function”函数的参数。 model.fit() 会为你处理剩下的事情......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-11
    • 1970-01-01
    • 1970-01-01
    • 2021-04-26
    • 2019-01-13
    • 2018-11-12
    • 2019-06-01
    相关资源
    最近更新 更多