Skip to content
Advertisement

tensorflow – how to add an if statement?

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

JavaScript

Yet when trying to run this I get:

JavaScript

How to fix this?

EDIT:

JavaScript

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

Advertisement

Answer

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.

Advertisement