The Wayback Machine - https://web.archive.org/web/20240917112902/https://www.geeksforgeeks.org/how-to-pad-the-input-tensor-boundaries-with-a-constant-value-in-pytorch/
Open In App

How to Pad the Input Tensor Boundaries With a Constant Value in PyTorch?

Last Updated : 10 Oct, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we will discuss How to Pad the Input Tensor Boundaries With a Constant Value in PyTorch. We can pad the input tensor boundaries with a constant value by using torch.nn.ConstantPad2D() method.

torch.nn.ConstantPad2D() method 

We can pad the boundaries of 3D and 4D tensors and the shape of the input tensor is [C, H, W] and [N, C, H, W] respectively, where N represents the mini-batch size, C represents the number of channels, and  H, W represents the height and width respectively. This method accepts the size of padding and a constant value as input. The boundaries may be the same or different from all sides (left, right, top, bottom). we can increase the height and width of a padded tensor by using top+bottom and left+right respectively. The below syntax is used to pad the input tensor boundaries with a Constant Value.

Syntax: torch.nn.ConstantPad2d(pad, value)

Parameter:

  • pad (int, tuple): This is size of padding. The size of padding is an integer or a tuple.
  • value: This is constant value. 

Return: This method returns a new tensor with boundaries.

Example 1:

In this example, we will see how to add the same padding sizes to all sides.

Python3




# Import required library
import torch
import torch.nn as nn
 
# define a tensor
tens = torch.tensor([[[21, 22], [23, 24]]])
print("\n Input Tensor: \n", tens)
 
# give padding size same for all sides
pad = nn.ConstantPad2d(2, 9)
output = pad(tens)
 
# display result
print("\n After Pad Input Tensor: \n", output)


Output:

How to Pad the Input Tensor Boundaries With a Constant Value in PyTorch?

 

Example 2:

In this example, we will see how to add unique padding sizes to all sides (left, right, top, bottom).

Python3




# Import required library
import torch
import torch.nn as nn
 
# define a tensor
tens = torch.tensor([[[11, 12], [13, 14]]])
print("\n Input Tensor: \n", tens)
 
# add unique padding sizes to all sides
# (left, right, top, bottom)
pad = nn.ConstantPad2d((1, 2, 3, 4), 8)
output = pad(tens)
 
# display result
print("\n After Pad Input Tensor:\n", output)


Output:

How to Pad the Input Tensor Boundaries With a Constant Value in PyTorch?

 

Example 3:

In this example, we will see how to pad the boundaries of a batch of tensors.

Python3




# Import required library
import torch
import torch.nn as nn
 
# define a batch of tensor
tens = torch.tensor([[[11, 12], [13, 14]],
                     [[21, 22], [23, 24]]])
 
print("\n Input Tensor: \n", tens)
 
# add unique padding sizes to all sides
# (left, right, top, bottom)
pad = nn.ConstantPad2d(1, 8)
output = pad(tens)
 
# display result
print("\n After Pad Input Tensor:\n", output)


Output:

How to Pad the Input Tensor Boundaries With a Constant Value in PyTorch?

 



Similar Reads

