Session in TensorFlow
In this tutorial, let us find out what is a session in TensorFlow and it’s uses. Session will also allocate memory to store the current value of the variable. Session executes TensorFlow operations.
Basics:
Session is basically a class to run operations in TensorFlow. It encapsulates the data and method within the class. The value of the variable will be valid only in one session. Let us see a simple example and understand.
Example:
Here we use the multiply() function to multiply variables in a session. Since we are into sessions we execute within it.
1. Importing necessary Python libraries.
#tf import tensorflow as tf
As we can see from above, the TensorFlow library is enough for this simple example. Let us go to the next step.
2. Initializing and Storing the result:
Here we are initializing two arrays using the constant() function because tensors are all about arrays.
The names of the array are array1 and array2. See the Python code below:
array1 = tf.constant([26,0,1,5]) array2 = tf.constant([5,8,79,12]) result = tf.multiply(array1, array2)
3. Session:
We are initializing a session using the tf.Session. The result does not get printed unless we execute the sess.run() function.
It is important to close the session after completing the operation, done by sess.close().
sess = tf.Session() #print print(sess.run(result)) # Close sess.close()
Output:
Here we see the result of the arrays when multiplied.
The session takes in the variables as parameters, and prints down the result.
After which it is closed.
[130 0 79 60]
As seen above, session is explained with a simple example. It also supports complex operations.
You may also see:
Leave a Reply