tf.Session()
In TensorFlow, the computations are done using graphs. But when a graph is created, the values and computations are not defined. So a session is used to run the graph. The sessions place the graphs on targeted devices and execute them. It finally returns tensors. In tf.Session() we have to define the whole skeleton of the graph before the session is started. The entire calculations have to be mentioned in the graph before the session is initialized. We use sess.run(tensor_name) to execute each computation.
Let us illustrate with the help of an example:
Python3
# importing tensorflow import tensorflow as tf # A computational graph creation # in which we take two tensors # and perform summation of two tensors # defining constant tensors x = tf.constant( 1 ) y = tf.constant( 2 ) # summation of two tensors z = x + y with tf.Session() as sess: print (sess.run(x)) print (sess.run(y)) print (sess.run(z)) |
Output:
1 2 3
Explanation of the Code
In the above code, we create two tensors and define the addition operation. Then the session is defined and executed. Each computation is performed in the session. So first x and y are printed followed by a summation of x+y.
Difference Between tf.Session() And tf.InteractiveSession() Functions in Python Tensorflow
In this article, we are going to see the differences between tf.Session() and tf.InteractiveSession().