Prepare features for Dense layers
Convert a spatial or sequence-like tensor into a vector before a fully connected layer.
Keras · Class
Keras Flatten collapses all non-batch input dimensions into one feature dimension while preserving the batch size. It supports channels_last or channels_first input dimension ordering.
Flatten converts every non-batch dimension of an input into one feature dimension. It preserves the batch axis; for an input shaped only as (batch,), it inserts a single feature axis, producing (batch, 1).
keras.layers.Flatten(data_format=None, **kwargs)| Name | Type | Description |
|---|---|---|
data_format | string, optional | Dimension ordering of the input tensor: channels_last or channels_first. If omitted, the configured image_data_format is used. |
import keras
x = keras.Input(shape=(10, 64))
y = keras.layers.Flatten()(x)
print(y.shape) # (None, 640)Creates a symbolic input with 10 by 64 features, then converts each example to one 640-element vector.
Convert a spatial or sequence-like tensor into a vector before a fully connected layer.
Build a symbolic functional model from a multidimensional input.
Handle tensors whose channel axis follows either common data-layout convention.
Flatten collapses all dimensions after the batch dimension into one dimension, while leaving the batch size unchanged. For an input shape of (None, 10, 64), the output shape is (None, 640).
Follow-up: What happens for an input shaped (batch,)? It gains a feature axis, resulting in (batch, 1).
The signature is keras.layers.Flatten(data_format=None, **kwargs). data_format controls whether dimensions follow channels_last or channels_first ordering; when omitted, Keras uses the configured image data format.
Follow-up: How would you choose the setting? Match the layout of the incoming tensor, such as (batch, height, width, channels) versus (batch, channels, height, width).
Flatten is useful when a tensor with spatial or other structured dimensions must be passed to a layer expecting a single feature vector, commonly before a Dense layer. It changes representation shape but does not alter the batch axis.
Follow-up: When might another operation be preferable? Use a reshaping operation when you need a specific target shape rather than flattening every non-batch dimension.
keras.layers.Reshapekeras.layers.Densekeras.Inputimage_data_format