How to assign a value to a TensorFlow variable?
I am trying to assign a new value to a tensorflow variable in python.
import tensorflow as tf import numpy as np x = tf.Variable(0) init = tf.initialize_all_variables() sess = tf.InteractiveSession() sess.run(init) print(x.eval()) x.assign(1) print(x.eval())
But the output I get is
So the value has not changed. What am I missing?
x.assign(1) does not actually assign the value
x, but rather creates a
tf.Operation that you have to explicitly run to update the variable.* A call to
Session.run() can be used to run the operation:
assign_op = x.assign(1) sess.run(assign_op) # or `assign_op.op.run()` print(x.eval()) # ==> 1
(* In fact, it returns a
tf.Tensor, corresponding to the updated value of the variable, to make it easier to chain assignments.)
★ Back to homepage or read more recommendations: