Convert final convolutional feature maps into one vector per example before Dense layers.
Convolutional classifier heads
TensorFlow · Class
A Keras layer that averages each channel across the height and width of 2D feature maps. It can either remove those spatial axes or preserve them as size-one dimensions.
The layer averages each channel across the input's two spatial axes, height and width. By default it removes those axes and returns one value per channel; setting keepdims=True preserves them as dimensions of length one. The data_format setting determines whether channels come last or first.
tf.keras.layers.GlobalAveragePooling2D(
data_format=None, keepdims=False, **kwargs
)| Name | Type | Description |
|---|---|---|
data_format | string or None | Channel layout: either "channels_last" or "channels_first". If omitted, the layer uses the image_data_format value from the Keras configuration. |
keepdims | boolean | Whether to retain the reduced spatial dimensions as length-one axes; defaults to False. |
**kwargs | keyword arguments | Additional keyword arguments accepted by the Keras layer base class. |
For keepdims=False, a 2D tensor shaped (batch_size, channels). For keepdims=True, a 4D tensor with singleton spatial dimensions: (batch_size, 1, 1, channels) for channels_last or (batch_size, channels, 1, 1) for channels_first.
import numpy as np
import tensorflow as tf
x = np.random.rand(2, 4, 5, 3).astype("float32")
y = tf.keras.layers.GlobalAveragePooling2D()(x)
print(y.shape) # (2, 3)A channels-last batch of feature maps is reduced over height and width, leaving one value per channel for each example.
Convolutional classifier heads
Transfer learning
Shape-preserving model blocks
It computes the mean over height and width independently for every channel and every batch item. With the default keepdims=False, a channels-last input shaped (batch, height, width, channels) becomes (batch, channels).
Follow-up: What changes with keepdims=True? The spatial axes remain, producing (batch, 1, 1, channels) for channels-last or (batch, channels, 1, 1) for channels-first.
data_format selects the position of the channel axis. channels_last expects (batch, height, width, channels), while channels_first expects (batch, channels, height, width).
Follow-up: How would a mismatch show up? The layer would average the wrong axes or interpret the dimensions incorrectly, so the configured format must match the input layout.
For an input with shape (2, 4, 5, 3), the default output has shape (2, 3). The 4-by-5 spatial locations are averaged, while the three channel values remain separate.
Follow-up: Why is this useful before a classifier? It converts spatial feature maps into a compact per-example channel vector without requiring a Flatten layer over every spatial location.
tf.keras.layers.GlobalAveragePooling1Dtf.keras.layers.AveragePooling2Dtf.reduce_meantf.keras.layers.Dense