v9.1.1
Menu

Calculate Output Volume

easyFREEConvolutional Neural Networks (CNNs)Deep LearningDeep Learning 1

Problem Statement

Calculate the spatial dimensions of a convolutional layer output.

Background

The output size OO of a convolutional layer is determined by input size II, filter size FF, padding PP, and stride SS using the formula:

O=⌊I−F+2PS⌋+1O = \lfloor \frac{I - F + 2P}{S} \rfloor + 1

If the filter is larger than the padded input (i.e., I−F+2P<0I - F + 2P < 0), the configuration is invalid.

Your Task

Write a function conv_output_size(input_size, filter_size, padding, stride) that returns the output dimension. If the configuration is invalid (filter larger than padded input), return -1.

Output Format

Return an integer representing the output dimension, or -1 if invalid.

Example

Input
input_size=32, filter_size=3, padding=1, stride=1
Output
32
Reasoning
  • Inputs: a 3232-pixel input (I=32I = 32), a 33-wide filter (F=3F = 3), 11 pixel of zero padding per side (P=1P = 1), and stride S=1S = 1 (the filter moves one pixel at a time).
  • Padded width: 32+2⋅1=3432 + 2 \cdot 1 = 34 pixels for the filter to sweep.
  • Room to slide: the filter covers 33 of those, leaving I−F+2P=32−3+2=31I - F + 2P = 32 - 3 + 2 = 31 pixels of travel. Non-negative, so the configuration is valid.
  • Count positions: ⌊31/1⌋=31\lfloor 31 / 1 \rfloor = 31 steps, plus the starting position: 31+1=3231 + 1 = 32.
  • Output: the integer 32, one value per filter position along this dimension.
  • Notice: F=3F = 3, P=1P = 1, S=1S = 1 keeps the width unchanged ("same" padding). Stride 22 would give ⌊31/2⌋+1=16\lfloor 31/2 \rfloor + 1 = 16; the floor discards the leftover pixel the filter can't fully cover.

Constraints

  • 1 <= input_size <= 1000
  • 1 <= filter_size <= input_size
  • 0 <= padding <= 100
  • 1 <= stride <= input_size

Learn this in

More from Deep Learning 1

solution.py

Test results

Sign in to run your code against the test cases.