Sessions

A computational graph with operations on its nodes and tensors to its edges will be created, and in order to execute the graph, we use a TensorFlow session.

A TensorFlow session can be created using tf.Session(), as shown in the following code, and it will allocate memory for storing the current value of the variable:

sess = tf.Session()

After creating the session, we can execute our graph, using the sess.run() method.

Every computation in TensorFlow is represented by a computational graph, so we need to run a computational graph for everything. That is, in order to compute anything on TensorFlow, we need to create a TensorFlow session.

Let's execute the following code to multiply two numbers:

a = tf.multiply(3,3)
print(a)

Instead of printing 9, the preceding code will print a TensorFlow object, Tensor("Mul:0", shape=(), dtype=int32).

As we discussed earlier, whenever we import TensorFlow, a default computational graph will automatically be created and all nodes will get attached to the graph. Hence, when we print a, it just returns the TensorFlow object because the value for a is not computed yet, as the computation graph has not been executed.

In order to execute the graph, we need to initialize and run the TensorFlow session, as follows:

a = tf.multiply(3,3)
with tf.Session as sess:
print(sess.run(a))

The preceding code will print 9.

..................Content has been hidden....................

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