Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tensorflow error: Using a `tf.Tensor` as a Python `bool` is not allowed

I am struggling to implement an activation function in tensorflow in Python.

The code is the following:

def myfunc(x):
    if (x > 0):
        return 1
    return 0

But I am always getting the error:

Using a tf.Tensor as a Python bool is not allowed. Use if t is not None:

like image 390
Lilo Avatar asked Feb 01 '18 20:02

Lilo


2 Answers

Use tf.cond:

tf.cond(tf.greater(x, 0), lambda: 1, lambda: 0)

Another solution, which in addition supports multi-dimensional tensors:

tf.sign(tf.maximum(x, 0))

Note, however, that the gradient of this activation is zero everywhere, so the neural network won't learn anything with it.

like image 118
Maxim Avatar answered Nov 10 '22 20:11

Maxim


In TF2, you could just decorate the function myfunc() with @tf.function:

@tf.function
def myfunc(x):
    if (x > 0):
        return 1
    return 0
like image 2
Ayush Garg Avatar answered Nov 10 '22 21:11

Ayush Garg