I am trying to understand the difference between tf.assign and the assignment operator (=). I have three sets of code
First using simple tf.assign
import tensorflow as tf with tf.Graph().as_default(): a = tf.Variable(1, name="a") assign_op = tf.assign(a, tf.add(a,1)) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) print sess.run(assign_op) print a.eval() print a.eval()
The conclusion is expected to be
2 2 2
Secondly, using the assignment operator
import tensorflow as tf with tf.Graph().as_default(): a = tf.Variable(1, name="a") a = a + 1 with tf.Session() as sess: sess.run(tf.global_variables_initializer()) print sess.run(a) print a.eval() print a.eval()
The results are still 2, 2, 2.
Thirdly, I use both tf.assign and the assignment operator
import tensorflow as tf with tf.Graph().as_default(): a = tf.Variable(1, name="a") a = tf.assign(a, tf.add(a,1)) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) print sess.run(a) print a.eval() print a.eval()
Now the output becomes 2, 3, 4.
My questions
In the second snippet using (=), when I have sess.run (a), it seems like I'm running an op assignment. So, "a = a + 1" internally creates an op assignment, for example assign_op = tf.assign (a, a + 1)? Is op a running session really just assign_op? But when I run a.eval (), it does not continue to increment a, so eval appears, evaluating the βstaticβ variable.
I am not sure how to explain the third fragment. Why are two evals increasing a, but the two ratings in the second fragment are not?
Thanks.
source share