Classifier heads
Convert convolutional feature maps into per-example channel features before Dense layers.
Keras · Class
GlobalAveragePooling2D averages each channel across an image feature map's height and width. It normally returns one value per channel per example, or preserves singleton spatial axes when keepdims=True.
GlobalAveragePooling2D averages each channel across the two spatial axes of a 4D image-feature tensor. By default it removes those axes, leaving one value per channel; setting keepdims=True retains them as singleton dimensions, which can help preserve convolution-compatible rank.
keras.layers.GlobalAveragePooling2D(data_format=None, keepdims=False, **kwargs)| Name | Type | Description |
|---|---|---|
data_format | string or None | Input dimension ordering: either "channels_last" or "channels_first". If omitted, the Keras configuration determines it. |
keepdims | boolean | Whether to retain the reduced spatial axes with length 1; defaults to False. |
**kwargs | keyword arguments | Additional base-layer keyword arguments. |
For keepdims=False, a 2D tensor shaped (batch_size, channels). For keepdims=True, a 4D tensor shaped (batch_size, 1, 1, channels) with channels_last or (batch_size, channels, 1, 1) with channels_first.
import numpy as np
import keras
x = np.random.rand(2, 4, 5, 3).astype("float32")
y = keras.layers.GlobalAveragePooling2D()(x)
print(y.shape) # (2, 3)A channels-last batch is reduced across height and width, producing one value per channel for each example.
Convert convolutional feature maps into per-example channel features before Dense layers.
Reduce spatial dimensions without specifying a pooling window or stride.
Keep rank compatible with convolution-style tensors while replacing spatial dimensions by 1.
It performs global mean pooling over height and width independently for every channel. With the default keepdims=False, an input shaped (batch, height, width, channels) becomes (batch, channels).
Follow-up: What changes with keepdims=True? The spatial axes remain, each with length 1, so channels_last output is (batch, 1, 1, channels), or channels_first output is (batch, channels, 1, 1).
data_format selects the dimension ordering. channels_last uses (batch, height, width, channels), whereas channels_first uses (batch, channels, height, width).
Follow-up: How is the default selected? If data_format is omitted, Keras uses the image_data_format value from the Keras configuration file.
The constructor is keras.layers.GlobalAveragePooling2D(data_format=None, keepdims=False, **kwargs). data_format controls layout, and keepdims controls whether singleton spatial dimensions are retained.
Follow-up: How would you verify the resulting shape? Apply the layer to a representative NumPy array and inspect the output shape, as in the documentation example.
GlobalAveragePooling1DGlobalAveragePooling3DAveragePooling2D