Mencia
Mencia

Reputation: 898

Tensorflow: tf.while_loop() with vector condition

The function tf.while_loop() (https://www.tensorflow.org/api_docs/python/tf/while_loop) repeats the body "b" while the condition "c" is true. For example:

import tensorflow as tf    
i = tf.constant(0)
c = lambda i: tf.greater(10,i)
b = lambda i: tf.add(i, 1)
r = tf.while_loop(c, b, [i])

How can I adjust this, when the condition is a vector, e.g.

c = lambda i: tf.greater([10,10],[i,i])

?

The problem is that the above returns a vector (instead of True or False), same as e.g.

tf.greater([2,2],[1,1])

I need something that returns true when all the vector elements are true, and false otherwise. I would suggest

i = tf.constant(0)
c = lambda i: True if all(item == True for item in tf.greater([10,10],[i,i]))==True else False
b = lambda i: tf.add(i, 1)
r = tf.while_loop(c, b, [i])

But this does not work, with the following error:

TypeError: `Tensor` objects are not iterable when eager execution is not enabled. To iterate over this tensor use `tf.map_fn`.

Any ideas?

Upvotes: 1

Views: 218

Answers (1)

Mencia
Mencia

Reputation: 898

The solution is to use tf.reduce_all():

i = tf.constant(0)
c = lambda i: tf.reduce_all(tf.greater([10,10],[i,i]))
b = lambda i: tf.add(i, 1)
r = tf.while_loop(c, b, [i])

Upvotes: 2

Related Questions