We will now make use of Tensorflow's variables. They are different from constant in that
1. they are mutable during the execution, i.e., they can change their values
2. they will store their state (value), which shall equal to that from the lastest execution
For example, you can define a counter variable that will increment its value on each execution:
counter = counter + 1
Below is the simple demo code for doing this in Tensorflow:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import tensorflow as tf | |
# counter init to 0 | |
counter = tf.Variable(0) | |
# constant to increment counter by each execution | |
one = tf.constant(1) | |
# counter = counter + 1 | |
increment = tf.assign(counter, tf.add(counter, one)) | |
# required to initialize any tf's variables | |
init = tf.global_variables_initializer() | |
with tf.Session() as sess: | |
# init all tf variables | |
sess.run(init) | |
# initial counter value | |
print sess.run(counter) | |
# increment 5 times | |
for _ in range(5): | |
# execute the actually increment | |
sess.run(increment) | |
print sess.run(counter) |
1. tf.assign is another operation that will assign a new value to the variable on each execution (run)
2. one must initialize all variables
Running it will output
0
1
2
3
4
5
So far so good!
No comments:
Post a Comment