I need to convert a KerasTensor to a Tensor because when I try to use a contional (tf.cond()
) it reports an error:
def custon_loss(self, input_tensor): # input type = <class 'tensorflow.python.keras.engine.keras_tensor.KerasTensor'>
def loss(y_actual, y_predicted):
mse = K.mean(K.sum(K.square(y_actual - y_predicted)))
mse = tf.reshape(mse, [1, 1])
y_actual = keras.layers.core.Reshape([1, 1])(y_actual)[0]
ax_input = tf.reshape(input_tensor[0][-1:][0][:1], [1, 1])
# convert here ax_input to Tensor
greater_equal = tf.reshape(tf.math.logical_and(tf.math.greater_equal(ax_input, y_actual), tf.math.greater_equal(ax_input, y_predicted))[0], [1, 1])
less_equal = tf.reshape(tf.math.logical_and(tf.math.less_equal(ax_input, y_actual), tf.math.less_equal(ax_input, y_predicted))[0], [1, 1])
logical_or = tf.reshape(tf.math.logical_or(greater_equal, less_equal)[0], [1, 1])
return tf.cond(logical_or, lambda: mse, lambda: tf.math.multiply(mse, 10))
return loss
Error caused in tf.cond
:
TypeError: Cannot convert a symbolic Keras input/output to a numpy array. This error may indicate that you're trying to pass a symbolic value to a NumPy call, which is not supported. Or, you may be trying to pass Keras symbolic inputs/outputs to a TF API that does not register dispatching, preventing Keras from automatically converting the API call to a lambda layer in the Functional Model.
I believe that converting the tensor will not make the error.