Python TensorFlow expand_dims

In this Python tutorial, we will learn how to expand the dimension in the Tensor by using the TensorFlow function. Additionally, we will cover the following topics.

  • TensorFlow expand_dims multiple times
  • TensorFlow expand_dims reverse
  • TensorFlow expand_dims layer
  • TensorFlow expand_dims pytorch
  • TensorFlow sparse expand_dims
  • TensorFlow keras expand_dims

Python TensorFlow expand_dims

  • In this section, we will discuss how to expand the dimension in TensorFlow Python.
  • To perform this particular task, we are going to use the tf.expand_dims() function and this method is used to add a new dimension in Tensor and it always returns a tensor with a new dimension.

Syntax:

Here is the Syntax of tf.expand_dims() function

tf.expand_dims
              (
               input,
               axis,
               name=None
              )

Example:

Let’s take an example and understand the working of the tf.expand_dims() function.

Source Code:

import tensorflow as tf

tensor=tf.constant([[2,3,4],
                   [12,34,56]])
print(tensor)

result=tf.expand_dims(tensor,0)
print("Extend dimension:",result)

Here is the Screenshot of the following given code.

Python TensorFlow expand_dims
Python TensorFlow expand_dims

Another approach is to extend the dimension in TensorFlow Python by using the tf.new axis() function.

In this example, we are going to expand the dimension by using the tf.newaxis() function. In Python TensorFlow, this function is used to add a new dimension to is a given shape.

Example:

import tensorflow as tf

tensor=tf.constant([[2,3,4],
                   [12,34,56]])
print(tensor)
result2 = tensor[:, tf.newaxis]
print("Extend dimension:",result2)

In the above code first, we have created an input tensor by using the tf.constant() function and then use the tf.newaxis() function along with the slicing method.

Here is the execution of the following given code.

TensorFlow expand_dims in Python
TensorFlow expand_dims in Python

Read: TensorFlow Tensor to numpy

TensorFlow expand_dims multiple times

  • In this section we will discuss how to expand the dimension multiple times in Python TensorFlow.
  • To perform this particular task, we are going to use the tf.newaxis() function and this function will help the user to expand the dimension multiple times in Tensor along with the slicing method.
  • In this example, we are going to create a 3-d tensor by using the tf.constant() function, and then we will use the slicing method in the tf.newaxis() function.

Example:

import tensorflow as tf

inpu_tens=tf.constant([[[56,89,167],
                   [55,59,126],
                    [345,894,178]]])
print(inpu_tens)
new_result=inpu_tens[:,:,:,tf.newaxis]
print("Extend dimension multiple times:",new_result)

Once you will execute this code the output displays the new added dimension multiple times.

Here is the execution of the following given code.

Python TensorFlow expand_dims multiple times
Python TensorFlow expand_dims multiple times

Read: TensorFlow get shape

TensorFlow expand_dims reverse

  • Here we are going to discuss how to expand the dimension and get the result in reverse order by using the tf.expand_dims() function in Tensorflow Python.
  • To perform this particular task, we are going to use the tf.reverse() function and this function is used to reverse tensor elements based on the given specific axis.

Syntax:

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

tf.reverse
          (
           tensor,
           axis,
           name=None
          )
  • It consists of a few parameters
    • tensor: This parameter indicates the input tensor.
    • axis: This parameter specifies the indices of the dimension to be reverse.
    • name: It is an optional parameter and it specifies the name of the operation.

Example:

Let’s take an example and understand the working of the tf.expand_dims() and tf.reverse() function in Python TensorFlow.

Source Code:

import tensorflow as tf

new_tensor=tf.constant([[56,89,167],
                       [78,92,67]])
print(new_tensor)#Display the tensor

result=tf.expand_dims(new_tensor,0)
print(result) # expand the dimension
dims=[-1]
new_output=tf.reverse(result, dims)
print(new_output)

In the above code, we have created a tensor by using the tf.constant() function, and then we have applied the tf.expand_dims() function for expanding the dimension in a given shape.

After expanding the dimension we have used the tf.reverse() function and within this function, we have assigned the result and dims as an argument. In this example, the ‘result’ and ‘dims’ variable indicates the expanded dimension, and the reverse number by default it is -1.

Here is the Screenshot of the following given code.

Python TensorFlow expand_dims reverse
Python TensorFlow expand_dims reverse

As you can see in the Screenshot the output displays the reverse elements of a given tensor.

Read: Import error no module named TensorFlow

TensorFlow expand_dims layer

  • In this Program, we will discuss how to expand the dimension in TensorFlow keras layer.
  • To do this task, we are going to use the tf.keras.layers.Reshape() function and this function returns the reshape input from the given shape.

Syntax:

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

tf.keras.layers.Reshape
                       (
                        target_shape,
                        **kwargs
                       )
  • It consists of a few parameters
    • target_shape: This parameter will be consider as input shape and it must be a tuple of integers.
    • **kwargs: This is an additional layer keyword parameters.

Example:

