I would like to use tf.function
when defining a custom loss function, however, I am receiving an error as:
`
TypeError: To be compatible with tf.eager.defun, Python functions must return zero or more Tensors; in compilation of <function myLoss at 0x000001FDF6C20F70>, found return value of type <class ‘tensorflow.python.eager.def_function.Function’>, which is not a Tensor.
`
Here is a MWE.
import numpy as np
import random
import tensorflow as tf
my_input = np.random.random([5,2])
my_output = np.random.random([5,1])
@tf.function
def loss(y_true ,y_pred, model):
tf.print(model.name)
return tf.keras.losses.mse(y_true, y_pred)
@tf.function
def myLoss(model, y_true):
@tf.function
def my_Loss(y_true,y_pred):
return loss(y_true, y_pred, model)
return my_Loss
my_model = tf.keras.Sequential([
tf.keras.layers.Flatten(input_shape=(my_input.shape[1],)),
tf.keras.layers.Dense(neuron,activation='relu'),
tf.keras.layers.Dense(1)
])
my_model.compile(loss= myLoss( my_model, tf.convert_to_tensor(my_output, dtype = tf.float32)) , optimizer = tf.keras.optimizers.Adam(learning_rate=0.0001))
my_model.fit( tf.convert_to_tensor(my_input, dtype = tf.float32), tf.convert_to_tensor(my_output, dtype = tf.float32), epochs=1, batch_size=5, verbose=2)
How can I convert the method myLoss
into a tensor flow function?