/    /  TensorFlow Sessions

TensorFlow Sessions

A session will execute the operations of the graph. To feed the graph with tensors, you need to open a session. Inside a session, an operator has to be run to create an output.Graphs and sessions are independent on each other. So, You can run a session and get the values to use later for computations.

 

Example:

Create two tensors

Create an operation

Open a session

Print the result.

 

Step 1: create two tensors A1 and A2

A1 = tf.constant([2])

A2= tf.constant([4])

Step 2: create the operator by multiplying A1 and A2

multiply = tf.multiply(A1, A2)

Step 3: open a session. All the computations will happen within the session and  need to close the       session When you are done.

Example:--

## Create a session to run the code

sess = tf.Session()

result = sess.run(multiply)

print(result)

sess.close()

Output:-- [8]

 

TensorFlow  uses an outstanding  approach for  rendering  the operation. All the computations are represented with a dataflow scheme. Dependencies between individual operation can be seen and visualize how the computations  are done using dataflow graph . Mathematical formula or algorithm are made of a number of successive operations. Graph does not display the output of the operations, it only helps to visualize the connection between individual operations.

 

Let’s see an example.

Tensorflow 13 (i2tutorials)

 

x = tf.get_variable("x", dtype=tf.int32,  initializer=tf.constant([5]))

z = tf.get_variable("z", dtype=tf.int32,  initializer=tf.constant([6]))

c = tf.constant([5], name =            "constant")square = tf.constant([2], name =            "square")

f = tf.multiply(x, z) + tf.pow(x, square) + z + c

 

Code Explanation

x: Initialize a variable( x) with a constant value of 5

z: Initialize a variable(z) with a constant value of 6

c: Initialize a constant tensor© with a constant value of 5

square: Initialize a constant tensor called square with a constant value of 2

f: Construct the operator

 

We choose to keep the values of the variables fixed. Function f contains a constant tensor called c which is the constant parameter. It takes a fixed value of 5. In the graph.

 

We also constructed a constant tensor for the power in the operator tf.pow(). It is not necessary. We did it so that you can see the name of the tensor in the graph. It is the circle called square.

 

The code below evaluates the function in a session.

 

init = tf.global_variables_initializer() # prepare to initialize all variables

with tf.Session() as sess:   

   init.run() # Initialize x and y   

function_result = f.eval()

print(function_result)                                

Output:   [66]