user104493 user104493 - 1 year ago 419
Python Question

How to assign 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()



But the output I get is


So the value has not changed. What am I missing?

Answer Source

The statement x.assign(1) does not actually assign the value 1 to x, but rather creates a tf.Operation that you have to explicitly run to update the variable.* A call to or can be used to run the operation:

assign_op = x.assign(1)  # or ``
# ==> 1

(* In fact, it returns a tf.Tensor, corresponding to the updated value of the variable, to make it easier to chain assignments.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download