Deep LearningDeep Learning Comparison Series
Global Average Pooling vs Flattening
Question 311 of 314 · Updated
On this page
- 1. The two approaches
- 2. Numerical example
- 3. Mathematical operations
- 4. Tensor shapes
- 5. Parameter-count example
- 6. Spatial information and location
- 7. Translation sensitivity and generalization
- 8. PyTorch implementations
- 9. Computational and memory considerations
- 10. Common mistakes
- 11. When should you use each?
- 12. Quick comparison
Global average pooling (GAP) turns each feature map into one average value; flattening keeps every spatial activation as a separate feature. Both convert CNN feature maps into vectors for a classifier, but differ in information retained, classifier size, and sensitivity to object position.
1. The two approaches#
A convolutional network produces a tensor commonly shaped (N, C, H, W): batch size, channels, height, and width.
- Global average pooling: averages all H × W values independently in each channel. Each channel becomes one number.
- Flattening: reshapes the C × H × W values into a vector without averaging or discarding them.
Both are often followed by a fully connected (linear) classification layer.
2. Numerical example#
Consider one channel with a 2 × 2 feature map:
GAP calculates (1 + 3 + 5 + 7) / 4 = 4, so this channel becomes [4].
Flattening rearranges the same values into [1, 3, 5, 7]. No values are averaged away.
With two channels:
GAP returns [4, 5]: one mean per channel. Flattening returns [1, 3, 5, 7, 2, 4, 6, 8] (assuming channel-first contiguous ordering).
GAP is compact. Flattening preserves individual spatial responses.
3. Mathematical operations#
For feature map X in channel c, with height H and width W, global average pooling computes:
The output has one scalar for each channel.
Flattening performs a reshape:
It does not perform a numerical reduction. Every activation remains an individual vector element.
4. Tensor shapes#
For input feature tensor (N, C, H, W):
- GAP with output size 1 produces (N, C, 1, 1), then flattening the last dimensions gives (N, C).
- Direct flattening produces (N, C × H × W).
Example: a CNN outputs (32, 128, 7, 7).
- GAP: (32, 128, 1, 1), then (32, 128).
- Flatten: (32, 6272).
For 10 classes, the first linear layer receives 128 inputs with GAP and 6,272 inputs with flattening.
5. Parameter-count example#
A linear layer with D input features and K output classes has:
The extra K values are biases.
For 128 channels, a 7 × 7 feature map, and 10 classes:
GAP followed by Linear(128, 10):
Flatten followed by Linear:
The flattened classifier has 61,440 more parameters, about 48.6 times as many. GAP itself has no trainable parameters. Flattening also has no trainable parameters; the difference appears in the following dense layer.
A hidden fully connected layer after flattening can make the input-dependent parameter count much larger. Fewer parameters can reduce memory and overfitting risk, but do not guarantee better accuracy.
6. Spatial information and location#
Flattening retains spatial layout implicitly. Each position maps to a distinct vector index, allowing a dense classifier to learn different weights for activations at different positions. This can help when object location or arrangement matters, but ties the classifier's input size to feature-map dimensions.
GAP discards within-channel spatial arrangement. Two feature maps with the same values in different spatial positions have the same global average. GAP retains each channel's average strength, not where activations occurred.
This is a deliberate information bottleneck. It can encourage a classifier to use the presence of learned features across the image rather than memorize exact positions. But it can be harmful for tasks requiring localization, geometry, or fine spatial relationships.
7. Translation sensitivity and generalization#
GAP is invariant to a permutation of spatial positions within a channel: moving the same activation values around without changing their sum leaves the average unchanged. In practice, a translated input can still change convolutional features because of boundaries, padding, receptive fields, and stride. GAP does not make an entire CNN perfectly translation-invariant.
Flattening is generally more position-sensitive: moving a response to another spatial cell changes a different vector element, which may be multiplied by a different classifier weight.
Generalization trade-off:
- GAP uses fewer classifier parameters and can reduce the opportunity to overfit to fixed spatial positions.
- Flattening gives the classifier more capacity to learn location-specific patterns, but increases parameter count and may overfit when data is limited.
- Neither guarantees better generalization. Dataset size, object alignment, architecture, augmentation, and task requirements matter.
8. PyTorch implementations#
Global average pooling
PYTHONimport torch import torch.nn as nn x = torch.tensor([ [[[1.0, 3.0], [5.0, 7.0]], [[2.0, 4.0], [6.0, 8.0]]] ]) # (N=1, C=2, H=2, W=2) gap = nn.AdaptiveAvgPool2d((1, 1)) pooled = gap(x) features = torch.flatten(pooled, 1) print(pooled.shape) # torch.Size([1, 2, 1, 1]) print(features) # tensor([[4., 5.]])
Flattening
PYTHONflat_features = torch.flatten(x, start_dim=1) print(flat_features.shape) # torch.Size([1, 8]) print(flat_features) # tensor([[1., 3., 5., 7., 2., 4., 6., 8.]])
A compact classifier using GAP:
PYTHONclass GAPClassifier(nn.Module): def __init__(self, num_classes=10): super().__init__() self.features = nn.Sequential( nn.Conv2d(3, 128, kernel_size=3, padding=1), nn.ReLU(), ) self.pool = nn.AdaptiveAvgPool2d(1) self.classifier = nn.Linear(128, num_classes) def forward(self, x): x = self.features(x) x = self.pool(x) x = torch.flatten(x, 1) return self.classifier(x)
A flatten-based alternative for a fixed 32 × 32 input (after the feature extractor):
PYTHONclass FlattenClassifier(nn.Module): def __init__(self, num_classes=10): super().__init__() self.features = nn.Sequential( nn.Conv2d(3, 128, kernel_size=3, padding=1), nn.ReLU(), nn.AdaptiveAvgPool2d((7, 7)), ) self.classifier = nn.Linear(128 * 7 * 7, num_classes) def forward(self, x): x = self.features(x) x = torch.flatten(x, 1) return self.classifier(x)
The adaptive 7 × 7 layer in the second example fixes feature-map size before flattening, so the linear layer has a known input dimension. Without such a step, changing image dimensions can break a flatten-based classifier.
9. Computational and memory considerations#
- GAP reduces C × H × W activations to C values per example before the classifier.
- Flattening preserves all C × H × W values for the next layer.
- The dense layer after flattening can have many more weights, increasing parameter storage, optimizer state, gradient memory, and matrix multiplication work.
- GAP requires summing and scaling each channel's spatial values; it is not computationally free, but the resulting classifier is often much smaller.
- The convolutional backbone may dominate total model cost, so compare end-to-end latency and memory rather than only classifier weights.
nn.AdaptiveAvgPool2d(1) can produce a 1 × 1 output for varying input spatial sizes, allowing the same GAP classifier to accept different image resolutions (provided the rest of the model supports them).
10. Common mistakes#
- Confusing GAP with local average pooling: GAP averages the entire spatial map of each channel; local average pooling averages smaller windows.
- Flattening the batch dimension: Use torch.flatten(x, start_dim=1) or torch.flatten(x, 1) so each example remains separate.
- Assuming GAP has trainable parameters: Standard adaptive average pooling has no learned weights.
- Assuming flattening itself adds parameters: The following Linear layer creates the parameters.
- Forgetting the classifier input size: Linear must receive C for GAP or C × H × W for flattening.
- Assuming GAP preserves location: It removes spatial arrangement within each channel.
- Assuming GAP guarantees translation invariance or better accuracy: It reduces position dependence at the head, but the complete CNN is not perfectly invariant.
- Ignoring input resolution: A flatten-based dense head usually expects a fixed feature-map size; GAP is more flexible spatially.
11. When should you use each?#
Choose global average pooling when:
- You are building an image-level classifier.
- Presence and strength of learned features matter more than exact location.
- You want a compact classifier with fewer dense parameters.
- You need the classifier head to handle varying spatial input sizes.
Choose flattening when:
- Spatial arrangement and position are useful to the prediction.
- Input or feature-map size is fixed and controlled.
- You have enough data and regularization to support a larger dense head.
- A later dense network needs individual spatial activations.
For object detection, segmentation, pose estimation, and other spatially precise tasks, do not collapse all spatial dimensions too early. Keep feature maps or use suitable multi-scale spatial heads. A hybrid design can preserve a small spatial grid with adaptive pooling (for example, 2 × 2 or 7 × 7) before flattening.
Evaluate both choices on a held-out set. Compare accuracy, calibration, robustness to object shifts, parameter count, latency, and memory. The right choice follows from the information the task needs, not a universal rule.
12. Quick comparison#
| Property | Global average pooling | Flattening |
|---|---|---|
| Operation | Mean over H × W per channel | Reshape all values |
| Output features | C | C × H × W |
| Spatial layout | Discarded within each channel | Retained by vector position |
| Dense-head parameters | Usually much fewer | Usually many more |
| Input spatial size | Flexible with adaptive GAP | Usually fixed for a dense head |
| Position sensitivity | Lower at pooled representation | Higher |
| Best suited to | Image-level classification | Tasks where spatial layout helps |
Key takeaway: GAP compresses every channel into one average, producing a small and spatially tolerant feature vector. Flattening preserves every location, giving the classifier more spatial detail and more parameters. Choose based on whether exact spatial arrangement is useful for your task.
References
- 1.PyTorch AdaptiveAvgPool2d documentationdocs.pytorch.org
- 2.PyTorch Flatten documentationdocs.pytorch.org
- 3.PyTorch Linear documentationdocs.pytorch.org
- 4.Network in Networkarxiv.org
- 5.Going Deeper with Convolutionsarxiv.org
Related questions
Explore other topics:Machine LearningLarge Language Models