TensorFlow Multiplication – Helpful Guide

In this Python tutorial, we will learn how to get the multiplication of tensor in Python TensorFlow. Also, we will cover the following topics.

  • TensorFlow multiplication
  • TensorFlow multiplication layer
  • TensorFlow multiplication matrix
  • TensorFlow multiplication operation
  • TensorFlow multiply tensor by scaler
  • TensorFlow multiply along axis
  • TensorFlow multiply matrix by vector
  • TensorFlow multiply int and float
  • TensorFlow multiply different shapes
  • TensorFlow multiply weights
  • TensorFlow multiply element wise
  • TensorFlow row wise multiplication
  • TensorFlow reduce multiply
  • TensorFlow multiply 3d tensor
  • TensorFlow multiply list of tensors
  • TensorFlow keras multiply layer
  • matrix multiplication tensorflow vs numpy

TensorFlow multiplication

  • In this section, we will discuss how to get the multiplication of tensor in Python TensorFlow.
  • To perform this particular task, we are going to use the tf.math.multiply() function and this function will help the user to multiply element-wise value in the form of x*y.
  • If you want to build the machine learning model then, the multiplication method will easily help you because when we take input data as an image or sound then it will be represented in the form of tensors.

Syntax:

Let’s have a look at the Syntax and understand the working of tf.math.multiply() function in Python TensorFlow.

tf.math.multiply
                (
                 x,
                 y,
                 name=None
                )
  • It consists of a few parameters.
    • x: This parameter indicates the input tensor and it must be a integer and floating data type.
    • y: This parameter indicates the input tensor and it must be a integer and floating data type.
    • name: By default it takes none value and it specifies the name of the operation.

Example:

Let’s take an example and check how to get the multiplication of tensor in Python TensorFlow.

Source Code:

import tensorflow as tf
tf.compat.v1.disable_eager_execution()

tens1 = tf.constant(189,dtype="int32",name="tens1")
tens2 = tf.constant(78,dtype="int32",name="tens2")
result= tf.math.multiply(tens1,tens2)
with tf.compat.v1.Session() as val:
    new_output=val.run(result)
    print("Multiplication of two tensors:",new_output)

In the above code, we have imported the TensorFlow library and then we have created the tensor by using the tf.constant() function and within this function, we assigned the value and datatype as an argument.

After that, we have operated by using the tf.math.multiply() method and this function will return the multiplication of the given tensor.

Here is the Screenshot of the following given code.

TensorFlow multiplication
TensorFlow multiplication

Also, read: TensorFlow mean squared error

TensorFlow multiplication layer

  • In this example we are going to multiply the layers of Tensors in Python TensorFlow.
  • To perform this particular task we are going to use the tf.Keras.layers.Multiply() function and this function will easily multiply the layers in the list of input tensors and the input tensors must be the same shape.

Syntax:

Let’s have a look at the Syntax and understand the working of tf.Keras.layers.Multiply() function in Python TensorFlow.

tf.keras.layers.Multiply
                       (
                        **kwargs
                       )

Note: This method takes only a single parameter that is ** and it always returns a single Tensor.

Example:

Let’s take an example and check how to multiply the layers of Tensors in Python TensorFlow.

Source Code:

import tensorflow as tf
import numpy as np

tf.compat.v1.disable_eager_execution()

result=tf.keras.layers.Multiply()([np.arange(6).reshape(6, 1),
                            np.arange(6, 12).reshape(6, 1)])
with tf.compat.v1.Session() as val:
    new_output=val.run(result)
    print("Multiplication of two layers tensors:",new_output)

In the following given code we have imported the TensorFlow and NumPy library and then created a session by using tf.compat.v1.disable_eager_execution() function.

After that, we have used the tf.Keras.layers.Multiply() and within this function we have passed the np.arange() function as an argument.

Here is the implementation of the following given code

Flow multiplication layer
TensorFlow multiplication layer

Read: Python TensorFlow Placeholder

