v9.1.1
Menu

Padding for Same Convolution

easyFREEConvolutional Neural Networks (CNNs)Deep LearningDeep Learning 1

Problem Statement

Determine the padding PP required to keep the output size equal to the input size (assuming stride S=1).

Background

To maintain spatial dimensions (O=IO = I) with stride 1, we solve:

I=I−F+2P+1I = I - F + 2P + 1

This gives us: P=F−12P = \frac{F - 1}{2}

This is called "same" padding because the output has the same spatial dimensions as the input.

Your Task

Write a function calculate_same_padding(filter_size) returning the integer padding amount. Assume the filter size is always odd.

Output Format

Return an integer representing the padding needed for "same" convolution.

Example

Input
filter_size=5
Output
2
Reasoning
  • Input: filter_size is the side length FF of a square kernel, here F=5F = 5 (a 5×55 \times 5 patch), with stride S=1S = 1.
  • Why padding is needed: with no padding, a 55-wide window fits into an II-wide image only I−5+1=I−4I - 5 + 1 = I - 4 times, so the output shrinks by 44 pixels per side length.
  • The math: setting the output size equal to the input, I=I−F+2P+1I = I - F + 2P + 1, the II cancels and leaves 2P=F−1=42P = F - 1 = 4, so P=2P = 2.
  • Output: 2, meaning two rows/columns of padding on each side, so the 44 lost pixels are restored exactly.
  • Notice that the padding depends only on FF, not on the image size. Because FF is odd, F−1F - 1 is even and PP is always a whole number: F=3F = 3 gives 11, F=7F = 7 gives 33. An even FF would need uneven padding on the two sides.

Constraints

  • filter_size is always an odd number
  • 1 <= filter_size <= 15

Learn this in

More from Deep Learning 1

solution.py

Test results

Sign in to run your code against the test cases.