How can element wise multiplication be done in Tensorflow using Python?

TensorFlow is a machine learning framework provided by Google for implementing algorithms, deep learning applications, and complex mathematical operations. It uses multi-dimensional arrays called tensors and supports GPU computation for efficient processing.

Element-wise multiplication in TensorFlow multiplies corresponding elements of two tensors, producing a new tensor of the same shape. This operation is performed using the tf.multiply() function.

Installation

Install TensorFlow using pip ?

pip install tensorflow

Syntax

The basic syntax for element-wise multiplication is ?

tf.multiply(x, y, name=None)

Parameters:

  • x ? First tensor
  • y ? Second tensor (must be compatible shape with x)
  • name ? Optional name for the operation

Example

Here's how to perform element-wise multiplication of two matrices ?

import tensorflow as tf
import numpy as np

# Create two matrices using NumPy
matrix_1 = np.array([(1, 2, 3, 4, 5)], dtype='int32')
matrix_2 = np.array([(-1, 0, 1, 3, 3)], dtype='int32')

print("The first matrix is")
print(matrix_1)
print("The second matrix is")
print(matrix_2)

# Convert to TensorFlow constants
matrix_1 = tf.constant(matrix_1)
matrix_2 = tf.constant(matrix_2)

# Perform element-wise multiplication
matrix_prod = tf.multiply(matrix_1, matrix_2)
print("The element-wise product is")
print(matrix_prod)
The first matrix is
[[1 2 3 4 5]]
The second matrix is
[[-1  0  1  3  3]]
The element-wise product is
tf.Tensor([[-1  0  3 12 15]], shape=(1, 5), dtype=int32)

Using the * Operator

You can also use the * operator for element-wise multiplication ?

import tensorflow as tf

# Create tensors directly
tensor_a = tf.constant([[1, 2], [3, 4]])
tensor_b = tf.constant([[2, 1], [1, 2]])

# Element-wise multiplication using * operator
result = tensor_a * tensor_b
print("Result using * operator:")
print(result)
Result using * operator:
tf.Tensor(
[[2 2]
 [3 8]], shape=(2, 2), dtype=int32)

Key Points

  • Both tensors must have compatible shapes for broadcasting
  • tf.multiply() and * operator perform the same operation
  • The operation is performed element by element: [1,2,3] * [2,3,4] = [2,6,12]
  • The result maintains the data type of the input tensors

Conclusion

Element-wise multiplication in TensorFlow is accomplished using tf.multiply() or the * operator. This operation multiplies corresponding elements of compatible tensors, making it essential for many machine learning computations.

Updated on: 2026-03-25T15:31:56+05:30

782 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements