tensorflow - Difference between tf.assign and assignment operator (=) -
i'm trying understand difference between tf.assign , assignment operator(=). have 3 sets of code
first, using simple tf.assign
import tensorflow tf tf.graph().as_default(): = tf.variable(1, name="a") assign_op = tf.assign(a, tf.add(a,1)) tf.session() sess: sess.run(tf.global_variables_initializer()) print sess.run(assign_op) print a.eval() print a.eval()
the output expected as
2 2 2
second, using assignment operator
import tensorflow tf tf.graph().as_default(): = tf.variable(1, name="a") = + 1 tf.session() sess: sess.run(tf.global_variables_initializer()) print sess.run(a) print a.eval() print a.eval()
the results still 2, 2, 2.
third, use both tf.assign , assignment operator
import tensorflow tf tf.graph().as_default(): = tf.variable(1, name="a") = tf.assign(a, tf.add(a,1)) tf.session() sess: sess.run(tf.global_variables_initializer()) print sess.run(a) print a.eval() print a.eval()
now, output becomes 2, 3, 4.
my questions are
in 2nd snippet using (=), when have sess.run(a), seems i'm running assign op. "a = a+1" internally create assignment op assign_op = tf.assign(a, a+1)? op run session assign_op? when run a.eval(), doesn't continue increment a, hence appears eval evaluating "static" variable.
i'm not sure how explain 3rd snippet. why 2 evals increment a, 2 evals in 2nd snippet doesn't?
thanks.
the main confusion here doing a = + 1
reassign python variable a
resulting tensor of addition operation a + 1
. tf.assign
, on other hand, operation setting value of tensorflow variable.
a = tf.variable(1, name="a") = + 1
this equivalent to:
a = tf.add(tf.variable(1, name="a"), 1)
with in mind:
in 2nd snippet using (=), when have sess.run(a), seems i'm running assign op. "a = a+1" internally create assignment op assign_op = tf.assign(a, a+1)? [...]
it might so, not true. explained above, reassign python variable. , without tf.assign
or other operation changes variable, stays value 1. each time a
evaluated, program calculate a + 1 => 1 + 1
.
i'm not sure how explain 3rd snippet. why 2 evals increment a, 2 evals in 2nd snippet doesn't?
that's because calling eval()
on assignment tensor in third snippet triggers variable assignment (note isn't different doing session.run(a)
current session).
Comments
Post a Comment