w3resource

Python TensorFlow graph and session

Python TensorFlow Basic: Exercise-7 with Solution

Write a Python program that creates a TensorFlow graph and run it inside a session to compute the result of a basic mathematical operation.

Sample Solution:

Python Code:

import tensorflow as tf
# Define a computational graph
graph = tf.Graph()
with graph.as_default():
    # Define TensorFlow constants
    x = tf.constant(5.0)
    y = tf.constant(3.0)
    
    # Define a mathematical operation
    result = tf.multiply(x, y)

# Create a TensorFlow session
with tf.compat.v1.Session(graph=graph) as session:
    # Run the session to compute the result
    output = session.run(result)
    
    # Print the result
    print("Result of the operation (within a session):", output)

Output:

Result of the operation (within a session): 15.0

Explanation:

In the exercise above -

  • We define a TensorFlow graph using tf.Graph() and use graph.as_default() to set it as the default graph.
  • Inside the graph context, we define TensorFlow constants a and b and a multiplication operation (tf.multiply(x, y)).
  • Create a TensorFlow session (tf.compat.v1.Session()) and pass the graph to it.
  • Within the session context, we run the session using session.run(result) to compute the operation result.

Python Code Editor:


Previous: Python TensorFlow eager execution.
Next: Python TensorFlow matrix initialization and print.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.