Variables

Now that we are more familiar with the structure of data, we will take a look at how TensorFlow handles variables.

To define variables, we use the command tf.variable(). To be able to use variables in a computation graph, it is necessary to initialize them before running the graph in a session. This is done by running tf.global_variables_initializer().

To update the value of a variable, we simply run an assign operation that assigns a value to the variable:

state = tf.Variable(0)

Let's first create a simple counter, a variable that increases one unit at a time:

one = tf.constant(1)
new_value = tf.add(state, one)
update = tf.assign(state, new_value)

Variables must be initialized by running an initialization operation after having launched the graph. We first have to add the initialization operation to the graph:

init_op = tf.global_variables_initializer()

We then start a session to run the graph.

We first initialize the variables, then print the initial value of the state variable, and finally run the operation of updating the state variable and printing the result after each update:

with tf.Session() as session:
session.run(init_op)
print(session.run(state))
for _ in range(3):
session.run(update)
print(session.run(state))
Output:
0
1
2
3
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset