The Wayback Machine - https://web.archive.org/web/20241122170312/https://www.geeksforgeeks.org/what-is-padding-in-neural-network/
Open In App

What is Padding in Neural Network?

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

As we know while building a neural network we are doing convolution to extract features with the help of kernels with respect to the current datasets which is the important part to make your network learn while convolving.

For example, if you want to train your neural network to classify whether it is a dog or cat then while applying convolution, kernels are going to extract features from the images like the ear of a dog & tails of a dog much more to get differentiate between dog & cat features that is how convolution work.

As you can see from the above image if you convolve 3 X 3 kernels over 6 x 6 input image size, the size of the image will be reduced by 2 as kernel size is 3 with output as 4 x 4 further applying 3 x 3 on 4 x 4 size will be reduced to 2 x 2 as seen in the above image. But if you will applying 3 x3 now we cannot convolve further as the output image size is 2 x 2 now as mathematically you will get a negative dimension which is not possible.

But if you observe it may happen our network will not consider some of the important features because we end up with just 2 convolutions which are therefore difficult to find that all features are extracted to differentiate between two objects that you are training the neural network with.

Why image size is reduced by 2 only?

We have the formula to calculate the output image size which is:

O = n - k + 1

Where O stands for output image size, n is the input image size & k is the kernel size.

If you look at the above example we have input image size as 6 x 6 with kernel size 3 x 3. So, output size after applying the first convolution will be

O = 6 - 3 + 1
O = 4 x 4

Here is one of the reasons why Padding comes into a picture

Why Do We Need padding?

  • The main aim of the network is to find the important feature in the image with the help of convolutional layers but it may happen that some features are the corner of the image which the kernel (feature extractor) visit very less number of times due to which there could be a possibility to miss out some of the important information.
  • So, padding is the solution where we add extra pixels around the 4 corners of the image which increases the image size by 2 but should be as neutral as possible which means do not alter the original image features in any way to make it complicated for the network to learn further. Also, we can add more layers as now we have a larger image.

We can say for easy understanding that padding helps the kernel (feature extractor) to visit pixels of the image around the corners more times to extract important features for better learning.

If you see the below image showing an illustration of how the kernel is visiting the pixels of the image & it is important that the kernel should visit each pixel at least more than 1 time or 2 times to extract the important features.

Have a look at the above Image while convolving around the image with the kernel as pixels around the corners of the image visited by the kernel very less number of time as compared to the middle part of the pixels.

If you can observe from the above picture we have added the padding of Zero around the 4 corners of the image & input image size increased from 6 x 6 to 8 x 8 after applying the first convolution output image size would be 6 x 6 that is what we want as per the question above.

After applying the padding we can observe that there is the possibility of convolving one more time compared to without padding which helps the network to extract more features for better learning at the same time. Even applying the padding helps us to convolve one more time which helps the network to extract more features for better learning at the same time.

If you see the below image & this is how the padded image looks like:

There are two types of padding

  • Valid padding where we are not applying padding at all & P=0
  • Same padding where output images size should be equal to the input image size due to which we have applied the same padding.

From the above formula we have:

O = n - k + 1

Now, we are adding padding over the 4 sides of an image down, up, right & left side adding zero padding. (NOTE: Here we are not considering strides)

Let’s see a new formula with padding

O = n - k + 1 +2p

If you see for same padding  O = n (Output image size should be equal to input image size)

So, O = O - k + 1 + 2p     from here we can use simply mathematics in above equation mentioned P = (k - 1)/2

Why do we always use ODD kernels like 3 x 3, 5 x 5 & so on why not 4 x 4 kernels(even kernels)?

For example, if you want to use a 4 x 4 kernel then what will be the padding you have to use?

You can use the above formula p =( k – 1)/2

We have kernel = 4 x 4

p= 4 -1/2  =  3/2 = 1.5

Which means you have to add 1.5 pixels around 4 corners of the image to apply padding, which in turn is not possible because we can’t add 1.5 pixels instead we can only add the pixels in whole numbers like 1,2,3,4,5,6 & 7 so on pixels around the corners of the image.

This is one of the reasons why kernels are always an odd number so that we can add a whole number of pixels around the image to extract more features as adding 1.5 pixels around doesn’t make any sense & is difficult to add at the same time.

