The Column That Doesn't Fit

ConvolutionMedium+20 XP+20

The Column That Doesn't Fit

Pooling is the one stage of a convolutional network with nothing to learn in it. A small window sweeps the grid, and every stop is replaced by a single summary number — either the largest value lying under the window, or the mean of the values lying under it.

Task: write pool2d(grid, size, stride, mode), returning the pooled grid with every value rounded to 4 decimal places.

  • grid is a rectangular list of rows of numbers, and size is the side of the square window.
  • stride is how far the window moves between stops, applied the same way across and down.
  • mode is "max" (keep the largest value in the window) or "avg" (keep the mean of the window).
  • The window may never hang off the edge. Only stops where the whole window sits on real values are visited, so a side of length nnn offers ⌊(n−size)/stride⌋+1\lfloor (n - \texttt{size}) / \texttt{stride} \rfloor + 1⌊(n−size)/stride⌋+1 of them, and a leftover row or column that cannot hold a full window is never looked at.
  • The windows are not obliged to tile. stride == size sets them edge to edge, and a smaller stride makes consecutive windows overlap — legal, and it must work.

The pooling layer you will actually meet is size = 2, stride = 2, which halves each side and so quarters the number of positions. Everything else here is that same sweep with the knobs turned — and it is the identical sweep a convolution performs, which is why the two shrink a grid by exactly the same formula.

12
40
180
90
55
20
210
130
200
160
30
45
175
190
60
25
keeps the largest
55

Examples

grid = [[1, 3, 2, 4], [5, 6, 7, 8], [9, 2, 1, 0], [4, 4, 3, 3]]
size = 2
stride = 2
mode = "max"
returns [[6.0, 8.0], [9.0, 3.0]]
grid = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]]
size = 2
stride = 2
mode = "avg"
returns [[4.0, 6.0]]
grid = [[1, 2, 3], [4, 5, 6], [7, 8, 10]]
size = 3
stride = 3
mode = "avg"
returns [[5.1111]]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run