Saturday, December 13, 2025
HomeLanguagesHow to Pad the Input Tensor Boundaries with Zero in PyTorch

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 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 zero.

Syntax: torch.nn.ZeroPad2d(pad)

Parameter:

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

Return: This method returns a new tensor with boundaries.

Example 1:

In this example, we will see how to pad the input tensor boundaries with zero.

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)
 
# give padding size same for all sides
pad = nn.ZeroPad2d(1)
output = pad(tens)
 
# display result
print("\n After Pad Input Tensor: \n", output)


Output:

 

Example 2:

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

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.ZeroPad2d((1, 2, 3, 4))
output = pad(tens)
 
# display result
print("\n After Pad Input Tensor:\n", output)


Output:

 

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32446 POSTS0 COMMENTS
Milvus
105 POSTS0 COMMENTS
Nango Kala
6814 POSTS0 COMMENTS
Nicole Veronica
11952 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12030 POSTS0 COMMENTS
Shaida Kate Naidoo
6949 POSTS0 COMMENTS
Ted Musemwa
7200 POSTS0 COMMENTS
Thapelo Manthata
6897 POSTS0 COMMENTS
Umr Jansen
6882 POSTS0 COMMENTS