w3resource

Python TensorFlow element-wise addition

Python TensorFlow Basic: Exercise-2 with Solution

Write a Python program that implements element-wise addition on two TensorFlow tensors of shape (2, 3) filled with random values.

Sample Solution:

Python Code:

import tensorflow as tf
import numpy as np

# Enable eager execution in TensorFlow 2.x
tf.config.run_functions_eagerly(True)

# Create two random tensors with shape (2, 3)
# Tensors are multi-dimensional arrays with a uniform type (called a dtype ).
ts1 = tf.constant(np.random.rand(2, 3))
ts2 = tf.constant(np.random.rand(2, 3))

# Perform element-wise addition
result_tensor = tf.add(ts1, ts2)

# Print the original tensors and the result
print("Original tensors:")
print("Tensor1:")
print(ts1)
print("Tensor2:")
print(ts2)
print("\nResult of Element-wise Addition:")
print(result_tensor)

Output:

Original tensors:
Tensor1:
tf.Tensor(
[[0.16777132 0.45360842 0.72095194]
 [0.5060912  0.80159217 0.06390026]], shape=(2, 3), dtype=float64)
Tensor2:
tf.Tensor(
[[0.01992499 0.4548276  0.55259358]
 [0.67508427 0.1676432  0.77147187]], shape=(2, 3), dtype=float64)

Result of Element-wise Addition:
tf.Tensor(
[[0.18769631 0.90843602 1.27354552]
 [1.18117547 0.96923538 0.83537213]], shape=(2, 3), dtype=float64)
 

Explanation:

In the exercise above -

  • import tensorflow as tf - It imports the TensorFlow library ('tf').
  • import numpy as np - It imports the NumPy library ('np').
  • tf.config.run_functions_eagerly(True) - Enable eager execution in TensorFlow 2.x.
  • ts1 = tf.constant(np.random.rand(2, 3)) - It creates a TensorFlow constant tensors, ts1.
  • ts2 = tf.constant(np.random.rand(2, 3)) - It creates a TensorFlow constant tensors, ts2.
  • result_tensor = tf.add(ts1, ts2) - It performs element-wise addition between 'ts1' and 'ts2' using the tf.add() function, stored in 'result_tensor'.
  • Finally, the print() function prints the original tensors (ts1 and ts2) and the result of element-wise addition (result_tensor).

Go to:


PREV : Shape and data type.
NEXT : Python TensorFlow create and update tensor shape.

Python Code Editor:


Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.