What is wrong with the following code? The tf.assign
op works just fine when applied to a slice of a tf.Variable
if it happens outside of a loop.
Your variable is not an output of the operations run inside your loop, it is an external entity living outside the loop. So you do not have to provide it as an argument.
Also, you need to enforce the update to take place, for example using tf.control_dependencies
in body
.
import tensorflow as tf
v = [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0]
n = len(v)
a = tf.Variable(v, name = 'a')
def cond(i):
return i < n
def body(i):
op = tf.assign(a[i], a[i-1] + a[i-2])
with tf.control_dependencies([op]):
return i + 1
i = tf.while_loop(cond, body, [2])
sess = tf.InteractiveSession()
tf.global_variables_initializer().run()
i.eval()
print(a.eval())
# [ 1 1 2 3 5 8 13 21 34 55 89]
Possibly you may want to be cautious and set parallel_iterations=1
to enforce the loop to run sequentially.