Max Pooling Forward Pass
Implement max_pool2d(x, pool_size, stride).
xis a 2D array (single channel).pool_sizeis the square window edge length F.strideis S; note that S may differ from F, giving overlapping windows when S<F.- Return the pooled 2D array.
Hint: two nested loops over the output grid are perfectly acceptable here. Compute the output shape first, allocate, then fill. Deriving the shape from the loop bounds is where off-by-one errors come from.
Examples
2x2 window, stride 2: the textbook non-overlapping case
- Input
- max_pool2d([[1, 3, 2, 4], [5, 6, 7, 8], [9, 2, 1, 0], [1, 1, 3, 4]], 2, 2)
- Output
- [[6, 8], [9, 4]]
Stride 1 gives overlapping windows and a 3x3 output
- Input
- max_pool2d([[1, 3, 2, 4], [5, 6, 7, 8], [9, 2, 1, 0], [1, 1, 3, 4]], 2, 1)
- Output
- [[6, 7, 8], [9, 7, 8], [9, 3, 4]]
Ragged input: the leftover 5th column and row are dropped
- Input
- max_pool2d([
- Output
- [[6, 8], [14, 16]]
Hints
Hint 1
Loop a fixed number of times and update the running value each pass.
Hint 2
Reach for floor reading past the input edge rather than ceil.
Requirements
x: (H, W) input arraypool_size: square window edge length Fstride: step size S between windowsReturn (floor((H-F)/S)+1, floor((W-F)/S)+1) array of window maxima.
Constraints
Allowed library: NumPy only
Time limit: 200 ms, Memory: 64 MB
Where this shows up
8 employers weight this skill
4 autonomy companies, 1 defense company, 1 health and bio company, 1 enterprise vendor, 1 AI product company. Top match scores 92.
import numpy as np
def max_pool2d(x: np.ndarray, pool_size: int, stride: int) -> np.ndarray:
"""
2D max pooling over a single-channel input, no padding.
Args:
x: (H, W) input array
pool_size: square window edge length F
stride: step size S between windows
Returns:
(floor((H-F)/S)+1, floor((W-F)/S)+1) array of window maxima.
"""
# YOUR CODE HERE
pass