Max Pooling Forward Pass

~20 mincode completion

Implement max_pool2d(x, pool_size, stride).

  • x is a 2D array (single channel).
  • pool_size is the square window edge length .
  • stride is ; note that may differ from , giving overlapping windows when .
  • 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 array

  • pool_size: square window edge length F

  • stride: step size S between windows

  • Return (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

~20 min

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.

Python
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
Loading docs…

The AI Mentor needs an account

It reads your code and the failing tests and nudges you toward the fix without handing you the answer. Free accounts get it on every problem you're working on today.