Roman
Roman

Reputation: 131038

How to change a value of a variable in TensorFlow?

I create a Variable in TensorFlow:

c = tf.Variable([1.0, 2.0, 3.0], tf.float32)

Then I define a placeholder:

x = tf.placeholder(tf.float32)

After that I define a function (computational graph) combining the two above defined objects:

y = x + c

After that I "initialize" the global variables:

s = tf.Session()
init = tf.global_variables_initializer()
s.run(init)

Finally, I can run my function:

s.run(y, {x : [10.0, 20.0, 30.0]})

Now, I want to change the value of c. Is it possible in TensorFlow? I tried for example:

c = tf.assign(c, [1.0, 1.0, 1.0])

and also:

c = tf.Variable([1.0, 1.0, 1.0], tf.float32)

Nothing works. Whenever I call

s.run(y, {x : [10.0, 20.0, 30.0]})

I still get the old result (corresponding to the old / initial value of c).

So, how do I assign a new value to a global variables in TensorFlow?

Upvotes: 0

Views: 2515

Answers (2)

Pop
Pop

Reputation: 12401

After assigning a new value to the variable c with one of the methods you used, you need to evaluate it:

c.eval(session=s)

or

s.run(c)

Upvotes: 1

Suresh
Suresh

Reputation: 5870

After assigning new values to variable 'c', you got to make session initialize new values,

c = tf.assign(c, [1.0, 1.0, 1.0])
s.run(c)
s.run(y, {x : [10.0, 20.0, 30.0]})
array([ 11.,  21.,  31.], dtype=float32)

Upvotes: 1

Related Questions