Problems
Loading...
1 / 1

Max Pooling 2D

Computer Vision
Medium

Max pooling is a downsampling operation commonly used in convolutional neural networks. It reduces the spatial dimensions of a feature map by selecting the maximum value within non-overlapping rectangular regions (pools). This helps reduce computation, extract dominant features, and provide a degree of spatial invariance.

Given a 2D matrix and a pool size, apply max pooling with non-overlapping windows (stride equal to pool size).

Algorithm

  1. Compute the output dimensions by dividing the input dimensions by the pool size (integer division):
Hout=H/p,Wout=W/pH_{out} = \lfloor H / p \rfloor, \quad W_{out} = \lfloor W / p \rfloor
  1. For each output position (i, j), examine the corresponding p × p window in the input starting at (i·p, j·p), and select the maximum value:
out[i][j]=max0a,b<pX[ip+a][jp+b]\text{out}[i][j] = \max_{0 \le a,b < p} X[i \cdot p + a][j \cdot p + b]
Loading visualization...

Examples

Input:

X = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]], pool_size = 2

Output:

[[6, 8], [14, 16]]

The 4×4 matrix is divided into four 2×2 windows. The maximum of each window is: max(1,2,5,6)=6, max(3,4,7,8)=8, max(9,10,13,14)=14, max(11,12,15,16)=16.

Input:

X = [[1,2,3,4,5,6],[7,8,9,10,11,12],[13,14,15,16,17,18],[19,20,21,22,23,24],[25,26,27,28,29,30],[31,32,33,34,35,36]], pool_size = 3

Output:

[[15, 18], [33, 36]]

The 6×6 matrix is divided into four 3×3 windows. The maximum of each 3×3 block is selected.

Hint 1

Compute out_h = H // pool_size and out_w = W // pool_size. For each output position (i, j), iterate over the pool_size × pool_size window starting at (i * pool_size, j * pool_size) and track the maximum value.

Hint 2

Use nested loops: outer loops for output rows and columns, inner loops for the pooling window. Initialize max_val = float('-inf') for each window, then compare each element.

Requirements

  • Apply non-overlapping max pooling with stride equal to pool_size
  • Select the maximum value from each pooling window
  • Handle rectangular inputs where dimensions may not be square
  • Discard any remaining rows or columns that don't form a complete pool
  • Return the pooled 2D matrix as a list of lists

Constraints

  • X is a non-empty 2D matrix of numbers
  • pool_size >= 1
  • Input dimensions are at least pool_size in both directions
  • Return a 2D list of numbers
  • Time limit: 300 ms
Try Similar Problems