Let’s take an example and check how to expand the dimension in the TensorFlow Keras layer.

Source Code:

import tensorflow as tf

new_tens = tf.keras.Sequential()
new_tens.add(tf.keras.layers.Reshape((4, 4), input_shape=(16,)))
print(new_tens.output_shape)

In the above code we have imported the TensorFlow library and then use the tf.Keras.layers.Reshape() function and within this function, we have assigned the input shape as an argument. Once you will execute this code the output displays the shape.

Here is the implementation of the following given code.

TensorFlow expand_dims layer
TensorFlow expand_dims layer

Read: Python TensorFlow reduce_sum

TensorFlow expand_dims pytorch

  • In this Program, we will discuss how to expand the dimension in Python Pytorch.
  • To perform this particular task we are going to use the tensor.expand() function and this method are used to perform expand dimension and it always returns a singleton dimension in output shape.

Syntax:

Here is the Syntax of the torch.Tensor.expand() function

Tensor.expand(*sizes)
  • It consists only one parameter
    • sizes: This parameter indicates the expanded size.

Example:

Let’s have a look at the example and check how to expand the dimension in Python Pytorch.

Source Code:

import tensorflow as tf
import torch

new_tensor = torch.tensor([[6],[16],[144]])
result=new_tensor.expand(3, 6)
print(result)

In the above code we have imported the torch library and then create a tensor by using the torch.tensor() function. After creating the tensor we have used the tensor.expand() function and within this function, we have passed the new shape which we want to expand with the given tensor.

Here is the implementation of the following given code

Python TensorFlow expand_dims pytorch
Python TensorFlow expand_dims pytorch

As you can see in the Screenshot the output displays the expanded dimension of the tensor.

Read: Python TensorFlow reduce_mean

TensorFlow sparse expand_dims

  • In this section, we will discuss how to use the sparse expand_dims() function in TensorFlow Python.
  • By using the tf.sparse.expand_dims(), we can easily add a dimension of length 1 inside a tensor shape.

Syntax:

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

tf.sparse.expand_dims
                     (
                      sp_input,
                      axis=None,
                      name=None
                     )
  • It consists of a few parameters
    • sp_input: This parameter specifies the given sparse tensor.
    • axis: By default it takes -1 value and it indicates the dimension index which we want to operate on shape input.
    • name: This parameter indicates the name of the output sparse tensor.

Example:

Let’s take an example and understand the working of tf.sparse.expand_dims() function.

Source Code:

import tensorflow as tf

new_tensor = tf.sparse.SparseTensor(indices=[[2,1,3]], values=[14,],
                            dense_shape=[4,4,6])
result=tf.sparse.expand_dims(new_tensor, axis=0)
print(result)

In the following given code we have imported the TensorFlow library and then created a sparse tensor by using the tf.sparse.SparseTensor() function and within this function, we have passed the indices, values, and dense_shape as an argument. After creating a sparse tensor we have used the tf.sparse.expand_dims() for expanding the dimension.

Here is the implementation of the following given code.

Python TensorFlow sparse expand_dims
Python TensorFlow sparse expand_dims

As you can see in the Screenshot the Output displays the new size of a given tensor.

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

TensorFlow keras expand_dims

  • Here we are going to discuss how to expand the dimension in TensorFlow keras.
  • To perform this particular task we are going to use the tf.keras.backend.expand_dims() function and this method are used to add 1-length of dimension at index axis.

Syntax:

Let’s have a look at the syntax and understand the working of tf.keras.backend.expand_dims() function.

tf.keras.backend.expand_dims(
    x,
    axis=-1
)
  • It consists of a few parameters
    • x: This parameter indicates the inout tensor or input variable.
    • axis: By default it takes -1 value and this specifies that where we want to add new axis.

Example:

Let’s take an example and check how to expand the dimension in Python TensorFlow Keras.

Source Code:

import tensorflow as tf

tensor= tf.constant([[13,56,27],
                    [14,28,39]])
print(tensor)
new_output=tf.keras.backend.expand_dims(tensor,-1)
print("Expand dimension in keras backend:",new_output)

In the above code we have imported the TensorFlow library and then created an input tensor by using the tf.constant() function and within this function, we have assigned the 2-dimensional tensor.

After creating a tensor we have used the tf.keras.backend.expand_dims() function and assign the tensor and axis=-1 parameter as an argument. Once you execute this code the output displays the new size of the tensor by adding the length of 1.

Here is the Screenshot of the following given code.

Python TensorFlow keras expand_dims
Python TensorFlow Keras expand_dims

You may also like to read the following TensorFlow tutorials.

So, in this Python tutorial, we have learned how to expand the dimension in the Tensor by using the TensorFlow function. Additionally, we will cover the following topics.

  • TensorFlow expand_dims multiple times
  • TensorFlow expand_dims reverse
  • TensorFlow expand_dims layer
  • TensorFlow expand_dims pytorch
  • TensorFlow sparse expand_dims
  • TensorFlow keras expand_dims