Skip to content
E
Educatum

Zero padding in CNN

Curated by Educatum AI teamLast updated:
Computer Vision and CNN
Direct Answer

Zero-padding appends borders of zeros around an input feature map before applying a convolutional kernel. It prevents spatial dimensions from shrinking across deep stacks of convolutional layers ('same' padding) and ensures edge pixels participate in multiple receptive fields rather than being under-sampled. While simple and computationally cheap, zero-padding introduces artificial step edges at borders and can leak absolute spatial position cues compared with reflection or replication padding.

Study Card: Zero padding in CNN

Direct Answer

Zero-padding surrounds the spatial borders of an input tensor or intermediate feature map with zeros before applying a convolutional filter. For an input spatial width/height NN, kernel size KK, symmetric padding PP on each side, and stride SS, the output spatial dimension is:

Nout=⌊N+2P−KS⌋+1N_{\text{out}} = \left\lfloor \frac{N + 2P - K}{S} \right\rfloor + 1

Two common regimes follow directly from this formula:

  • valid padding (P=0P = 0): No padding is added, so each K>1K > 1 convolution shrinks spatial resolution by K−1K - 1 (at S=1S = 1), limiting maximum network depth before maps vanish and giving border pixels fewer receptive-field passes than interior pixels.
  • same padding (P=K−12P = \frac{K - 1}{2} for odd KK and S=1S = 1): Output spatial dimensions match the input (Nout=NN_{\text{out}} = N), letting deep CNNs stack dozens of layers while preserving border information. (Note: When S>1S > 1 or KK is even, TensorFlow’s "same" mode pads asymmetrically on bottom/right if total padding is odd, whereas PyTorch specifies explicit symmetric padding.)

Key Terms

  • Convolutional Layer: Slides learnable K×KK \times K spatial filters across feature maps to detect local patterns.
  • Spatial Dimensions (H×WH \times W): Height and width of an image or feature map.
  • Valid vs. Same Padding: Unpadded shrinking convolution (P=0P = 0) versus dimension-preserving padding (Nout=⌈N/S⌉N_{\text{out}} = \lceil N / S \rceil).
  • Border Information Preservation: Padding lets corner and edge pixels sit at the center of kernels just like interior pixels.
  • Boundary Artifacts: Sharp zero discontinuities at image edges that can distort edge filters or subtly encode absolute spatial coordinates inside CNNs.

Example

Apply a 3×33\times 3 kernel with stride S=1S = 1 to a 5×55\times 5 image:

  • Without padding (P=0P = 0): Nout=(5+0−3)/1+1=3N_{\text{out}} = (5 + 0 - 3)/1 + 1 = 3, shrinking output to 3×33\times 3; corner pixels participate in only 11 kernel window instead of 99.
  • With zero-padding (P=1P = 1): the padded input becomes 7×77\times 7, giving Nout=(5+2(1)−3)/1+1=5N_{\text{out}} = (5 + 2(1) - 3)/1 + 1 = 5, keeping the output at 5×55\times 5 and allowing corner pixels to sit centered inside a 3×33\times 3 receptive field.

Code Implementation

import tensorflow as tf
from tensorflow import keras

# Same padding preserves spatial resolution across Conv2D layers (downsampling occurs only in MaxPooling2D)
model_same = keras.Sequential([
    keras.layers.Input(shape=(28, 28, 1)),
    keras.layers.Conv2D(32, (3, 3), activation="relu", padding="same"),
    keras.layers.MaxPooling2D((2, 2)),
    keras.layers.Conv2D(64, (3, 3), activation="relu", padding="same"),
    keras.layers.MaxPooling2D((2, 2)),
    keras.layers.Conv2D(128, (3, 3), activation="relu", padding="same"),
])

# Valid padding shrinks spatial size by (K - 1) = 2 at every Conv2D layer
model_valid = keras.Sequential([
    keras.layers.Input(shape=(28, 28, 1)),
    keras.layers.Conv2D(32, (3, 3), activation="relu", padding="valid"),
    keras.layers.MaxPooling2D((2, 2)),
    keras.layers.Conv2D(64, (3, 3), activation="relu", padding="valid"),
    keras.layers.MaxPooling2D((2, 2)),
    keras.layers.Conv2D(128, (3, 3), activation="relu", padding="valid"),
])

print("=== Same Padding Layer Output Shapes ===")
for layer in model_same.layers:
    print(f"  {layer.name}: {layer.output.shape}")

print("\n=== Valid Padding Layer Output Shapes ===")
for layer in model_valid.layers:
    print(f"  {layer.name}: {layer.output.shape}")
  • Stride & Dilation: Generalize the output formula to Nout=⌊N+2P−D(K−1)−1S⌋+1N_{\text{out}} = \left\lfloor \frac{N + 2P - D(K - 1) - 1}{S} \right\rfloor + 1 for dilation factor DD.
  • Reflect & Replicate Padding: Alternatives (tf.pad(..., mode="REFLECT") or PyTorch padding_mode="reflect") that mirror or extend boundary pixels instead of inserting zeros, avoiding artificial dark-border contrast in image synthesis, style transfer, and super-resolution.
  • Circular Padding: Wraps boundaries around for periodic signals such as 360∘360^\circ panoramas or audio spectrograms.
  • Transposed Convolutions: Padding controls how fractional-stride upsampling aligns spatial output dimensions in segmentation decoders like U-Net.
View all →

Try keywords like RoPE, FlashAttention, DPO, or Blind 75.