TensorFlow multiplication matrix

  • In this section, we will discuss how to find the multiplication matrix in Python TensorFlow.
  • To do this task, we are going to use the tf.matmul() function and this function will help the user to multiply the matrix given input with another matrix (x*y). In simple words, we can say this function is basically used for dot product matrices.

Syntax:

Here is the Syntax of tf.matmul() function in Python TensorFlow

tf.matmul
         (
          a,
          b,
          transpose_a=False,
          transpose_b=False,
          adjoint_a=False,
          adjoint_b=False,
          a_is_sparse=False,
          b_is_sparse=False,
          name=None
         )

Example:

Let’s take an example of how to find the multiplication matrix in Python TensorFlow.

Source Code:

import tensorflow as tf
import numpy as np

new_arrays = np.array([(25,78,18),(99,27,18),(45,28,99)],dtype = 'int32')
new_arr2 = np.array([(14,18,16),(45,29,18),(24,19,55)],dtype = 'int32')
new_tens1 = tf.constant(new_arrays)
new_tens2 = tf.constant(new_arr2)
result = tf.matmul(new_tens1, new_tens2)
print((result))

In the following given code, we have imported the TensorFlow and NumPy library and then we have created a NumPy array by using the np.array() function and within this function, we assigned the integer values.

After that, we have used the tf.constant() function for creating the tensor and within this function, we assigned the array. Once you will execute this code the output displays the multiplication matrix.

Here is the execution of the following given code

TensorFlow multiplication matrix
TensorFlow multiplication matrix

Read: Tensorflow iterate over tensor

TensorFlow multiplication operation

  • In this section, we will discuss how to multiply the tensor in Python TensorFlow by using the * operator function.
  • In this example, we are going to use the tf.constant() function for creating the tensors, and then we are going to use the * operator for the multiplication tensor.

Example:

import tensorflow as tf
tf.compat.v1.disable_eager_execution()

tens1 = tf.constant([16,27,98])
tens2 = tf.constant([78,178,289])
result= tens1*tens2
with tf.compat.v1.Session() as val:
    new_output=val.run(result)
    print("Multiplication of two tensors:",new_output)

You can refer to the below Screenshot

TensorFlow multiplication operation
TensorFlow multiplication operation

Read: Python TensorFlow truncated normal

TensorFlow multiply tensor by scaler

  • In this section, we will discuss how to multiply tensor by scaler in Python TensorFlow.
  • To do this task, we are going to use the tf.multiply() function and this function will help the user to multiply tensor by the scaler. In simple words, a scaler is a single value.

Syntax:

Here is the Syntax of tf.multiply() function in Python TensorFlow

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

Example:

Let’s take an example and check how to multiply tensor by scaler in Python TensorFlow.

Source Code:

import tensorflow as tf
tf.compat.v1.disable_eager_execution()

input_tensor = tf.constant([[17, 37], [89, 45]])
result = tf.multiply(input_tensor, 67)

with tf.compat.v1.Session() as val:
    new_output=val.run(result)
    print("Multiplication of tensor by scaler:",new_output)

Here is the Screenshot of the following given code

TensorFlow multiply tensor by scaler
TensorFlow multiply tensor by scaler

Read: Convert list to tensor TensorFlow

TensorFlow multiply along axis

  • In this section, we will discuss how to multiply the tensor along axis in Python TensorFlow.
  • To do this task, we are going to use the tf.math.multiply() function and this function is used to get the multiplication.

Example:

import tensorflow as tf
tf.compat.v1.disable_eager_execution()

tens1 = tf.constant([12,34,56])
tens2 = tf.constant([83,24,67])
result= tf.math.multiply(tens1,tens2)
with tf.compat.v1.Session() as val:
    new_output=val.run(result)
    print("Multiplication of two tensors:",new_output)

Here is the Screenshot of the following given code

TensorFlow multiply along axis
TensorFlow multiply along an axis

Read: Python TensorFlow one_hot

