How to design a custom loss function to add two loss

I am using CNN to solve a regression problem in a supervised manner. i have input data(X_train) and the target data(y_train). I allow the network to train and during training process in each batch of the corresponding epoch I extracted the predicted data using callbacks. And the extracted predicted data is used to recreate the input data through a numerical simulation and it gives results interms of numpy array. Now I want to compute the loss between predicted data(y_predict) and target(y_true) data and the loss between recreated input data(X_train’) and original input data(X_train) and finally i want to add these two loss functions. Important thing is that simultaneously network is doing two things.

I looked into this Keras custom loss function: Accessing current input pattern but not getting idea on how to proceed.

Hope experts may provide the solution with small example. Thanks in advance.

Hi @titu_kumar, you can define a custom loss function to add two losses as show in the example below.

def custom_loss_function(y_true, y_pred,X_train,X_generated):
   loss1=tf.keras.metrics.mean_squared_error(y_true, y_pred)
   loss2=tf.keras.metrics.mean_absolute_error(X_train, X_generated)
   return loss1+loss2

Thank You.

@Kiran_Sai_Ramineni Do u think, by using loss2 will update the gradients.I am in doubt as X_generated is not defined inside the model.