sebtac
sebtac

Reputation: 578

tf.assign() - How to Increment value by given value in each iteration

I am trying to create iteration in tensor flow where "val" increases by one after each iteration of the loop below. But this code increases it by 2. so i have two questions:

1.) Why is it happening? 2.) what should i do to make it add only 1 in each iteration?

iters = 10

x = tf.constant(1, dtype=tf.float32, name="X")
y = tf.constant(2, dtype=tf.float32, name="y")
val = tf.Variable(y-x, name="val")
assign_op = tf.assign(val, val+1)

init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)

    print("val_init",val.eval())

    for iter in range(iters):
        sess.run(assign_op)
        print(iter, x.eval(),y.eval(),"val",val.eval(),"assign_op", assign_op.eval())

RESULTS:

"""
val_init 1.0
0 1.0 2.0 val 2.0 assign_op 3.0
1 1.0 2.0 val 4.0 assign_op 5.0
2 1.0 2.0 val 6.0 assign_op 7.0
3 1.0 2.0 val 8.0 assign_op 9.0
4 1.0 2.0 val 10.0 assign_op 11.0
5 1.0 2.0 val 12.0 assign_op 13.0
6 1.0 2.0 val 14.0 assign_op 15.0
7 1.0 2.0 val 16.0 assign_op 17.0
8 1.0 2.0 val 18.0 assign_op 19.0
9 1.0 2.0 val 20.0 assign_op 21.0
"""

Upvotes: 0

Views: 511

Answers (1)

sladomic
sladomic

Reputation: 876

Your "assign_op.eval()" is increasing "val" as well. So you are increasing it twice per iteration. You see it in your output.

""" val_init 1.0 0 1.0 2.0 val 2.0 assign_op 3.0 1 1.0 2.0 val 4.0 assign_op 5.0 2 1.0 2.0 val 6.0 assign_op 7.0 3 1.0 2.0 val 8.0 assign_op 9.0 4 1.0 2.0 val 10.0 assign_op 11.0 5 1.0 2.0 val 12.0 assign_op 13.0 6 1.0 2.0 val 14.0 assign_op 15.0 7 1.0 2.0 val 16.0 assign_op 17.0 8 1.0 2.0 val 18.0 assign_op 19.0 9 1.0 2.0 val 20.0 assign_op 21.0 """

Upvotes: 1

Related Questions