Why do we always use padding = 1 & what do we mean by saying that you are using padding of 1. In all the standard networks you notice that the padding used is always 1, as simply while we are padding we are adding some information by ourselves and it not a good idea to interfere with the network that a lot as the best features learned by the network is the self-learned once and also will be increasing the input size a lot and make the model heavy.

Why “zero-padding”?

Now one of the questions that arise in our mind is why do people always use zero(0) padding blindly just following what we have read in blogs or any course. So, now we understand how padding is working, and how it is important for a neural network. But one question always comes to our head, why only 0 padding? Why can’t we use 1-padding or any number?

When we normalize an image, the pixel range goes from 0 to 1, and if it hasn’t been normalized then the pixel range will be from 0 to 255.

If we consider both cases, we can see 0 is the minimum number. So, using 0 becomes a more generic way of doing this. Also, it makes sense computationally since we are considering the minimum number among those pixels.

But it is not always 0, Consider a case where we have values ranging from -0.3 to 0.3, in this case, the minimum number is -0.3, and if we use the padding of 0 around it, it would be Gray instead of black. The same case comes when we have an activation function like tanh, which ranges the values from -1 to 1, in this case, the minimum value is -1., so we would be using (-1) padding instead of 0 paddings, for adding black pixels around it. If we use 0 paddings, then it would be a gray color boundary instead of black color.

But Here, is a problem, it is not always possible where we can calculate what will happen to inactivation values, so we look for a neutral value that can satisfy most of the cases without problem, and this is where 0 padding saves us. If we even consider the above-mentioned two ranges, we can see, the use of 0 padding would give a gray boundary instead of black, which is not a huge loss. We can also call these cases, “The Minimum Padding Case”, where we are considering the minimum value among activation maps.

Most of the time, we use relu in between layers, so in the case of relu, 0 becomes the minimum value and that is why it is so popular and generic.

Do we need to add padding in every layer?

Let’s understand this with the help of an example, lets the MNIST digit recognizer dataset

Here are some sample images from the MNIST dataset. Above we discussed two main reasons to use padding:

  • Shrinking Output after convolution, so we can add more layers to extract more features
  • Add to save the loss of information around the edges

You can see that the numbers in the dataset are not around the edges, they are mainly at the center. That means there may be very little information around the edges. So, the main reason to add padding, in this case, is to add more layers. But also MNIST does not require that many layers. You may add padding in the initial layers but in all the layers it would be of much use, you will be just making your model heavier.

In conclusion, it depends on the datasets and the problem statement, which layers would require padding.



Previous Article
Next Article

Similar Reads

