Zero padding in CNN
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 , kernel size , symmetric padding on each side, and stride , the output spatial dimension is:
Two common regimes follow directly from this formula:
validpadding (): No padding is added, so each convolution shrinks spatial resolution by (at ), limiting maximum network depth before maps vanish and giving border pixels fewer receptive-field passes than interior pixels.samepadding ( for odd and ): Output spatial dimensions match the input (), letting deep CNNs stack dozens of layers while preserving border information. (Note: When or is even, TensorFlow’s"same"mode pads asymmetrically on bottom/right if total padding is odd, whereas PyTorch specifies explicit symmetricpadding.)
Key Terms
- Convolutional Layer: Slides learnable spatial filters across feature maps to detect local patterns.
- Spatial Dimensions (): Height and width of an image or feature map.
- Valid vs. Same Padding: Unpadded shrinking convolution () versus dimension-preserving padding ().
- 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 kernel with stride to a image:
- Without padding (): , shrinking output to ; corner pixels participate in only kernel window instead of .
- With zero-padding (): the padded input becomes , giving , keeping the output at and allowing corner pixels to sit centered inside a 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}")
Related Concepts
- Stride & Dilation: Generalize the output formula to for dilation factor .
- Reflect & Replicate Padding: Alternatives (
tf.pad(..., mode="REFLECT")or PyTorchpadding_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 panoramas or audio spectrograms.
- Transposed Convolutions: Padding controls how fractional-stride upsampling aligns spatial output dimensions in segmentation decoders like U-Net.