TensorFlow multiply matrix by vector

  • In this section, we will discuss how to multiply the matrix by a vector in Python TensorFlow.
  • To perform this task, first, we will discuss the vectors in Python. A vector can be defined as a one-dimensional array. To create a vector we are going to use the numpy.array() function.
  • In this example, we are going to multiply the matrix by a vector in Python TensorFlow.

Example:

import tensorflow as tf
import numpy as np

tf.compat.v1.disable_eager_execution()
#matrix
new_matrix= np.array([[1,2,3,4],
                       [62,34,5,6]])
tens1 = tf.constant(new_matrix)
new_vector = np.array([83,24,67,5])
# vector array
tens2=tf.constant(new_vector)
result= tf.math.multiply(tens1,tens2)
with tf.compat.v1.Session() as val:
    new_output=val.run(result)
    print("Multiplication of two tensors:",new_output)

Here is the implementation of the following given code.

TensorFlow multiply matrix by vector
TensorFlow multiply matrix by a vector

Read: Python TensorFlow expand_dims

TensorFlow multiply int and float

  • In this section, we will discuss how to multiply the integer and floating datatype values in Python TensorFlow.
  • To do this task, first, we will create an array with integer values and assign an array in the tf.constant() function as an argument. This function specifies the creation of a tensor.
  • Next, we will create another array with a floating datatype and assign an array in tf.constant() function as an argument and then we will create the session by using the tf.compat.v1.Session() function.

Example:

Let’s take an example and check how to multiply the integer and floating data type values in Python TensorFlow.

Source Code:

import tensorflow as tf
import numpy as np

tf.compat.v1.disable_eager_execution()
#matrix
new_matrix= np.array([[1,2,3,4],
                       [62,34,5,6]])
tens1 = tf.constant(new_matrix)
new_vector = np.array([83.2,24.5,67.8,5.2])
# vector array
tens2=tf.constant(new_vector)
result= tf.math.multiply(tens1,tens2)
with tf.compat.v1.Session() as val:
    new_output=val.run(result)
    print("Multiplication of two tensors:",new_output)

You can refer to the below Screenshot.

TensorFlow multiply int and float
TensorFlow multiply int and float

As you can see in the Screenshot the Output displays the typeError: Input ‘y’ of ‘Mul’ Op has type float64 that does not match type int64 of argument ‘x’.

The reason behind this error is the ‘tens1’ datatype is an integer while in the case of tens2 datatype is afloat and in Python TensorFlow tf.multiply() method does not convert the type of its variable by default.

Now, the solution to this error is we can easily create the same data type in input tensors

Source Code:

import tensorflow as tf
import numpy as np

tf.compat.v1.disable_eager_execution()
#matrix
new_matrix= np.array([[1,2,3,4],
                       [62,34,5,6]])
tens1 = tf.constant(new_matrix)
new_vector = np.array([[2,4,5,6],
                      [56,7,8,9]])
# vector array
tens2=tf.constant(new_vector)
result= tf.math.multiply(tens1,tens2)
with tf.compat.v1.Session() as val:
    new_output=val.run(result)
    print(new_output)

Here is the Screenshot of the following given code

Python TensorFlow multiply int and float
Python TensorFlow multiply int and float

Read: Python TensorFlow random uniform

TensorFlow multiply different shapes

  • In this section, we will discuss how to multiply different shapes in Python TensorFlow.
  • To perform this particular task, we are going to use the tf.compat.v1.random_normal() and this function will generate from a normal distribution.
  • Next, we will use the tf.constant() function with floating values and expand the shape by using the tf.expand_dims() function.

Syntax:

Let’s have a look at the Syntax and understand the working of the tf.expand_dims() function in Python TensorFlow.

tf.expand_dims
              (
               input,
               axis,
               name=None
              )
  • It consists of a few parameters.
    • input: This parameter indicates the input tensor.
    • axis: This parameter indicates to expand the shape of input.
    • name: By default it takes none value and it specifies the name of the operation.

Example:

Let’s take an example and check how to multiply different shapes in Python TensorFlow.

