AI Logic

Pooling

Global Average Pooling (GAP)

Updated:

How global average pooling works. Left: the overall flow of a classification network, where convolution and ReLU layers repeat, global average pooling turns h × w × C into 1 × 1 × C, and a fully connected layer maps it to classes. Right: a numerical example that turns a 3-channel 4 × 4 input into the per-channel averages 2.75, 0.75 and 0.625. Bottom: a comparison of the weight counts of the classification layer (25,088,000 when flattening into a fully connected layer, 512,000 after global average pooling)

What is global average pooling?

Global average pooling (GAP) averages each channel of a feature map over every spatial position, reducing it to a single value. An h×w×Ch \times w \times C feature map becomes a vector of length CC. It has no learnable parameters.

Whereas ordinary pooling such as max pooling summarizes values within small windows, global average pooling is average pooling with the window widened to the whole feature map. In the example in the top figure, a 3-channel 4 × 4 input yields three values: the per-channel averages (2.75, 0.75, 0.625).

Lin et al. proposed global average pooling in 2013 in the Network In Network (NIN) paper, as a replacement for the fully connected layers at the end of a CNN. CNNs of that time flattened the feature map of the last convolutional layer into a vector and fed it into fully connected layers, but those layers had many weights and were prone to overfitting. Global average pooling spread as a way to connect feature maps to classification without any weights, and many later CNNs, including GoogLeNet and ResNet, use it right before classification.

Computation and usage

Let fk(x,y)f_k(x, y) be the feature map of channel kk (of size h×wh \times w). The output of global average pooling is:

Fk=1hw∑x=1w∑y=1hfk(x,y),k=1,…,CF_k = \frac{1}{h w} \sum_{x=1}^{w} \sum_{y=1}^{h} f_k(x, y), \qquad k = 1, \dots, C

The way it is used differs slightly between the original NIN and the common form adopted later.

Usage in NIN (no fully connected layer)

  1. Set the number of output channels of the last layer equal to the number of classes (10 channels for CIFAR-10).
  2. Apply global average pooling to each channel's feature map, producing a vector whose length equals the number of classes.
  3. Feed that vector directly into softmax to obtain the probability of each class.

