Variables are TensorFlow objects that hold and update parameters. A variable must be initialized; also you can save and restore it to analyze your code.
Variables are created by the tf.Variable() statement.
In the following example, we want to count the numbers from 1 to 10:
import tensorflow as tf
We create a variable that will be initialized to the scalar value 0:
value = tf.Variable(0,name="value")
The assign() and add() operators are just nodes of the computation graph so they do not execute the assignment until the session is run:
one = tf.constant(1)
new_value = tf.add(value,one)
update_value=tf.assign(value,new_value)
initialize_var = tf.global_variables_initializer()
We can instantiate the computation graph:
with tf.Session() as sess:
sess.run(initialize_var)
print(sess.run(value))
for _ in range(10):
sess.run(update_value)
print(sess.run(value))
Let's recall that a tensor object is a symbolic handle to the result of an operation, but does not actually hold the values of the operation's output:
>>>
0
1
2
3
4
5
6
7
8
9
10
>>>
You typically represent the parameters of a statistical model as a set of variables. For example, you would store the weights for a neural network as a tensor in a variable. During the training phase, you update this tensor by running a training graph repeatedly.