Source Code:

import tensorflow as tf
import numpy as np

tf.compat.v1.disable_eager_execution()
tens1 = tf.compat.v1.random_normal([3, 3, 2])
tens2 = tf.constant([[1., 0., 0.], [0., 1., 0.], [1., 0., 1.]])

tens2 = tf.expand_dims(tens2, 2) 
new_result = tf.math.multiply(tens1, tens2)
with tf.compat.v1.Session() as val:
    new_output=val.run(new_result)
    print(new_output)

In the following given code, we have multiplied the given tensors by using the tf.math.multiply() function and then created the session by using the tf.compat.v1.Session() function.

Here is the Screenshot of the following given code.

TensorFlow multiply different shapes
TensorFlow multiply different shapes

Read: Python TensorFlow reduce_mean

TensorFlow multiply weights

  • In this section, we will discuss how to multiply the weights in Python TensorFlow.
  • To perform this particular task, we are going to use the tf.keras.layers.Multiply() function
  • And this function will easily multiply the layers in the list of input tensors and the input tensors must be the same shape.

Syntax:

Here is the Syntax of tf.Keras.layers.Multiply() function in Python TensorFlow.

tf.keras.layers.Multiply
                       (
                        **kwargs
                       )

Example:

Let’s take an example and check how to multiply the weights in Python TensorFlow.

Source Code:

import tensorflow as tf
import numpy as np

tf.compat.v1.disable_eager_execution()

result=tf.keras.layers.Multiply()([np.arange(6).reshape(6, 1),
                            np.arange(6, 12).reshape(6, 1)])
with tf.compat.v1.Session() as val:
    new_output=val.run(result)
    print(new_output)

In the following given code, we have imported the TensorFlow and NumPy library. After that, we have used the tf.Keras.layers.Multiply() function and within this function, we have assigned the np.arange() function with reshape method.

Here is the Screenshot of the following given code

TensorFlow multiply weights
TensorFlow multiply weights

Read: Python TensorFlow reduce_sum

TensorFlow multiply element wise

  • In this section, we will discuss how to multiply element-wise in Python TensorFlow.
  • In this example, we are going to use the tf.constant() function for creating the tensors, and then we are going to use the * operator for the multiplication tensor.

Example:

Let’s take an example and check how to multiply element-wise in Python TensorFlow.

Source Code:

import tensorflow as tf

tf.compat.v1.disable_eager_execution()

tens1 = tf.constant([27,18,27])
tens2 = tf.constant([190,278,189])
result= tens1*tens2
with tf.compat.v1.Session() as val:
    new_output=val.run(result)
    print("Multiplication element wise:",new_output)

In the above code, we have imported the TensorFlow library and then we have used the tf.constant() function for creating the tensor. After that, we have used the * operator and multiply both the tensors.

Here is the execution of the following given code.

TensorFlow multiply element wise
TensorFlow multiply elementwise

Read: TensorFlow Tensor to NumPy

TensorFlow row wise multiplication

  • In this section, we will discuss how to multiply row wise element in Python TensorFlow.
  • To perform this particular task, we are going to initialize the input tensor and then create another 1d tensor by using the tf.constant() function.
  • Next, we will use the tf.math.multiply() function and within this function, we are going to assign the tensors with tf.newaxis() function, and this function is used to expand the dimension multiple times in Tensor.

Example:

Let’s take an example and check how to multiply row-wise elements in Python TensorFlow.

Source Code:

import tensorflow as tf

tf.compat.v1.disable_eager_execution()
# Initializing the input tensor
tens1 = tf.constant([[[78, 56], 
                 [19, 21],
                 [15,19]]])
tens2=tf.constant([13,19,21])
result=tf.math.multiply(tens1, tens2[:, tf.newaxis])
with tf.compat.v1.Session() as val:
    new_output=val.run(result)
    print("Multiplication row wise:",new_output)

In the above code, we have just created simple tensors and now we want to display the multiplication of both the tensors row-wise by using the tf.constant() function.

