简体   繁体   English

在张量流中,如何将多个损失与所需的公式结合起来

[英]In tensorflow, how to combine multiple losses with a desired formula

I have a CNN model with a single output neuron consisting of sigmoid activation, hence its value is in between 0 and 1. I wanted to calculate a combination of loss for this particular output neuron.我有一个 CNN 模型,它有一个由 sigmoid 激活组成的输出神经元,因此它的值在 0 和 1 之间。我想计算这个特定输出神经元的损失组合。

I was using Mean Absolute Error and Mean Squared Error for the same, and creating a loss like this:我同样使用了平均绝对误差和均方误差,并产生了这样的损失:

loss = tf.keras.losses.MeanAbsoluteError() + tf.keras.losses.MeanSquaredError()

Now, due to some issue, the tensorflow framework is not supporting loss function like this.现在,由于某些问题,tensorflow 框架不支持这样的损失函数。 Here is the error:这是错误:

Traceback (most recent call last):
  File "run_kfold.py", line 189, in <module>
    loss = tf.keras.losses.MeanAbsoluteError() + tf.keras.losses.MeanSquaredError()
TypeError: unsupported operand type(s) for +: 'MeanAbsoluteError' and 'MeanSquaredError'

Can anyone suggest how to calculate combo loss for a certain output layer.谁能建议如何计算某个输出层的组合损失。 This will help to create multiple weighted losses in combination, like this:这将有助于组合创建多个加权损失,如下所示:

l_1 = 0.6
l_2 = 0.4
loss = l_1 * tf.keras.losses.MeanAbsoluteError() + l_2 *tf.keras.losses.MeanSquaredError()

I can then pass this loss variable to the model.compile() function然后我可以将此损失变量传递给model.compile()函数

model.compile(optimizer=opt, 
                  loss=loss,
                  metrics = ['accuracy', sensitivity, specificity, tf.keras.metrics.RootMeanSquaredError(name='rmse')]
                )

You can write a function and use MeanAbsoluteError() and MeanSquaredError() and compute custom_loss and return it:您可以编写一个函数并使用MeanAbsoluteError()MeanSquaredError()并计算 custom_loss 并返回它:

import tensorflow as tf

# model = your_model
...

def custom_loss(y_true, y_pred):
    l_1 = 0.6
    l_2 = 0.4
    mae = tf.keras.losses.MeanAbsoluteError()
    mse = tf.keras.losses.MeanAbsoluteError()
    loss_mae = mae(y_true , y_pred)
    loss_mse = mse(y_true , y_pred)
    total_loss = l_1*loss_mae + l_2*loss_mse
    return total_loss


model.compile(loss=custom_loss, 
              optimizer='Adam')

model.fit(x_train, y_train, batch_size=BATCH_SIZE, epochs=EPOCHS)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM