3

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.

Gustavo F
  • 45
  • 4
  • 1
    I recommend u to use model.add_loss to use external layers for loss computation: https://stackoverflow.com/a/68275764/10375049 – Marco Cerliani Sep 27 '21 at 07:01

1 Answers1

0

Looks like Issue is with numpy =1.20 version. Downgrade your numpy version to 1.19.5.

W.R.T Keras tensor you can use below sample code

import tensorflow as tf
import numpy as np
np_var = np.array([1])
keras_var = tf.keras.backend.variable(np_var)
def f1(): return tf.multiply(np_var, 17)
def f2(): return tf.add(np_var, 23)
r = tf.cond(tf.less(np_var, np_var), f1, f2)