Custom loss problem: inputs to eager execution function cannot be keras symbolic tensors but found
If you are encountering the error “inputs to eager execution function cannot be keras symbolic tensors but found” when trying to use a custom loss function in your Keras model, there are a few things you can do to troubleshoot and resolve the issue.
Check for symbolic tensors
One common cause of this error is using symbolic tensors as input to your custom loss function. Symbolic tensors are not compatible with eager execution, which is the default mode of operation in TensorFlow 2.x. Make sure that the input to your custom loss function is not a symbolic tensor, and instead use concrete arrays or tensors.
Use tf.keras.backend functions
If you need to perform tensor operations within your custom loss function, it’s important to use the functions provided by tf.keras.backend rather than directly using the TensorFlow operations. This ensures that the operations are compatible with eager execution and do not result in symbolic tensors.
Explicitly set the execution mode
If you are still encountering the error, you can explicitly set the execution mode to graph by using the following code:
“`html
import tensorflow as tf
tf.compat.v1.disable_eager_execution()
“`
Keep in mind that this will switch the execution mode to graph, which may affect the performance and flexibility of your model.
Consider using the functional API
If none of the above solutions work for your specific case, you may consider using the functional API of Keras to define your custom loss function. This can provide more flexibility and control over the inputs and operations within the loss function.
By following these steps and ensuring that your custom loss function does not operate on symbolic tensors, you can resolve the “inputs to eager execution function cannot be keras symbolic tensors but found” error and continue training your Keras model with a custom loss function.