How to multiply tensors using Tensorflow

Tensorflow is an open-source Python framework that is mainly used to build and train machine learning models. Tensorflow provides a range of functions to deal with data structures, such as single dimension or multi-dimensional arrays known as tensors.

Tensor multiplication is an important part of building machine learning models, as all data (images or sounds) is represented in the form of tensors. The tensorflow.math.multiply() function is used for this purpose.

Syntax

tensorflow.math.multiply(x, y, name)

Parameters

  • x: Input tensor to be multiplied.
  • y: Input tensor that multiplies. y must have the same data type as x.
  • name: Defines the name of the operation. This parameter is optional.

Return value

The function returns a tensor object with the data type of the input tensors.

Code

#import library
import tensorflow as tf
#define the input tensors
x=tf.constant([4,8,1,5],dtype=tf.int64)
y=tf.constant([9,3,7,6],dtype=tf.int64)
#print input tensors
print('x: ',x)
print('y: ',y)
#multiply the tensors
result=tf.math.multiply(x,y)
#print the result
print('Result: ',result)

Output

The code above will give the following output.

x:  tf.Tensor([4 8 1 5], shape=(4,), dtype=int64)
y:  tf.Tensor([9 3 7 6], shape=(4,), dtype=int64)
Result:  tf.Tensor([36 24  7 30], shape=(4,), dtype=int64)

Free Resources