Max pooling divides a feature map into small windows and reduces its height and width by keeping only the maximum in each window. In a convolutional neural network (CNN), it is placed after convolutional layers and activation functions, passing only the strongly activated features to the next layer while reducing computation. It has no learnable parameters.
The most common setting slides a 2×2 window by 2 pixels at a time (stride 2). In the example in the top figure, a 4×4 input is divided into four 2×2 windows, and the maximum of each is taken to produce a 2×2 output.
Window (position)
Values in the window
Output (maximum)
Top left
1, 3, 4, 6
6
Top right
2, 1, 5, 0
5
Bottom left
3, 1, 0, 2
3
Bottom right
1, 2, 4, 3
4
As a formula, the output value at position (i,j) is the maximum within the corresponding window Ri,j.
yi,j,c=(p,q)∈Ri,jmaxxp,q,c
Here x is the input feature map, y is the output, and c is the channel. Each channel is computed separately, so the number of channels does not change.
With window size k, stride s and no padding, the output height (width) is:
Hout=⌊sH−k⌋+1
For example, with H=224, k=2 and s=2, Hout=112: height and width are halved, and the number of pixels becomes 1/4.
Why use it?
There are three reasons to use max pooling.
It reduces computation and lets later layers see a wider area: Halving the height and width cuts the computation of the following convolutional layers to about 1/4. Also, the same 3×3 filter covers a wider area of the original image on the reduced feature map.
It becomes robust to small shifts in position: Even if the position of the maximum moves slightly within a window, the output does not change. For example, in the top-left window of the top figure, the output remains 6 even if the 6 is at a different position in the window. Summarizing nearby features in this way to reduce the effect of small changes is a major purpose of pooling (Boureau et al., 2010).
It keeps "whether the feature is present": Averaging mixes strong responses with the weak responses around them and dilutes them. Taking the maximum keeps the strength intact as long as the feature responds strongly somewhere in the window. From a theoretical analysis, Boureau et al. state that max pooling is particularly suited to discriminating features that rarely activate (sparse features).
The idea of taking the maximum of nearby responses was also used in models of the brain's visual cortex (Riesenhuber and Poggio, 1999). In CNNs, Ranzato et al. (2007) and others used max pooling, and many representative CNNs later adopted it, including AlexNet (2012) and VGG (2015).
AlexNet used overlapping pooling (3×3 window, stride 2). Compared with non-overlapping 2×2 windows with stride 2, it reported top-1 and top-5 error rates on ImageNet lower by 0.4 and 0.3 points respectively, and slightly less overfitting.
Gradient flow during training
Max pooling has no learnable parameters, so in backpropagation it simply passes gradients to the previous layer. It does so as follows.
During the forward pass, remember the position where the maximum was taken in each window.
During the backward pass, pass the output gradient as is only to the position of the maximum, and pass 0 to the other positions in the window.
In the example in the top figure, the gradient arriving at the output "6" goes only to row 2, column 2 of the input (the position with value 6), and the gradients at the positions of 1, 3 and 4 in the same window are 0. This expresses the fact that only the position of the maximum affects the output, so changing the other positions slightly does not change the output.
PyTorch's nn.MaxPool2d(return_indices=True) returns the positions of the maxima. Combined with nn.MaxUnpool2d, the maxima of the reduced feature map can be put back at their original positions (positions other than the maxima become 0).
Comparison with other pooling methods and how to choose
The table lists max pooling and commonly compared downsampling methods from the same viewpoints.
Method
How window values are summarized
Learnable parameters
Main use
Max pooling
Takes the maximum
None
Reducing height and width inside a CNN (VGG, etc.)
Average pooling
Takes the average
None
Early CNNs (the subsampling layers of LeNet-5 multiply the window sum by a learned coefficient and add a bias)
Picks one value with probability proportional to its magnitude
None
Regularization during training
Strided convolution
Multiplies by weights and sums
Yes
A replacement for max pooling (Springenberg et al., 2015)
With average pooling, the output for the example in the top figure is 3.5, 2, 1.5, 2.5. Compared with max pooling (6, 5, 3, 4), average pooling keeps the overall trend of each window, while max pooling keeps the strongest response.
Rough guidelines for choosing:
To reduce height and width inside a CNN: Start with max pooling (2×2, stride 2). It adds no parameters and has been the standard choice in many models.
To turn the feature map into a single vector right before classification: Use global average pooling.
To learn the downsampling as well: Use strided convolution. Springenberg et al. (2015) showed that replacing max pooling with convolutions with a larger stride does not reduce accuracy on several image recognition tasks.
Max pooling discards where in the window the feature was. For tasks where fine positions matter (such as segmentation, which finds object outlines pixel by pixel), downsampling too much reduces accuracy. Also, robustness to shifts only covers small shifts that stay within a window. If a shift moves the maximum into the neighboring window, the output changes.
PyTorch example
▶Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
# Input/output example (same values as the top figure). Shape is [batch, channels, height, width]
x = torch.tensor([[[[1., 3., 2., 1.],
[4., 6., 5., 0.],
[3., 1., 1., 2.],
[0., 2., 4., 3.]]]], requires_grad=True)
y = F.max_pool2d(x, kernel_size=2, stride=2)
print(y) # 2×2: 6, 5 / 3, 4
print(F.avg_pool2d(x, kernel_size=2, stride=2)) # For comparison: 3.5, 2.0 / 1.5, 2.5
# Backward pass: gradients go only to the positions of the maxima (6, 5, 3, 4)
y.sum().backward()
print(x.grad) # 1 at the positions of the maxima, 0 elsewhere
'''
Image classification on MNIST (convolution → ReLU → max pooling, twice)
'''
# Hyperparameters
batch_size = 64 # Batch size
epochs = 3 # Number of epochs
learning_rate = 1e-3 # Learning rate
# 'cuda' if available, 'mps' on Apple Silicon, otherwise 'cpu'
device = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])
train_dataset = datasets.MNIST(root='./data', train=True, download=True, transform=transform)
test_dataset = datasets.MNIST(root='./data', train=False, download=True, transform=transform)
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=batch_size)
class SmallCNN(nn.Module):
def __init__(self, num_classes=10):
super().__init__()
self.features = nn.Sequential(
nn.Conv2d(1, 32, kernel_size=3, padding=1), # [B, 1, 28, 28] -> [B, 32, 28, 28]
nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2), # -> [B, 32, 14, 14]
nn.Conv2d(32, 64, kernel_size=3, padding=1), # -> [B, 64, 14, 14]
nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2), # -> [B, 64, 7, 7]
nn.Flatten(),
)
self.classifier = nn.Linear(64 * 7 * 7, num_classes)
def forward(self, x):
return self.classifier(self.features(x))
model = SmallCNN().to(device)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
# Training
for epoch in range(epochs):
model.train()
for images, labels in train_loader:
images, labels = images.to(device), labels.to(device)
optimizer.zero_grad()
loss = criterion(model(images), labels)
loss.backward()
optimizer.step()
# Evaluation
model.eval()
correct = 0
total = 0
with torch.no_grad():
for images, labels in test_loader:
images, labels = images.to(device), labels.to(device)
predicted = model(images).argmax(dim=1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print(f"Test Accuracy: {100 * correct / total:.2f}%")
FAQ
Q. How should the window size and stride be chosen?
A.
A 2×2 window with stride 2 is the most common, and VGG uses this setting. A slightly overlapping 3×3 window with stride 2 is also used in AlexNet and in the first part of ResNet. Both roughly halve the height and width.
Q. Which is better, max pooling or average pooling?
A.
It depends on the task and the nature of the features. According to the analysis by Boureau et al. (2010), max pooling suits sparse features that rarely activate. A common combination is max pooling inside the CNN and global average pooling right before classification.
Q. Does max pooling have learnable parameters?
A.
No. The window size and stride are hyperparameters chosen by hand. To learn the downsampling as well, use strided convolution.