Achilles
Achilles

Reputation: 1129

Tensorflow while loop runs only once

The below while loop should print "\n\nInside while..." 10 times but when I run the graph, "\n\nInside while..." is printed exactly once. Why is that?

i = tf.constant(0)

def condition(i):
   return i < 10

def body(i):
    print("\n\nInside while...", str(i))
    return i + 1

r = tf.while_loop(condition, body, [i])

Upvotes: 1

Views: 407

Answers (2)

Alexandre Passos
Alexandre Passos

Reputation: 5206

Your issue comes from conflating TensorFlow graph building with graph execution.

The functions you pass to tf.while_loop get executed once, to generate the TensorFlow graph responsible for executing the loop itself. So if you had put a tf.Print in there (for example, saying return tf.Print(i+1, [i+1])) you'd see it print 10 times when the loop is actually executed by the TensorFlow system.

Upvotes: 3

Noctis Skytower
Noctis Skytower

Reputation: 22001

I know practically nothing about TensorFlow and cannot help you with your immediate problem, but you can accomplish something similar (maybe) if you write your code differently. Following the logic of your program, a different implementation of while_loop was devised below. It takes your condition and body to run a while loop that has been parameterized with functions passed to it. Shown below is a conversation with the interpreter showing how this can be done.

>>> def while_loop(condition, body, local_data):
    while condition(*local_data):
        local_data = body(*local_data)
    return local_data

>>> i = 0
>>> def condition(i):
    return i < 10

>>> def body(i):
    print('Inside while', i)
    return i + 1,

>>> local_data = while_loop(condition, body, (i,))
Inside while 0
Inside while 1
Inside while 2
Inside while 3
Inside while 4
Inside while 5
Inside while 6
Inside while 7
Inside while 8
Inside while 9
>>> local_data
(10,)
>>> 

Upvotes: 0

Related Questions