In this form, the feature map of channel kk is trained to become a map of "where in the image class kk appears" (a confidence map, in the paper's words).

Common usage (one fully connected layer after global average pooling)

GoogLeNet added one fully connected layer after global average pooling. The paper says this makes it easier to fine-tune for other label sets and does not affect accuracy much. ResNet also ends with "global average pooling and a 1000-way fully connected layer with softmax". In this form, the number of channels of the last convolutional layer does not need to match the number of classes.

The output size depends only on CC, not on the spatial size h×wh \times w of the feature map. A network that ends with global average pooling can therefore take images of a different size from those used in training as they are. When the feature map is fed directly into a fully connected layer, changing the input size changes the length of that layer's input.

Why it can replace fully connected layers

The NIN paper lists three advantages of global average pooling.

  1. Less overfitting: Global average pooling itself has no learnable parameters, so no overfitting occurs in this layer. When the last feature map is 7×7×5127 \times 7 \times 512 and there are 1000 classes, flattening it into a fully connected layer requires 7⋅7⋅512⋅1000=25,088,0007 \cdot 7 \cdot 512 \cdot 1000 = 25{,}088{,}000 weights, while a fully connected layer after global average pooling needs only 512⋅1000=512,000512 \cdot 1000 = 512{,}000 (excluding biases).
  2. Clear correspondence between feature maps and classes: In the NIN form, each channel corresponds directly to a class, so the last feature maps can be read as "per-class confidence maps". Fully connected layers tend to be a "black box" whose computation between feature maps and outputs is hard to see.
  3. Robustness to spatial translation: Because it sums up all spatial information, the output barely changes when an object moves slightly within the image.

The paper calls global average pooling a "structural regularizer". Unlike Dropout, it adds nothing during training; instead, the structure of the network itself forces the feature maps to become confidence maps of the classes.

In relation to fully connected layers, global average pooling is also a kind of linear transformation that "multiplies the flattened feature map by a matrix". The difference lies in the matrix: a fully connected layer learns every entry, whereas the matrix of global average pooling has a fixed (block-diagonal) form with 1/(hw)1/(hw) at each channel's positions and is not learned.

Experimental results

CIFAR-10 test error compared with fully connected layers (Table 5 of the NIN paper)

Only the final part of NIN is swapped.

Classification layerTest error
Fully connected11.59%
Fully connected + Dropout10.88%
Global average pooling10.41%

The fully connected layer without Dropout performed worst, and global average pooling performed best.

The paper also compares them on a conventional CNN (three convolutional layers and one locally connected layer). The error was 17.56% with fully connected layers, 15.99% with Dropout added, and 16.46% with global average pooling. That is more than one point better than fully connected layers alone, but slightly short of Dropout. The paper suggests this may be because building class confidence maps is too hard for ordinary convolutional layers (with linear filters).

Results for NIN as a whole (with global average pooling and Dropout, test error)

DatasetError
CIFAR-1010.41% (8.81% with data augmentation)
CIFAR-10035.68%
SVHN2.35%
MNIST0.47%

GoogLeNet (ImageNet)

The GoogLeNet paper reports that switching from fully connected layers to average pooling improved top-1 accuracy by about 0.6%. It also notes, however, that Dropout remained essential even after the fully connected layers were removed.

Mapping the evidence for a decision: CAM

A network that ends with global average pooling can map the image regions used for a class decision without any additional training. Zhou et al. showed this in 2016 as the class activation map (CAM).

Place one fully connected layer after global average pooling and let wkcw_k^c be its weights for class cc. In the score of class cc, the order of averaging (summing, in the paper) and the weighted sum can be swapped.

Sc=∑kwkcFk=∑x,y∑kwkcfk(x,y)S_c = \sum_k w_k^c F_k = \sum_{x, y} \sum_k w_k^c f_k(x, y)

Building a map of the per-position values

Mc(x,y)=∑kwkcfk(x,y)M_c(x, y) = \sum_k w_k^c f_k(x, y)

shows how much each position contributed to the score of class cc. Upsampling it to the image size highlights the regions that served as evidence for the decision.

The CAM paper also compares global average pooling (GAP) with global max pooling (GMP). Classification performance was similar (top-1 errors of 35.0% and 35.6% with a modified GoogLeNet), but GAP localized objects better (top-5 localization errors of 43.0% and 45.3%). The paper explains that averaging requires finding all the discriminative parts of an object, while the maximum depends only on the single most discriminative spot.

This idea carries over to Grad-CAM, which extends it to networks without a fully connected layer at the end.

Caveats

All spatial information is lost. Global average pooling collapses the spatial dimensions by averaging, so placing it in the middle of a task that needs to know "what is where" (localizing objects, classifying each pixel, and so on) discards the information that is needed. Use it only at the end of classification or where a summary of the whole input is wanted (such as the part that computes per-channel weights).

  • Small objects and weak responses get diluted: Because it takes an average, a feature that responds strongly in only part of the image is mixed with small values at other positions and shrinks. When what matters is "whether" a feature is present, global max pooling is also a candidate.
  • The last layers need enough capacity: In the NIN paper, ending a conventional CNN with global average pooling was slightly worse than a fully connected layer with Dropout. In the CAM paper as well, removing the fully connected layers of AlexNet in favor of global average pooling reduced accuracy, and two convolutional layers were added to compensate. When removing fully connected layers, consider strengthening the layers before them.
  • Behavior is the same in training and inference: There are no parameters and no randomness, so model.train() and model.eval() give the same result.
  • In PyTorch, use nn.AdaptiveAvgPool2d(1): It specifies the output size (1 × 1), so the same layer works even when the input height and width change. x.mean(dim=(2, 3)) gives the same values.

Comparison with other methods and how to choose

The table lists ways to connect feature maps to classification, along with similar pooling methods, from the same viewpoints.

MethodHow values are summarizedLearnable parametersOutput sizeMain use
Global average poolingAverage over the whole feature mapNoneCCRight before classification (NIN, GoogLeNet, ResNet, etc.)
Global max poolingMaximum over the whole feature mapNoneCCWhen only the strongest response matters
Flatten + fully connected layerA separate weight for every positionhwC×h w C \times number of outputsNumber of outputsEarly CNNs (AlexNet, VGG, etc.)
Max poolingMaximum within each small windowNoneFeature map with reduced height and widthDownsampling inside the network
Spatial pyramid poolingSummarizes over grids at several levelsNoneNumber of grid cells × CCFixed-length output from inputs of different sizes, keeping some spatial information

Global average pooling is also used inside networks as a component that captures "the state of the whole image". For example, the SE block of SENet, CondConv, and dynamic convolution gather information from the whole image with global average pooling and compute weights from it.

Rough guidelines for choosing:

  • At the end of a classification network: Global average pooling followed by one fully connected layer is the standard. It has few weights and accepts any input size.
  • To see the evidence for a decision as a map: With the global average pooling + fully connected layer form, CAM can be applied as is.
  • To get a fixed length while keeping some spatial information: Consider spatial pyramid pooling.
  • To reduce height and width inside the network: Use max pooling or strided convolution instead of global average pooling.

PyTorch example

Show code
python
import torch
import torch.nn as nn

# Global average pooling: nn.AdaptiveAvgPool2d(1) in PyTorch (makes the output 1 × 1)
gap = nn.AdaptiveAvgPool2d(1)

# Same values as the top figure (3 channels × 4 × 4). Shape is [batch, channels, height, width]
x = torch.tensor([[
  [[2., 4, 3, 1], [5, 6, 4, 2], [3, 5, 2, 1], [1, 2, 1, 2]],
  [[0., 1, 0, 0], [1, 3, 2, 0], [0, 2, 1, 0], [0, 0, 0, 2]],
  [[1., 0, 2, 1], [0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1]],
]])
print(gap(x).flatten())       # tensor([2.7500, 0.7500, 0.6250])
print(x.mean(dim=(2, 3)))     # Same values (mean over height and width)


# End of a classification network: global average pooling → fully connected layer (the ResNet form)
class Classifier(nn.Module):
  def __init__(self, num_classes=10):
    super().__init__()
    self.features = nn.Sequential(
      nn.Conv2d(3, 64, 3, padding=1), nn.BatchNorm2d(64), nn.ReLU(),
      nn.MaxPool2d(2),
      nn.Conv2d(64, 128, 3, padding=1), nn.BatchNorm2d(128), nn.ReLU(),
    )
    self.pool = nn.AdaptiveAvgPool2d(1)      # No parameters
    self.fc = nn.Linear(128, num_classes)     # Only 128 × number of classes weights

  def forward(self, x):
    h = self.pool(self.features(x)).flatten(1)  # [B, 128], regardless of input height and width
    return self.fc(h)


model = Classifier()
model.eval()  # eval() for inference because of BatchNorm; global average pooling itself is the same in train/eval
with torch.no_grad():
  print(model(torch.randn(2, 3, 32, 32)).shape)  # torch.Size([2, 10])
  print(model(torch.randn(2, 3, 64, 48)).shape)  # torch.Size([2, 10]) even with a different size


# NIN form: make the last convolution output one channel per class and feed the averages straight into softmax
nin_head = nn.Sequential(nn.Conv2d(128, 10, kernel_size=1), nn.AdaptiveAvgPool2d(1), nn.Flatten())
print(nin_head(torch.randn(2, 128, 8, 8)).softmax(dim=1).shape)  # torch.Size([2, 10])


# CAM: sum the feature maps weighted by the fully connected layer's weights to get a per-class map
with torch.no_grad():
  feats = model.features(torch.randn(1, 3, 32, 32))           # [1, 128, 16, 16]
  c = model(torch.randn(1, 3, 32, 32)).argmax(dim=1).item()
  cam = torch.einsum("k,bkhw->bhw", model.fc.weight[c], feats)  # M_c(x, y) = Σ_k w_k^c f_k(x, y)
  print(cam.shape)  # torch.Size([1, 16, 16])

FAQ

Q. How does global average pooling differ from average pooling?
A.

Average pooling takes the average within small windows (such as 2 × 2) to reduce height and width, while global average pooling uses the whole feature map as the window and produces one value per channel. Global average pooling can be seen as average pooling whose window is the same size as the feature map.

Q. Is a fully connected layer needed after global average pooling?
A.

It is not required. The original NIN made the last layer have one channel per class and fed the averages straight into softmax. GoogLeNet and ResNet, however, place one fully connected layer after global average pooling. This removes the need to match the number of channels of the last layer to the number of classes and also makes fine-tuning for other classes easier.

Q. Should I use global average pooling or global max pooling?
A.

Classification performance is often similar, and in the CAM paper the difference in error was small. When you want to map the evidence for a decision and locate objects, however, global average pooling, which captures the full extent of an object more easily, gave better results. If in doubt, use the standard global average pooling.

References

  1. M. Lin, Q. Chen, and S. Yan, "Network In Network," ICLR, 2014.
  2. C. Szegedy et al., "Going Deeper with Convolutions," CVPR, 2015.
  3. K. He, X. Zhang, S. Ren, and J. Sun, "Deep Residual Learning for Image Recognition," CVPR, 2016.
  4. B. Zhou, A. Khosla, A. Lapedriza, A. Oliva, and A. Torralba, "Learning Deep Features for Discriminative Localization," CVPR, 2016.
  5. PyTorch Documentation, "torch.nn.AdaptiveAvgPool2d."