tensorflow – how to add an if statement?

0

Issue

This is a simplified version of what I am trying to do:

result = sess.run(cost, feed_dict={X: np.matrix(np.array(values[0][1]))})

if result > Z:
    print('A')
else:
    print('B')

Yet when trying to run this I get:

if result > Z:
  File "/home/John/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 578, in __nonzero__
    raise TypeError("Using a `tf.Tensor` as a Python `bool` is not allowed. "
TypeError: Using a `tf.Tensor` as a Python `bool` is not allowed. Use `if t is not None:` instead of `if t:` to test if a tensor is defined, and use TensorFlow ops such as tf.cond to execute subgraphs conditioned on the value of a tensor.

How to fix this?

EDIT:

def getCertitude1(result):
    return (Z/result)*100

def getCertitude2(result):
    return (result/Z)*100

result = sess.run(cost, feed_dict={X: np.matrix(np.array(reps[0][1]))})

if result is not None:
    a = tf.cond(tf.less(result, Z), lambda: getCertitude1(result), lambda: getCertitude2(result))     
    print("a: " + str(a))                   

results in a: : Tensor("cond/Merge:0", shape=(?, 128), dtype=float32)

Solution

objects can’t be used with regular python objects and functions. That’s how tensorflow is designed. if/else blocks, for, while and other python stuff should be replaced with appropriate tensorflow operations like tf.while_loop, tf.cond and so on. These operations operate with tensors which are the main tensorflow objects, and could not be used with python objects.

The only way to get a python object from tensor is to call tf.Session object on this object. Thus, when you are calling sess.run() you get python object (more precisely, numpy one). Apparently, Z is a tf.Tensor, and it shouldn’t be mixed with python object result.

You could either evaluate Z with another sess.run() and then switch to regular python operations, or properly use tf.cond and create a subgraph based on the values of cost and Z which are both tensors.

Answered By – Dmitriy Danevskiy

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More