Python TensorFlow eager execution

Python TensorFlow Basic: Exercise-6 with Solution

Write a Python program that enables eager execution in TensorFlow 2.x and prints the result of a simple operation without a session.

Sample Solution:

Python Code:

import tensorflow as tf

# Create TensorFlow tensors
# Tensors are multi-dimensional arrays with a uniform type (called a dtype ).
x = tf.constant([1.0, 3.0])
y = tf.constant([2.0, 4.0])

# Perform a simple operation
result = x + y

# Print the result
print("Result of the operation (eager execution):", result.numpy())


Result of the operation (eager execution): [3. 7.]


In the exercise above, we can directly create TensorFlow tensors 'x' and 'y', perform the addition operation (x + y), and access the result using result.numpy() without creating a session. TensorFlow 2.x allows eager execution, making it more intuitive for users.

Python Code Editor:

Previous: Python TensorFlow dot product of two vectors.
Next: Python TensorFlow graph and session.

What is the difficulty level of this exercise?

Follow us on Facebook and Twitter for latest update.