How To Multiplication Of 2 Tensors In TensorFlow?

We will learn how to do multiplication in TensorFlow using tf.multiply() function.

tf.multiply() : Do Element wise Multiplication,
It can be multiply list, tuple, scaler,
tf variable/constant/placeholder/SparceMatrix with each other and with scaler and with list/tuple

Note: * operator can be used to multiply 2 tensors

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

Args
xA Tensor. Must be one of the following types: bfloat16halffloat32float64uint8int8uint16int16int32int64complex64complex128.
yTensor. Must have the same type as x.
nameA name for the operation (optional).
Returns
Tensor. Has the same type as x.
Raises
InvalidArgumentError: When x and y have incompatible shapes or types.

Multiplication of 2 Variables with TensorFlow

import tensorflow as tf
import numpy as np

Scaler Multiply

a = 10
b = 20

tf.multiply(a,b)

Multiply 2 List

l1 = [1,2,3,4]
l2 = [5,6,7,8]

tf.multiply(l1, l2)

Multiply 2 Tuple

t1 = (1,2,3,4)
t2 = (5,6,7,8)

tf.multiply(t1,t2)

Multiply List/Tuple with Scaler

l1 = [1,2,3,4]
a =10
tf.multiply(a, l1)

Multiply of 2 list/Tuple with Diiferent Size

If the size of 2 variables is different then tf.subtract() function will through error. If any one of the variables contains only a single item then it will do the element-wise operation.

#this code will through error
l1 = [1,2,3,4]
l2 = [5,6]

tf.multiply(l1, l2)

Multiply 2 Numpy Array

npa1 = np.array([1,2,3,4,5])
npa2 = np.array([1,2,3,4,5])

tf.multiply(npa1, npa2)

Multiply Numpy array with Scaler

npa1 = np.array([1,2,3,4,5])
a = 10

tf.multiply(npa1, a)

Multiply Numpy array with single element np array

npa1 = np.array([1,2,3,4,5])
npa2 = np.array([[1]])

tf.multiply(npa1, npa2)

Multiply 2 TF Constant Tensor

tf_ct1 = tf.constant([1,2,3,4])
tf_ct2 = tf.constant([1,2,3,4])

tf.multiply(tf_ct1, tf_ct2)
tf_ct1 = tf.constant([1,2,3,4])
tf_ct2 = tf.constant([1,2,3,4])

tf_ct1 * tf_ct2

Multiply TF Constant Tensor with Scaler

tf_ct1 = tf.constant([1,2,3,4])
a = 10
tf.multiply(tf_ct1, a)
tf_ct1 = tf.constant([1,2,3,4])
a = 10
tf_ct1 * a

Multiply 2 TF Variable

tf_vr1 = tf.Variable([1,2,3,4])
tf_vr2 = tf.Variable([1,2,3,4])

tf.multiply(tf_vr1, tf_vr2)

Multiply TF Variable with Scaler

tf_vr1 = tf.Variable([1,2,3,4])
a = 10
tf.multiply(tf_vr1, a)

Multiply 2 Numpy array with different Shape

x = np.ones(6).reshape(1, 2, 1, 3) # (2,2,3,3)
print("x: ", x)
y = np.ones(6).reshape(2, 1, 3, 1)
print("y: ", y)

tf.multiply(x, y)

Leave a Reply