Problems
Loading...
1 / 1

Average Pooling 2D

Computer Vision
Medium

Average pooling is a downsampling operation that reduces the spatial dimensions of a feature map by computing the mean value within non-overlapping rectangular regions. Unlike max pooling which selects the strongest activation, average pooling captures the overall presence of features in each region.

Given a 2D matrix and a pool size, apply average 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), compute the mean of all values in the corresponding p × p window:
out[i][j]=1p2a=0p1b=0p1X[ip+a][jp+b]\text{out}[i][j] = \frac{1}{p^2} \sum_{a=0}^{p-1} \sum_{b=0}^{p-1} 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:

[[3.5, 5.5], [11.5, 13.5]]

The 4×4 matrix is divided into four 2×2 windows. The average of each window is: (1+2+5+6)/4=3.5, (3+4+7+8)/4=5.5, (9+10+13+14)/4=11.5, (11+12+15+16)/4=13.5.

Input:

X = [[10,20],[30,40]], pool_size = 2

Output:

[[25.0]]

The entire 2×2 matrix is one pool. The average is (10+20+30+40)/4 = 25.0.

Hint 1

Compute out_h = H // pool_size and out_w = W // pool_size. For each output position (i, j), sum all values in the pool_size × pool_size window starting at (i * pool_size, j * pool_size), then divide by pool_size * pool_size.

Hint 2

Use nested loops: outer loops for output rows and columns, inner loops for the pooling window. Accumulate the sum, then divide by the total number of elements (pool_size ** 2).

Requirements

  • Apply non-overlapping average pooling with stride equal to pool_size
  • Compute the arithmetic mean of all values in 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 of floats

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 floats
  • Time limit: 300 ms
Try Similar Problems