Problems
Loading...
1 / 1

Max Pooling Forward

Neural Networks
Medium

Max pooling is a downsampling operation commonly used in convolutional neural networks to reduce spatial dimensions while retaining the most prominent features. It slides a window over the input and takes the maximum value in each window position.

Given a 2D input matrix X (height H, width W), a pool size p, and a stride s, compute the max pooling output.

Algorithm

  1. Compute the output dimensions:
Hout=Hps+1,Wout=Wps+1H_{out} = \lfloor \frac{H - p}{s} \rfloor + 1, \quad W_{out} = \lfloor \frac{W - p}{s} \rfloor + 1
  1. For each output position (i, j), extract the p x p window and take the maximum:
out[i][j]=max0a<p,  0b<pX[is+a][js+b]\text{out}[i][j] = \max_{0 \le a < p,\; 0 \le b < p} X[i \cdot s + a][j \cdot s + 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, stride = 2

Output:

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

The 4x4 input is divided into four non-overlapping 2x2 windows. The max of each window: top-left max(1,2,5,6)=6, top-right max(3,4,7,8)=8, bottom-left max(9,10,13,14)=14, bottom-right max(11,12,15,16)=16.

Input:

X = [[1,5,3],[4,2,6],[7,8,0]], pool_size = 2, stride = 1

Output:

[[5, 6], [8, 8]]

With stride 1, the 2x2 window slides by 1 each step, producing overlapping windows. Top-left max(1,5,4,2)=5, top-right max(5,3,2,6)=6, bottom-left max(4,2,7,8)=8, bottom-right max(2,6,8,0)=8.

Hint 1

Compute output dimensions first: out_h = (H - pool_size) // stride + 1. Then use four nested loops: two for output positions (i, j) and two for positions within the pooling window (a, b). Track the maximum in each window.

Hint 2

The input element for output position (i, j) and window offset (a, b) is at X[i * stride + a][j * stride + b]. Initialize max_val to negative infinity for each window.

Requirements

  • Apply 2D max pooling with the given pool size and stride
  • Each output element is the maximum value in its pooling window
  • Handle both overlapping (stride < pool_size) and non-overlapping (stride = pool_size) cases
  • Return the pooled output as a list of lists of floats or ints

Constraints

  • X has at least pool_size rows and pool_size columns
  • pool_size >= 1, stride >= 1
  • Return a list of lists
  • Time limit: 300 ms
Try Similar Problems