web123456

tf.while_loop loop implementation

tf.while_loop can be understood in this way

loop = []
while cond(loop):
    loop = body(loop)

That is, the loop parameter is first passed into cond to determine whether the condition is true. After it is established, the loop parameter is passed into body to perform the operation, and then the loop parameter after the operation is returned, that is, the loop parameter has been updated, and the updated parameter is passed into cond and loop in turn until the condition does not meet.

Let's look at how such a scenario is implemented in tensorflow

i= 0
n =10
while(i < n):
    i = i +1

First of all, this sentence requires a judgment condition, that is,

i  < n

If the condition is met, the operation in the loop body will be executed. This judgment condition is in tensorflow. You need to write a function to replace it.

def cond(i, n):
    return i < n

Then there is the operation in the loop body, and a function is needed to replace it.

def body(i, n):
    i = i + 1
    return i, n

Please note that although there is no operation related to parameter n in the body function, parameter n must be passed in, because as mentioned above, to form a loop, the parameters must be returned to the cond function after the body function is updated to determine whether the conditions are met. If the parameter n is not passed in next time, it cannot be judged.

Together, the code must be

 i  = 0
 n =10 

 def cond(i, n):
    return i < n

def body(i, n):
    i = i + 1
    return i, n
i, n = tf.while_loop(cond, body, [i, n])

Executable code

import tensorflow as tf 
i = tf.get_variable("ii", dtype=tf.int32, shape=[], initializer=tf.ones_initializer())
n = (10)

def cond(a, n):
    return  a< n
def body(a, n):
    a = a + 1
    return a, n

a, n = tf.while_loop(cond, body, [a, n])
with () as sess:
    tf.global_variables_initializer().run()
    res = ([a, n])
    print(res)