How to Pad the Input Tensor Boundaries with Zero in PyTorch
In this article, we will discuss how to pad the input tensor boundaries with zero in Python using PyTorch. torch.nn.ZeroPad2D() method This method has accepted the size of padding as input and returns a new tensor with boundaries. The boundaries may be the same or different from all sides (left, right, top, bottom). we can increase the height and w
2 min read
TensorFlow - How to create a tensor of all ones that has the same shape as the input tensor
TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning neural networks. Method Used: ones_like: This method accepts a Tensor as input and returns a Tensor with same shape having all values set to one. Example 1: C/C++ Code # importing the library import tensorflow as tf # Initializing the In
1 min read
How to compute the element-wise angle of given input tensor in PyTorch?
In this article, we are going to see how to compute the element-wise angle of a given input tensor in PyTorch. torch.angle() method Pytorch is an open-source deep learning framework available with a Python and C++ interface. Pytorch resides inside the torch module. In PyTorch, we will use torch.angle() method to compute the element-wise angle, the
3 min read
How to compute element-wise entropy of an input tensor in PyTorch
In this article, we are going to discuss how to compute the element-wise entropy of an input tensor in PyTorch, we can compute this by using torch.special.entr() method. torch.special.entr() method torch.special.entr() method computes the element-wise entropy, This method accepts a tensor as input and returns a tensor with the element-wise entropy
2 min read
How to compute element-wise remainder of given input tensor in PyTorch?
In this article, we are going to see how to compute the element-wise remainder in PyTorch. we have two methods to compute element-wise reminders one is torch.remainder() and the other one is torch.fmod() let's go discuss both of them one by one. torch.remainder() method The PyTorch remainder() method computes the element-wise remainder of the divis
3 min read
How to pad an image on all sides in PyTorch?
In this article, we will discuss how to pad an image on all sides in PyTorch. transforms.pad() method Paddings are used to create some space around the image, inside any defined border. We can set different paddings for individual sides like (top, right, bottom, left). transforms.Pad() method is used for padding an image. This method accepts images
2 min read
How to Get the Value of a Tensor in PyTorch
When working with PyTorch, a powerful and flexible deep learning framework, you often need to access and manipulate the values stored within tensors. Tensors are the core data structures in PyTorch, representing multi-dimensional arrays that can store various types of data, including scalars, vectors, matrices, and higher-dimensional arrays. In thi
5 min read
How To Sort The Elements of a Tensor in PyTorch?
In this article, we are going to see how to sort the elements of a PyTorch Tensor in Python. To sort the elements of a PyTorch tensor, we use torch.sort() method. We can sort the elements along with columns or rows when the tensor is 2-dimensional. Syntax: torch.sort(input, dim=- 1, descending=False) Parameters: input: It is an input PyTorch tensor
3 min read
Difference between Tensor and Variable in Pytorch
In this article, we are going to see the difference between a Tensor and a variable in Pytorch. Pytorch is an open-source Machine learning library used for computer vision, Natural language processing, and deep neural network processing. It is a torch-based library. It contains a fundamental set of features that allow numerical computation, deploym
3 min read
Pytorch Functions - tensor(), fill_diagnol(), append(), index_copy()
This article aims to share some PyTorch functions that will help you a lot in your deep learning and data science journey. Each function will be explained using two write examples and one example where you can't use those functions. So let's get started. PyTorch is an open-source machine learning library, it contains a tensor library that enables t
9 min read
One-Dimensional Tensor in Pytorch
In this article, we are going to discuss a one-dimensional tensor in Python. We will look into the following concepts: Creation of One-Dimensional TensorsAccessing Elements of TensorSize of TensorData Types of Elements of TensorsView of TensorFloating Point TensorIntroduction The Pytorch is used to process the tensors. Tensors are multidimensional
5 min read
How to Get the Shape of a Tensor as a List of int in Pytorch?
To get the shape of a tensor as a list in PyTorch, we can use two approaches. One using the size() method and another by using the shape attribute of a tensor in PyTorch. In this short article, we are going to see how to use both of the approaches. Using size() method: The size() method returns the size of the self tensor. The returned value is a s
1 min read
How to Slice a 3D Tensor in Pytorch?
In this article, we will discuss how to Slice a 3D Tensor in Pytorch. Let's create a 3D Tensor for demonstration. We can create a vector by using torch.tensor() function Syntax: torch.tensor([value1,value2,.value n]) Code: C/C++ Code # import torch module import torch # create an 3 D tensor with 8 elements each a = torch.tensor([[[1, 2, 3, 4, 5, 6,
2 min read
Creating a Tensor in Pytorch
All the deep learning is computations on tensors, which are generalizations of a matrix that can be indexed in more than 2 dimensions. Tensors can be created from Python lists with the torch.tensor() function. The tensor() Method: To create tensors with Pytorch we can simply use the tensor() method: Syntax: torch.tensor(Data) Example: C/C++ Code im
6 min read
How to Get the Data Type of a Pytorch Tensor?
In this article, we are going to create a tensor and get the data type. The Pytorch is used to process the tensors. Tensors are multidimensional arrays. PyTorch accelerates the scientific computation of tensors as it has various inbuilt functions. Vector: A vector is a one-dimensional tensor that holds elements of multiple data types. We can create
3 min read
Change view of Tensor in PyTorch
In this article, we will learn how to change the shape of tensors using the PyTorch view function. We will also look at the multiple ways in which we can change the shape of the tensors. Also, we can use the view function to convert lower-dimensional matrices to higher dimensions. What is the necessary condition to use the PyTorch view() function o
3 min read
How to Convert Pytorch tensor to Numpy array?
In this article, we are going to convert Pytorch tensor to NumPy array. Method 1: Using numpy(). Syntax: tensor_name.numpy() Example 1: Converting one-dimensional a tensor to NumPy array C/C++ Code # importing torch module import torch # import numpy module import numpy # create one dimensional tensor with # float type elements b = torch.tensor([10
2 min read
Reshaping a Tensor in Pytorch
In this article, we will discuss how to reshape a Tensor in Pytorch. Reshaping allows us to change the shape with the same data and number of elements as self but with the specified shape, which means it returns the same data as the specified array, but with different specified dimension sizes. Creating Tensor for demonstration: Python code to crea
7 min read
How to Correctly Access Elements in a 3D Pytorch Tensor?
In this article, we will discuss how to access elements in a 3D Tensor in Pytorch. PyTorch is an optimized tensor library majorly used for Deep Learning applications using GPUs and CPUs. It is one of the widely used Machine learning libraries, others being TensorFlow and Keras. The python supports the torch module, so to work with this first we imp
4 min read
Tensor.detach() Method in Python PyTorch
In this article, we will see Tensor.detach() method in PyTorch using Python. Pytorch is a Python and C++ interface for an open-source deep learning platform. It is found within the torch module. In PyTorch, the input data has to be processed in the form of a tensor. It also includes a module that calculates gradients automatically for backpropagati
2 min read
How to access the metadata of a tensor in PyTorch?
In this article, we are going to see how to access the metadata of a tensor in PyTorch using Python. PyTorch in Python is a machine learning library. Also, it is free and open-source. It was firstly introduced by the Facebook AI research team. A tensor in PyTorch is similar to a NumPy array. But it doesn't have any knowledge of deep learning, graph
3 min read
How to access and modify the values of a Tensor in PyTorch?
In this article, we are going to see how to access and modify the value of a tensor in PyTorch using Python. We can access the value of a tensor by using indexing and slicing. Indexing is used to access a single value in the tensor. slicing is used to access the sequence of values in a tensor. we can modify a tensor by using the assignment operator
2 min read
How to compute the histogram of a tensor in PyTorch?
Before understanding how to compute a histogram of a tensor, we should have some basic knowledge. Tensors are simply mathematical objects that can be used to describe physical properties, just like scalars and vectors. And a histogram is a graphical representation that organizes a group of data points into user-specified ranges. Syntax: torch.histc
5 min read
How to find the k-th and the top "k" elements of a tensor in PyTorch?
In this article, we are going to see how to find the kth and the top 'k' elements of a tensor. So we can find the kth element of the tensor by using torch.kthvalue() and we can find the top 'k' elements of a tensor by using torch.topk() methods. torch.kthvalue() function: First this function sorts the tensor in ascending order and then returns the
2 min read
How to normalize a tensor to 0 mean and 1 variance in Pytorch?
A tensor in PyTorch is like a NumPy array with the difference that the tensors can utilize the power of GPU whereas arrays can't. To normalize a tensor, we transform the tensor such that the mean and standard deviation become 0 and 1 respectively. As we know that the variance is the square of the standard deviation so variance also becomes 1. We co
3 min read
How to squeeze and unsqueeze a tensor in PyTorch?
In this article, we will understand how to squeeze and unsqueeze a PyTorch Tensor. To squeeze a tensor we can apply the torch.squeeze() method and to unsqueeze a tensor we use the torch.unsqueeze() method. Let's understand these methods in detail. Squeeze a Tensor: When we squeeze a tensor, the dimensions of size 1 are removed. The elements of the
5 min read
How to resize a tensor in PyTorch?
In this article, we will discuss how to resize a Tensor in Pytorch. Resize allows us to change the size of the tensor. we have multiple methods to resize a tensor in PyTorch. let's discuss the available methods. Method 1: Using view() method We can resize the tensors in PyTorch by using the view() method. view() method allows us to change the dimen
5 min read
How to find the transpose of a tensor in PyTorch?
In this article, we are going to discuss how to find the transpose of the tensor in PyTorch. The transpose is obtained by changing the rows to columns and columns to rows. we can transpose a tensor by using transpose() method. the below syntax is used to find the transpose of the tensor. Syntax: torch.transpose(input_tens, dim_0, dim_1) Parameters:
2 min read
How to check if a tensor is contiguous or not in PyTorch
In this article, we are going to see how to check if a tensor is contiguous or not in PyTorch. A contiguous tensor could be a tensor whose components are stored in a contiguous order without having any empty space between them. We can check if a tensor is contiguous or not by using the Tensor.is_contiguous() method. Tensor.is_contiguous() method Th
2 min read
How to Compute the Error Function of a Tensor in PyTorch
In this article, we are going to cover how to compute the error function of a tensor in Python using PyTorch. torch.special.erf() method We can compute the error function of a tensor by using torch.special.erf() method. This method accepts the input tensor of any dimension and it returns a tensor with a computed error function with the same dimensi
2 min read
Article Tags :
Practice Tags :