Once you will execute this code the output displays the multiplication of input tensors.

Here is the implementation of the following given code

TensorFlow row wise multiplication
TensorFlow row-wise multiplication

Read: Module ‘TensorFlow’ has no attribute ‘session’

TensorFlow reduce multiply

  • In this section, we will discuss how to reduce the tensor while multiplying the input tensor in Pythn TensorFlow.
  • To do this task we are going to use the tf.reduce_prod() function and this function will help the user to generate the product of values across dimensions of an input tensor.

Syntax:

Let’s have a look at the Syntax and understand the working of tf.reduce_prod() function in Python TensorFlow.

tf.math.reduce_prod
                   (
                    input_tensor,
                    axis=None,
                    Keepdims=False,
                    name=None
                   )
  • It consists of a few parameters
    • input_tensor: This parameter indicates input tensor to reduce.
    • axis: By default it takes none value and it specifies the dimension to reduce and it will check the condition if it is none then all dimension will reduced.
    • Keepdims: By default it takes false value and if it is true then it will retains reduced dimension.
    • name: This parameter indicates the name of the operation.

Example:

Let’s take an example and check how to reduce the tensor while multiplying the input tensor in Python TensorFlow.

Source Code:

import tensorflow as tf

tf.compat.v1.disable_eager_execution()
tens = tf.constant([
    [17, 29, 18],
    [56, 96, 19],
    [23, 28, 39]
])
result = tf.reduce_prod(tens, 0)
with tf.compat.v1.Session() as val:
    new_output=val.run(result)
    print("Reduce multiply:",new_output)

In the following given code we have imported the TensorFlow library and then created a tensor by using the tf.constant() function. After that, we have used the tf.reduce_prod() function and within this function, we have assigned the input tensor and axis=0.

Here is the Output of the following given code

TensorFlow reduce multiply
TensorFlow reduce multiply

Read: TensorFlow Get Variable + Examples

TensorFlow multiply 3d tensor

  • In this section we will discuss how to multiply 3dimensional input tensors in Python TensorFlow.
  • To do this task, we are going to use the tf.matmul() function and this function will help the user to multiply the matrix given input with another matrix (x*y). In simple words, we can say this function is basically used for dot product matrices.

Example:

Let’s take an example and check how to multiply 3dimensional input tensors in Python TensorFlow.

Source Code:

import tensorflow as tf
import numpy as np

# Initialize 3D tensor
new_arrays = np.array([[[45,23,13],
                       [15,16,18],
                       [19,16,11]]])
new_arr2 = np.array([[[26,32,56],
                       [19,28,16],
                       [13,22,29]]])
new_tens1 = tf.constant(new_arrays)
new_tens2 = tf.constant(new_arr2)
result = tf.matmul(new_tens1, new_tens2)
print("Multiplication of 3D Tensors:",result)

In the above code, we have imported the TensorFlow library and created a 3-dimensional array. After that, we have inserted the array into a tf.constant() function and it will be considered as a tensor.

Once you will execute this code the output displays the new 3-dimensional tensor.

Here is the Screenshot of the following given code.

TensorFlow multiply 3d tensor
TensorFlow multiply 3d tensor

TensorFlow multiply list of tensors

  • In this section, we will discuss multiplying the list of tensors in Python TensorFlow.
  • In this example, we have created a list of tensors by using the tf.stack() function and this function is used to stack a list of ranks.
  • After creating the list of tensors, we are going to apply the tf.math.multiply() function for multiplication of input list tensors.

Syntax:

Here is the Syntax of tf.stack() function in Python TensorFlow.

tf.stack
        (
         values,
         axis=0,
         name='stack'
        )
  • It consists of a few parameters
    • values: This parameter indicates the list of tensors with same type and shape.
    • axis: By default it takes 0 value and it specifies the first dimension.
    • name: It defines the name of the operation and by default it takes ‘stack’ value.

Example:

import tensorflow as tf
import numpy as np

