Flatten collapses every dimension of an input except the batch dimension into one single dimension, preserving the values and their order but discarding any multi-dimensional spatial structure. It's most commonly used as the bridge between convolutional/pooling layers, which output multi-dimensional feature maps, and Dense layers, which require a flat 1D vector of features per example — Flatten has no learned parameters and performs no computation, it purely rearranges an existing tensor's shape.
1Understanding tf.keras.layers.Flatten()
Flatten collapses every dimension of an input except the batch dimension into one single dimension, preserving the values and their order but discarding any multi-dimensional spatial structure. It's most commonly used as the bridge between convolutional/pooling layers, which output multi-dimensional feature maps, and Dense layers, which require a flat 1D vector of features per example — Flatten has no learned parameters and performs no computation, it purely rearranges an existing tensor's shape.
Flatten produces no computation and no learned parameters — its output length is simply the product of all the non-batch dimensions of its input, which is exactly the number that determines how many parameters the very next Dense layer will need.
import tensorflow as tf
from tensorflow.keras import layers
layer = layers.Flatten()
output = layer(tf.zeros([1, 13, 13, 8]))
print(output.shape)2Practical Example
Here is a real-world application of tf.keras.layers.Flatten() showing how it is used in production TensorFlow code.
import tensorflow as tf
from tensorflow.keras import layers
layer = layers.Flatten()
x = tf.constant([[[1.0, 2.0], [3.0, 4.0]]])
print(layer(x).numpy())3Best Practices
Follow these guidelines when working with tf.keras.layers.Flatten():
1. Place Flatten immediately before the first Dense layer when transitioning from convolutional/pooling layers to a fully-connected classifier head
2. Check the flattened output size, the product of the preceding layer's non-batch dimensions, before adding a large Dense layer after it, since that size directly controls the next layer's parameter count
3. Consider GlobalAveragePooling2D as an alternative to Flatten when you want to avoid a huge Dense layer following a large feature map
Tip: Flatten produces no computation and no learned parameters — its output length is simply the product of all the non-batch dimensions of its input, which is exactly the number that determines how many parameters the very next Dense layer will need.
import tensorflow as tf
from tensorflow.keras import layers
layer = layers.Flatten()
output = layer(tf.zeros([1, 13, 13, 8]))
print(output.shape)