CodeBlanks Logo Icon CodeBlanks

MaxPool2d

MaxPool2d reduces image size and preserves important features.

MaxPool2d

Pooling shrinks the feature map. nn.MaxPool2d(2) takes the largest value from every 2×2 region: height and width are halved, the channel count doesn't change. It has no parameters:

havuz = nn.MaxPool2d(2)
x = torch.tensor([[[[1., 3., 2., 4.],
                    [5., 6., 1., 2.],
                    [7., 2., 9., 0.],
                    [1., 8., 3., 4.]]]])
print(havuz(x).tolist())   # [[[[6.0, 4.0], [8.0, 9.0]]]]

Pooling gives robustness to small shifts and reduces the computation of the following layers.

Average and global pooling

nn.AvgPool2d takes the region's mean. Modern networks usually use global average pooling at the end: it reduces each channel to a single number, so the model becomes independent of the input size:

gap = nn.AdaptiveAvgPool2d(1)
print(gap(torch.zeros(8, 512, 7, 7)).shape)    # torch.Size([8, 512, 1, 1])
print(gap(torch.zeros(8, 512, 13, 9)).shape)   # still (8, 512, 1, 1)

AdaptiveAvgPool2d takes the target output size and works out the needed window itself.

Practice Pooling

Apply nn.MaxPool2d(2) and nn.AvgPool2d(2) to the given 4×4 image; print the two results with tolist() on separate lines.

Starter code

model.py
import torch
from torch import nn

x = torch.tensor([[[[1., 3., 2., 4.], [5., 6., 1., 2.], [7., 2., 9., 0.], [1., 8., 3., 4.]]]])

# buraya yaz

Sample solution

model.py
import torch
from torch import nn

x = torch.tensor([[[[1., 3., 2., 4.], [5., 6., 1., 2.], [7., 2., 9., 0.], [1., 8., 3., 4.]]]])

print(nn.MaxPool2d(2)(x).tolist())
print(nn.AvgPool2d(2)(x).tolist())

Expected output

[[[[6.0, 4.0], [8.0, 9.0]]]]
[[[[3.75, 2.25], [4.5, 4.0]]]]

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the shape after applying <code>MaxPool2d(2)</code> to a tensor of shape (8, 32, 16, 16)?

  • (8, 16, 16, 16)
  • (4, 32, 16, 16)
  • (8, 32, 14, 14)
  • (8, 32, 8, 8) Correct answer

Explanation: Only the spatial dimensions are halved.

2 Apply 2×2 max pooling.

Question
havuz = nn.____(2)
Answer
havuz = nn.MaxPool2d(2)

Explanation: MaxPool2d takes each region's largest value.

3 Match the poolings.

Term Meaning
MaxPool2d(2) Region's maximum
AvgPool2d(2) Region's mean
AdaptiveAvgPool2d(1) One value per channel
parameter count 0

All lessons in Advanced