ML Grind

Convolution Output Size - CNNs & Computer Vision

Implement Convolution Output Size in Python with NumPy. easy exercise with examples, hints, and instant feedback. No setup or signup required.

Convolution Output Size

What you'll build

A function that returns the spatial output size (height or width) of a convolution or pooling layer.

Background

Designing a CNN means tracking shapes through every layer: the linear layer after the last conv needs to know how many features arrive. Interviewers ask this constantly ("a 224x224 image goes through a 7x7 stride-2 conv with padding 3: what comes out?").

Formula

output_size = floor((input_size + 2 * padding - kernel_size) / stride) + 1
  • input_size: height or width of the input, H
  • kernel_size: kernel height or width, k
  • padding: zeros added on each side, p (hence 2p)
  • stride: step between kernel positions, s

The + 1 counts the first kernel position; floor drops a last position that would hang off the edge. The same formula gives the output size of pooling layers.

Inputs

Four non-negative Python ints with stride >= 1 and kernel_size <= input_size + 2 * padding.

Expected return format

A Python int.

Edge cases and conventions

  • Use integer floor division //, never / (that returns a float such as 15.5).
  • padding = (k - 1) // 2 with stride = 1 and odd k keeps the size ("same" convolution).
  • A 1x1 convolution with stride 1 and no padding keeps the size.

Constraints

Plain Python arithmetic.

Follow-up

  • With dilation d, the effective kernel size is d * (k - 1) + 1. Extend the formula.
  • What is the output size of a transposed convolution with stride s?

Examples

Input: input_size=32, kernel_size=3, padding=1, stride=1
Output: 32

(32 + 2 - 3) // 1 + 1 = 32: "same" padding keeps the size.

Input: input_size=32, kernel_size=3, padding=0, stride=2
Output: 15

(32 - 3) // 2 + 1 = 14 + 1 = 15: floor drops the half step.

Input: input_size=224, kernel_size=7, padding=3, stride=2
Output: 112

The ResNet stem: (224 + 6 - 7) // 2 + 1 = 112.

Practice in Python

def conv_output_size(input_size, kernel_size, padding=0, stride=1):
    """
    Calculate the output size of a convolution (or pooling) layer.

    Args:
        input_size: Input height or width
        kernel_size: Kernel height or width
        padding: Zero-padding added to each side
        stride: Step between kernel positions

    Returns:
        output_size: Output height or width (int)
    """
    # Your code here
    pass

The interactive editor loads with Python and NumPy. Run your implementation against 6 tests, or use the progressive hints.

More exercises in this section →