TensorFlow works by first defining and describing our model in abstract, and then, when we are ready, we make it a reality in the session. The description of the model is what is known as your "Computation Graph" in TensorFlow terms. Let's play with a simple example. First, let's construct the graph:
In [ ]:
import tensorflow as tf
# creates nodes in a graph
# "construction phase"
x1 = tf.constant(5)
x2 = tf.constant(6)
result = tf.multiply(x1,x2)
print(result)
So we have some values. Now, we can do things with those values, such as multiplication:
Notice that the output is just an abstract tensor still. No actual calculations have been run, only operations created. Each operation, or "op," in our computation graph is a "node" in the graph.
To actually see the result, we need to run the session. Generally, you build the graph first, then you "launch" the graph:
In [ ]:
# defines our session and launches graph
sess = tf.Session()
# runs result
print(sess.run(result))
sess.close()
#after closing session the follwing print statement gives error ---RuntimeError: Attempted to use a closed Session.
#print(sess.run(result))
With the "With" statement, you get better syntax and exceptions handling.
"The with statement simplifies exception handling by encapsulating common preparation and cleanup tasks."
In addition, it will automatically close the file. The with statement provides a way for ensuring that a clean-up is always used.
In [ ]:
with tf.Session() as sess:
output = sess.run(result)
print(output)
In [ ]:
import tensorflow as tf
a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')
b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b')
c = tf.matmul(a, b)
sesss=tf.Session()
sesss.run(c)