Difference Between Feed-Forward Neural Networks and Recurrent Neural Networks
Pre-requisites: Artificial Neural Networks and its Applications Neural networks are artificial systems that were inspired by biological neural networks. These systems learn to perform tasks by being exposed to various datasets and examples without any task-specific rules. In this article, we will see the difference between Feed-Forward Neural Netwo
2 min read
A single neuron neural network in Python
Neural networks are the core of deep learning, a field that has practical applications in many different areas. Today neural networks are used for image classification, speech recognition, object detection, etc. Now, Let's try to understand the basic unit behind all these states of art techniques.A single neuron transforms given input into some out
3 min read
Effect of Bias in Neural Network
Neural Network is conceptually based on actual neuron of brain. Neurons are the basic units of a large neural network. A single neuron passes single forward based on input provided. In Neural network, some inputs are provided to an artificial neuron, and with each input a weight is associated. Weight increases the steepness of activation function.
3 min read
Importance of Convolutional Neural Network | ML
Convolutional Neural Network as the name suggests is a neural network that makes use of convolution operation to classify and predict. Let's analyze the use cases and advantages of a convolutional neural network over a simple deep learning network. Weight sharing: It makes use of Local Spatial coherence that provides same weights to some of the edg
2 min read
Neural Network Advances
We know that our world is changing quickly but there are lot of concrete technology advances that you might not hear a lot about in the newspaper or on tv, that are nevertheless having a dramatic impact on our lives. Some of these big new stories are related to the ANN(Artificial Neural Network) - a relatively new phenomenon in artificial intellige
3 min read
Why For loop is not preferred in Neural Network Problems?
For loop take much time for completing iterations and in ML practise we have to optimize the time so we can use for loops. But then you must be wondering what to use then? Don't worry we will discuss this in the below section. How to get rid from loop in Machine Learning or Neural Network? The solution is Vectorization. Now the question arises what
2 min read
Implementation of Artificial Neural Network for AND Logic Gate with 2-bit Binary Input
Artificial Neural Network (ANN) is a computational model based on the biological neural networks of animal brains. ANN is modeled with three types of layers: an input layer, hidden layers (one or more), and an output layer. Each layer comprises nodes (like biological neurons) are called Artificial Neurons. All nodes are connected with weighted edge
4 min read
Implementation of Artificial Neural Network for OR Logic Gate with 2-bit Binary Input
Artificial Neural Network (ANN) is a computational model based on the biological neural networks of animal brains. ANN is modeled with three types of layers: an input layer, hidden layers (one or more), and an output layer. Each layer comprises nodes (like biological neurons) are called Artificial Neurons. All nodes are connected with weighted edge
4 min read
Implementation of Artificial Neural Network for NAND Logic Gate with 2-bit Binary Input
Artificial Neural Network (ANN) is a computational model based on the biological neural networks of animal brains. ANN is modeled with three types of layers: an input layer, hidden layers (one or more), and an output layer. Each layer comprises nodes (like biological neurons) are called Artificial Neurons. All nodes are connected with weighted edge
4 min read
Implementation of Artificial Neural Network for NOR Logic Gate with 2-bit Binary Input
Artificial Neural Network (ANN) is a computational model based on the biological neural networks of animal brains. ANN is modeled with three types of layers: an input layer, hidden layers (one or more), and an output layer. Each layer comprises nodes (like biological neurons) are called Artificial Neurons. All nodes are connected with weighted edge
4 min read
Implementation of Artificial Neural Network for XOR Logic Gate with 2-bit Binary Input
Artificial Neural Network (ANN) is a computational model based on the biological neural networks of animal brains. ANN is modeled with three types of layers: an input layer, hidden layers (one or more), and an output layer. Each layer comprises nodes (like biological neurons) are called Artificial Neurons. All nodes are connected with weighted edge
4 min read
Implementation of Artificial Neural Network for XNOR Logic Gate with 2-bit Binary Input
Artificial Neural Network (ANN) is a computational model based on the biological neural networks of animal brains. ANN is modeled with three types of layers: an input layer, hidden layers (one or more), and an output layer. Each layer comprises nodes (like biological neurons) are called Artificial Neurons. All nodes are connected with weighted edge
4 min read
Implementation of neural network from scratch using NumPy
DNN(Deep neural network) in a machine learning algorithm that is inspired by the way the human brain works. DNN is mainly used as a classification algorithm. In this article, we will look at the stepwise approach on how to implement the basic DNN algorithm in NumPy(Python library) from scratch. The purpose of this article is to create a sense of un
11 min read
Difference between Neural Network And Fuzzy Logic
Neural Network: Neural network is an information processing system that is inspired by the way biological nervous systems such as brain process information. A neural network is composed of a large number of interconnected processing elements known as neurons which are used to solve problems. A neural network is an attempt to make a computer model o
2 min read
ANN - Implementation of Self Organizing Neural Network (SONN) from Scratch
Prerequisite: ANN | Self Organizing Neural Network (SONN) Learning Algorithm To implement a SONN, here are some essential consideration- Construct a Self Organizing Neural Network (SONN) or Kohonen Network with 100 neurons arranged in a 2-dimensional matrix with 10 rows and 10 columns Train the network with 1500 2-dimensional input vectors randomly
4 min read
ANN - Self Organizing Neural Network (SONN)
Self Organizing Neural Network (SONN) is an unsupervised learning model in Artificial Neural Network termed as Self-Organizing Feature Maps or Kohonen Maps. These feature maps are the generated two-dimensional discretized form of an input space during the model training (based on competitive learning). This phenomenon is very similar to biological
2 min read
ANN - Self Organizing Neural Network (SONN) Learning Algorithm
Prerequisite: ANN | Self Organizing Neural Network (SONN) In the Self Organizing Neural Network (SONN), learning is performed by shifting the weights from inactive connections to active ones. The neurons which were won are selected to learn along with their neighborhood neurons. If a neuron does not respond for a specific input pattern, then learni
3 min read
Adjusting Learning Rate of a Neural Network in PyTorch
Learning Rate is an important hyperparameter in Gradient Descent. Its value determines how fast the Neural Network would converge to minima. Usually, we choose a learning rate and depending on the results change its value to get the optimal value for LR. If the learning rate is too low for the Neural Network the process of convergence would be very
7 min read
Architecture and Learning process in neural network
In order to learn about Backpropagation, we first have to understand the architecture of the neural network and then the learning process in ANN. So, let's start about knowing the various architectures of the ANN: Architectures of Neural Network: ANN is a computational system consisting of many interconnected units called artificial neurons. The co
9 min read
Applications of Neural Network
A neural network is a processing device, either an algorithm or genuine hardware, that endeavors to recognize underlying relationships in a set of data through a process that mimics the way the human brain operates. The computing world has a ton to acquire from neural networks, also known as artificial neural networks or neural nets. The neural net
3 min read
How to Visualize a Neural Network in Python using Graphviz ?
In this article, We are going to see how to plot (visualize) a neural network in python using Graphviz. Graphviz is a python module that open-source graph visualization software. It is widely popular among researchers to do visualizations. It's representing structural information as diagrams of abstract graphs and networks means you only need to pr
4 min read
Deep parametric Continuous Convolutional Neural Network
Deep Parametric Continuous Kernel convolution was proposed by researchers at Uber Advanced Technologies Group. The motivation behind this paper is that the simple CNN architecture assumes a grid-like architecture and uses discrete convolution as its fundamental block. This inhibits their ability to perform accurate convolution to many real-world ap
6 min read
Convolutional Neural Network (CNN) Architectures
Convolutional Neural Network(CNN) is a neural network architecture in Deep Learning, used to recognize the pattern from structured arrays. However, over many years, CNN architectures have evolved. Many variants of the fundamental CNN Architecture This been developed, leading to amazing advances in the growing deep-learning field. Let's discuss, How
11 min read
Transformer Neural Network In Deep Learning - Overview
In this article, we are going to learn about Transformers. We'll start by having an overview of Deep Learning and its implementation. Moving ahead, we shall see how Sequential Data can be processed using Deep Learning and the improvement that we have seen in the models over the years. Deep Learning So now what exactly is Deep Learning? But before w
10 min read
Training of Convolutional Neural Network (CNN) in TensorFlow
In this article, we are going to implement and train a convolutional neural network CNN using TensorFlow a massive machine learning library. Now in this article, we are going to work on a dataset called 'rock_paper_sissors' where we need to simply classify the hand signs as rock paper or scissors. Stepwise ImplementationStep 1: Importing the librar
5 min read
Working of Convolutional Neural Network (CNN) in Tensorflow
In this article, we are going to see the working of convolution neural networks with TensorFlow a powerful machine learning library to create neural networks. Now to know, how a convolution neural network lets break it into parts. the 3 most important parts of this convolution neural networks are, ConvolutionPoolingFlattening These 3 actions are th
5 min read
Convolutional Neural Network (CNN) in Tensorflow
It is assumed that the reader knows the concepts of Neural Networks and Convolutional Neural Networks. If you are sure about the topics please refer to Neural Networks and Convolutional Neural Networks. Building Blocks of CNN: Convolutional Neural Networks are mainly made up of three types of layers: Convolutional Layer: It is the main building blo
4 min read
Difference between a Neural Network and a Deep Learning System
Since their inception in the late 1950s, Artificial Intelligence and Machine Learning have come a long way. These technologies have gotten quite complex and advanced in recent years. While technological advancements in the Data Science domain are commendable, they have resulted in a flood of terminologies that are beyond the understanding of the av
7 min read
Flower Recognition Using Convolutional Neural Network
In this article, we will use Convolutional Neural Network to solve a Supervised Image Classification problem of recognizing the flower types - rose, chamomile, dandelion, sunflower, & tulip. Understanding the concept of a Convolutional Neural Network refers to this. Once, understand the concept of CNN we can start with the project. Steps to be
4 min read
Lung Cancer Detection using Convolutional Neural Network (CNN)
Computer Vision is one of the applications of deep neural networks that enables us to automate tasks that earlier required years of expertise and one such use in predicting the presence of cancerous cells. In this article, we will learn how to build a classifier using a simple Convolution Neural Network which can classify normal lung tissues from c
8 min read
three90RightbarBannerImg