Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

0 0 

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

like image 218
abora Avatar asked Dec 11 '15 09:12

abora


People also ask

How do I assign a value in TensorFlow?

Tensorflow variables represent the tensors whose values can be changed by running operations on them. The assign() is the method available in the Variable class which is used to assign the new tf. Tensor to the variable. The new value must have the same shape and dtype as the old Variable value.

How do you assign something to a variable?

Assigning values to variables is achieved by the = operator. The = operator has a variable identifier on the left and a value on the right (of any value type). Assigning is done from right to left, so a statement like var sum = 5 + 3; will assign 8 to the variable sum .

How do you get the value of a tf variable?

To get the current value of a variable x in TensorFlow 2, you can simply print it with print(x) . This prints a representation of the tf. Variable object that also shows you its current value.


1 Answers

In TF1, 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 Operation.run() or 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.)

However, in TF2 x.assign(1) will now assign the value eagerly:

x.assign(1) print(x.numpy()) # ==> 1 
like image 61
mrry Avatar answered Oct 08 '22 08:10

mrry