Neural Mastery
← Practice
2D Max Pooling Forward Passeasy

2D Max Pooling Forward Pass

easy Neural Networks by Hand 15 min

NumPy allowed · plain Python earns 10 bonus points

Downsample spatial representations and extract dominant features using 2D max pooling.

Related Skills

Task

Implement max_pool2d_forward(x, pool_size=2, stride=2): slide a square window of size pool_size x pool_size with step size stride over 2D input x. For each window position, take the maximum element. Round output floats to 4 decimal places.

Function Signature

max_pool2d_forward(x: list[list[float]], pool_size: int = 2, stride: int = 2) -> list[list[float]]

Examples

Example 1: 4x4 matrix with 2x2 stride 2 pool
Input: x = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 1, 2, 3], [4, 5, 6, 7]] pool_size = 2 stride = 2
Output: [[6, 8], [9, 7]]
Example 2: Overlapping pooling stride 1
Input: x = [[1, 3, 2], [4, 0, 5], [2, 1, 3]] pool_size = 2 stride = 1
Output: [[4, 5], [4, 5]]
Example 3: 3x3 pool on 3x3 input
Input: x = [[-1, 2, 0.5], [4, -3, 1], [0, 5, -2]] pool_size = 3 stride = 1
Output: [[5]]

Constraints

  • 2 <= H, W <= 128
  • 1 <= pool_size <= min(H, W)
  • stride >= 1
Python3Saved ✓
def max_pool2d_forward(x: list[list[float]], pool_size: int = 2, stride: int = 2) -> list[list[float]]:
"""Execute 2D max pooling forward pass on a single-channel feature map.

Args:
x: 2D matrix of shape (H, W).
pool_size: Square pooling window dimension.
stride: Stride of the pooling window.

Returns:
Pooled 2D matrix of shape ((H - pool_size)//stride + 1, (W - pool_size)//stride + 1).
"""
pass

Case 1: 4x4 matrix with 2x2 stride 2 pool
Input: x = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 1, 2, 3], [4, 5, 6, 7]] pool_size = 2 stride = 2
Expected: [[6, 8], [9, 7]]
Case 2: Overlapping pooling stride 1
Input: x = [[1, 3, 2], [4, 0, 5], [2, 1, 3]] pool_size = 2 stride = 1
Expected: [[4, 5], [4, 5]]
Case 3: 3x3 pool on 3x3 input
Input: x = [[-1, 2, 0.5], [4, -3, 1], [0, 5, -2]] pool_size = 3 stride = 1
Expected: [[5]]