DL0012 Zero Padding

Why is zero padding used in deep learning?

Answer

Zero padding adds rows and columns of zeros around the input before a convolution. In CNNs it preserves spatial dimensions, prevents border information from being under-sampled, allows larger kernels and deeper stacks, and gives explicit control over output size. Beyond CNNs, padding standardizes variable-length sequences so NLP and time-series models can process them in batches.

(1) Preserves Spatial Dimensions: Without padding (“valid” convolution), a k \times k kernel shrinks the feature map by k - 1 in total per dimension ((k-1)/2 per side) each layer; padding with p = (k-1)/2 keeps the size unchanged.
(2) Retains Boundary Information: Padded borders let the kernel center on edge pixels, so corners and boundaries are processed as thoroughly as the interior.
(3) Controls Output Size: Padding decouples output dimensions from kernel size, enabling deeper networks and predictable feature-map shapes.

Mathematical Formulation:
n_{out} = \left\lfloor \frac{n_{in} + 2p - k}{s} \right\rfloor + 1

Where:

  • n_{out} and n_{in} are the output and input spatial sizes.
  • p is the padding width added to each side, k is the kernel size, and s is the stride.
  • “Same” padding for stride 1 uses p = (k-1)/2, giving n_{out} = n_{in}.
2D convolution example showing a 4x4 input padded with one ring of zeros into 6x6, so a 3x3 kernel produces a same-size 4x4 output.

Figure 1: Padding a 4 \times 4 input to 6 \times 6 lets a 3 \times 3 kernel output the same 4 \times 4 size instead of shrinking to 2 \times 2.

Beyond CNNs: In NLP and time-series tasks, zero padding extends shorter sequences to a uniform length for efficient batching. Because padded positions carry no information, models combine padding with attention masks so Transformer self-attention ignores those positions entirely.

Three panels comparing valid convolution without padding, same convolution with padding, and NLP sequence padding with an attention mask.

Figure 2: Valid shrinks the map, same preserves it, and sequence padding plus a mask enables batched NLP inputs.


Login to view more content


Log in to track your progress

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *