The function for tensor value generates this Error: 'false_fn' must be callable

Question:

I am creating a function that takes a tensor value and returns the result by applying the following formulation, There are 3 conditions so I am using @tf.functions.

def Spa(x):
    x= tf.convert_to_tensor(float(x), dtype=tf.float32)
    p= tf.convert_to_tensor(float(0.05), dtype=tf.float32)
    
    p_dash=x
    K = p*logp_dash
    Ku=K.sum(Ku)
    
    Ku= tf.convert_to_tensor(float(Ku), dtype=tf.float32)
    

    y= tf.convert_to_tensor(float(0), dtype=tf.float32)
    def a(): return tf.constant(0)

    r = tf.case([(tf.less(x, y), a), (tf.greater(x, Ku), a)], default=x, exclusive=False)
    return r

The code generates the following error:
‘false_fn’ must be callable.
I did many conversions, int to float and float to int but don’t know what is the issue.

Asked By: p200401Samuel

||

Answers:

In tf.case x should be a function not a tensor. As described in TF page.

def f1(): return tf.constant(17)
def f2(): return tf.constant(23)
def f3(): return tf.constant(-1)
r = tf.case([(tf.less(x, y), f1), (tf.greater(x, z), f2)], default=f3, exclusive=True)

You can see that f3 here is also a function.

Answered By: Deketh

It should be something like this.

x = tf.where(x < 0, tf.zeros_like(x), x)
p = 0.05
p_hat = x
KL_divergence = p * (tf.math.log(p / p_hat)) + (1 - p) * (tf.math.log(1 - p / 1 - p_hat))
x = tf.where(x < KL_divergence, tf.zeros_like(x), x)
return x
Answered By: user3768070