Well! Tensorflow works in such a way that we need to create graph . Tensorflow can distribute the graph in multiple chunks. Now Tensorflow handles the computation in distributive way . Actually these chunks can be distributed among various computing devices and run parallel . In this article we will see , How to create a Graph and run the session in Tensorflow : 3 Steps
How to create a Graph and run the session in Tensorflow-
There is a prerequisites of tensorflow installation . You may use the below command if they are not already installed –
pip3 install --upgrade tensorflow ### CPU version pip3 install --upgrade tensorflow-gpu ### GPU version
Step 1 : In the first place , Import tensorflow module .
import tensorflow as tf
Step 2 : Lets Define Variable and create graph in tensorflow .
x = tf.Variable(2, name="x") y = tf.Variable(4, name="y") f = x*x + y*y + 2
Lets move further .
Step 3 : Now Create session ,initialize the variable and execute the graph .
sess = tf.Session() sess.run(x.initializer) sess.run(y.initializer) result = sess.run(f) print(result) sess.close()
Actually The first two steps are Construction phase and the last step is execution phase . You will get the below output when you put the parts of code in above step together .
How to optimize graph creation and execution in Tensorflow –
The above code is enough to create a graph and run into session . Still you can cut down some line of code using below tips –
- global_variables_initializer() – Using the above function , will save you from initializing each variable in session . Please refer the below code –
#Graph creation remain same x = tf.Variable(2, name="x") y = tf.Variable(4, name="y") f = x*x + y*y + 2
#Graph execution init = tf.global_variables_initializer() # prepare an init node with tf.Session() as sess: init.run() # actually initialize all the variables result = f.eval() print(result)
2. InteractiveSession() – In fact InteractiveSession is helpful gain to reduce line of cede in tensorflow as It set the default session as currently created InteractiveSession automatically . Please do not forget to close it after finishing all computation .Lets see the implementation here –
x = tf.Variable(2, name="x") y = tf.Variable(4, name="y") f = x*x + y*y + 2 init = tf.global_variables_initializer() sess = tf.InteractiveSession() init.run() result = f.eval() print(result) sess.close()
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.