x = tf.constant([1, 4])
y = tf.constant([2, 5])
z = tf.constant([3, 6])
result=tf.stack([x, y, z])
print("Created first list of tensors:",result)
a = tf.constant([5, 6])
b = tf.constant([8, 9])
c = tf.constant([1, 2])
result2=tf.stack([a, b, c])
print("Created second list of tensors:",result2)
result3 = tf.math.multiply(result,result2)
print("Multiplication of list Tensors:",result3)

Here is the Screenshot of the following given code.

TensorFlow multiply list of tensors
TensorFlow multiply list of tensors

TensorFlow keras multiply layer

  • In this section, we will discuss how to use the keras multiply layer function in Python TensorFlow.
  • To perform this particular task, we are going to use the tf.keras.layers.Multiply() function and this function will easily multiply the layers in the list of input tensors and the input tensors must be the same shape.

Syntax:

Let’s have a look at the Syntax and understand the working of tf.Keras.layers.Multiply() function in Python TensorFlow.

tf.keras.layers.Multiply
                       (
                        **kwargs
                       )

Example:

Let’s take an example and check how to use the Keras multiply layer function in Python TensorFlow.

Source Code:

import tensorflow as tf
import numpy as np

tf.compat.v1.disable_eager_execution()

new_result=tf.keras.layers.Multiply()([np.arange(4).reshape(4, 1),
                            np.arange(4, 8).reshape(4, 1)])
with tf.compat.v1.Session() as val:
    new_output=val.run(new_result)
    print(new_output)

Here is the implementation of the following given code.

TensorFlow keras multiply layer
TensorFlow Keras multiply layer

Matrix multiplication tensorflow vs numpy

  • In this section, we will discuss the matrix multiplication in TensorFlow and numpy.
  • To do this task, we are going to use the tf.matmul() function and this function will help the user to multiply the matrix given input with another matrix (x*y). In simple words, we can say this function is basically used for dot product matrices.
  • Next, we will matrix product of two numpy arrays by using the np.matmul() function and this function is used to compute the matrix multiplication of given two arrays.

Example:

import tensorflow as tf
import numpy as np

new_arrays = np.array([(25,78,18),(99,27,18),(45,28,99)],dtype = 'int32')
new_arr2 = np.array([(14,18,16),(45,29,18),(24,19,55)],dtype = 'int32')
new_tens1 = tf.constant(new_arrays)
new_tens2 = tf.constant(new_arr2)
result = tf.matmul(new_tens1, new_tens2)
print((result))
#Matrix Multiplication of NumPy
import numpy as np

new_array = np.array([[56, 18],
                 [97, 25]])
new_array2 = np.array([[17, 28],
                 [98, 26]])
new_output = np.matmul(new_array, new_array2)

print("Matrix Multiplication of NumPy array:",new_output)

In the above code, we have imported the TensorFlow library for creating the tensor and using the tf.matmul() function for the multiplication of two given tensors.

After that, we have imported the NumPy library for creating the array and use the np.matmul() function for the multiplication of two given tensors.

Here is the execution of the following given code.

matrix multiplication tensorflow vs numpy
matrix multiplication TensorFlow vs NumPy

In this Python tutorial, we have learned how to get the multiplication of tensor in Python TensorFlow. Also, we have covered the following topics.

  • TensorFlow multiplication
  • TensorFlow multiplication layer
  • TensorFlow multiplication matrix
  • TensorFlow multiplication operation
  • TensorFlow multiply tensor by scaler
  • TensorFlow multiply along axis
  • TensorFlow multiply matrix by vector
  • TensorFlow multiply int and float
  • TensorFlow multiply different shapes
  • TensorFlow multiply weights
  • TensorFlow multiply element wise
  • TensorFlow row wise multiplication
  • TensorFlow reduce multiply
  • TensorFlow multiply 3d tensor
  • TensorFlow multiply list of tensors
  • TensorFlow keras multiply layer
  • matrix multiplication tensorflow vs numpy