Deep learning: Max and average pooling

Shrink a feature map with pooling.

What to build

A program that applies max or average pooling to a feature map.

Requirements

  • The mode is max or avg; the window is k × k and moves s positions at a time.
  • Print the output rows, values written with Python's g format.

Input

Line 1: height, width, mode, k and s. Then the rows.

Output

One line per output row.

Constraints

Maps up to 50 × 50.

Example

Input:

4 4 max 2 2
1 3 2 1
4 6 5 0
7 2 8 1
0 1 3 9

Output:

6 5
7 9

Why it works

Each window is replaced by one number that summarizes it, so the map gets smaller while keeping the strongest (or typical) response in each region.

Examples

Example 1 · Input
4 4 max 2 2
1 3 2 1
4 6 5 0
7 2 8 1
0 1 3 9
Expected output
6 5
7 9
Example 2 · Input
2 2 avg 2 2
1 2
3 4
Expected output
2.5

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

The output has ⌊(n − k) / s⌋ + 1 rows and columns.

Hint 2

Each output is the max (or the mean) of the k × k window starting at (row × s, column × s).

Solution

Show one correct solution (try it yourself first)
h, w, mode, k, s = input().split()
h, w, k, s = int(h), int(w), int(k), int(s)
fmap = [list(map(float, input().split())) for _ in range(h)]
for r in range((h - k) // s + 1):
    out = []
    for c in range((w - k) // s + 1):
        window = [fmap[r * s + a][c * s + b] for a in range(k) for b in range(k)]
        value = max(window) if mode == "max" else sum(window) / len(window)
        out.append(f"{value:g}")
    print(" ".join(out))

Lesson: Pooling and convolutional networks →