Image-recognition networks often shrink an image by pooling: a size × size window slides over the grid, moving stride cells at a time, and each window position is replaced by one number, either the largest value in the window (how = "max") or the mean of its values (how = "mean").
Windows start at the top-left corner, at rows 0, stride, 2 * stride, ... and the same columns, and only windows that fit completely inside the grid are used. The output has one row per window row and one value per window column.
Write pool(grid, size, stride, how) that returns the pooled grid.
Examples
Input: grid = [[1, 2, 5, 6],
[3, 4, 7, 8],
[9, 1, 0, 2],
[5, 3, 4, 4]], size = 2, stride = 2, how = "max"
Output: [[4, 8],
[9, 4]]
Input: same grid, size = 2, stride = 2, how = "mean"
Output: [[2.5, 6.5],
[4.5, 2.5]]
Input: grid = [[1, 2, 3],
[4, 5, 6]], size = 2, stride = 1, how = "max"
Output: [[5, 6]]
Explanation: Windows start at columns 0 and 1; a window at row 1 would not fit.
If the grid is smaller than one window, return []. The setup defines noise_image(rows, cols, seed), a random grid of values from 0 to 255 you can try with Run. Floats are compared with a tolerance of 1e-6.
Constraints
1 <= size,1 <= stride; the grid is rectangular with at most250 000valueshowis"max"or"mean"
Goals
- Cut a square window out of a grid with one slice of rows and one slice per row
- Flatten a window into its values with a two-clause comprehension
- Produce a nested list of results with a nested comprehension over window starts