Problems
Loading...
1 / 1

Implement Global Average Pooling

Neural Networks
Medium

Implement Global Average Pooling (GAP) over spatial dimensions for channel-first tensors.

Shape Transformations

• If input x has shape (C, H, W) → output is shape (C,)
• If input x has shape (N, C, H, W) → output is shape (N, C)

Mathematical Definition

GAP(x)c=1HWh=1Hw=1Wxc,h,wFor each channel c, average all spatial locations\begin{gather*} \text{GAP}(x)_c = \frac{1}{HW} \sum_{h=1}^{H} \sum_{w=1}^{W} x_{c,h,w} \\ \text{For each channel } c \text{, average all spatial locations} \end{gather*}
Loading visualization...

Examples

Input: x = np.ones((3, 2, 2))

Output: [1., 1., 1.]

Each channel has all 1s, so average = 1

Input: x = np.array([[[[1,2],[3,4]]]]) (shape (1,1,2,2))

Output: [[2.5]]

(1+2+3+4)/4 = 2.5

Requirements

  • NumPy only. Vectorized (no Python loops over elements)
  • Accept (C,H,W) or (N,C,H,W). Raise ValueError otherwise
  • Return dtype float (np.float64 is fine), do not modify the input

Constraints

  • H,W ≥ 1; N,C up to a few hundred
  • Time ≤ 200 ms; Memory ≤ 64 MB
Try Similar Problems