Neural Mastery
← Practice
Conv2D Output Spatial Dimension Calculatoreasy

Conv2D Output Spatial Dimension Calculator

easy Neural Networks by Hand 15 min

NumPy allowed · plain Python earns 10 bonus points

Calculate exact output spatial feature map dimensions for convolutional layers across various padding, stride, and dilation configurations.

Task

Implement conv2d_output_shape(...): calculate the output spatial shape [out_H, out_W]. The effective kernel dimension with dilation d is k_eff = k + (k - 1) * (d - 1). The output dimension is floor((dim + 2 * pad - k_eff) / stride) + 1. Return [out_H, out_W] as integers.

Function Signature

conv2d_output_shape(H: int, W: int, kH: int, kW: int, pad_h: int = 0, pad_w: int = 0, stride_h: int = 1, stride_w: int = 1, dilation_h: int = 1, dilation_w: int = 1) -> list[int]

Examples

Example 1: Valid convolution no padding
Input: H = 32 W = 32 kH = 3 kW = 3 pad_h = 0 pad_w = 0 stride_h = 1 stride_w = 1 dilation_h = 1 dilation_w = 1
Output: [30, 30]
Example 2: Same convolution with padding 1
Input: H = 28 W = 28 kH = 3 kW = 3 pad_h = 1 pad_w = 1 stride_h = 1 stride_w = 1 dilation_h = 1 dilation_w = 1
Output: [28, 28]
Example 3: Strided downsampling
Input: H = 224 W = 224 kH = 7 kW = 7 pad_h = 3 pad_w = 3 stride_h = 2 stride_w = 2 dilation_h = 1 dilation_w = 1
Output: [112, 112]

Constraints

  • 1 <= H, W <= 4096
  • 1 <= kH <= H
  • 1 <= kW <= W
  • stride_h, stride_w >= 1
  • dilation_h, dilation_w >= 1
Python3Saved ✓
def conv2d_output_shape(H: int, W: int, kH: int, kW: int, pad_h: int = 0, pad_w: int = 0, stride_h: int = 1, stride_w: int = 1, dilation_h: int = 1, dilation_w: int = 1) -> list[int]:
"""Compute the output spatial height and width of a 2D convolution.

Args:
H, W: Input spatial height and width.
kH, kW: Kernel height and width.
pad_h, pad_w: Implicit padding added to both sides of height/width.
stride_h, stride_w: Stride of the convolution.
dilation_h, dilation_w: Dilation rate of kernel elements.

Returns:
List [out_H, out_W] of integer dimensions.
"""
pass

Case 1: Valid convolution no padding
Input: H = 32 W = 32 kH = 3 kW = 3 pad_h = 0 pad_w = 0 stride_h = 1 stride_w = 1 dilation_h = 1 dilation_w = 1
Expected: [30, 30]
Case 2: Same convolution with padding 1
Input: H = 28 W = 28 kH = 3 kW = 3 pad_h = 1 pad_w = 1 stride_h = 1 stride_w = 1 dilation_h = 1 dilation_w = 1
Expected: [28, 28]
Case 3: Strided downsampling
Input: H = 224 W = 224 kH = 7 kW = 7 pad_h = 3 pad_w = 3 stride_h = 2 stride_w = 2 dilation_h = 1 dilation_w = 1
Expected: [112, 112]