Ch 02: Concept 05

Using variables

Here we go, here we go, here we go! Moving on from those simple examples, let's get a better understanding of variables. Start with a session:


In [1]:
import tensorflow as tf
sess = tf.InteractiveSession()

Below is a series of numbers. Don't worry what they mean. Just for fun, let's think of them as neural activations.


In [2]:
raw_data = [1., 2., 8., -1., 0., 5.5, 6., 13]

Create a boolean variable called spike to detect a sudden increase in the values.

All variables must be initialized. Go ahead and initialize the variable by calling run() on its initializer:


In [3]:
spike = tf.Variable(False)
spike.initializer.run()

Loop through the data and update the spike variable when there is a significant increase:


In [4]:
for i in range(1, len(raw_data)):
    if raw_data[i] - raw_data[i-1] > 5:
        updater = tf.assign(spike, tf.constant(True))
        updater.eval()
    else:
        tf.assign(spike, False).eval()
    print("Spike", spike.eval())


Spike False
Spike True
Spike False
Spike False
Spike True
Spike False
Spike True

You forgot to close the session! Here, let me do it:


In [5]:
sess.close()