Keras - Flatten Layers

Flatten is used to flatten the input. For example, if flatten is applied to layer having input shape as (batch_size, 2,2), then the output shape of the layer will be (batch_size, 4)

Flatten has one argument as follows

keras.layers.Flatten(data_format = None)

data_format is an optional argument and it is used to preserve weight ordering when switching from one data format to another data format. It accepts either channels_last or channels_first as value. channels_last is the default one and it identifies the input shape as (batch_size, ..., channels) whereas channels_first identifies the input shape as (batch_size, channels, ...)

A simple example to use Flatten layers is as follows −

>>> from keras.models import Sequential 
>>> from keras.layers import Activation, Dense, Flatten 
>>> model = Sequential() 
>>> layer_1 = Dense(16, input_shape=(8,8)) 
>>> model.add(layer_1) 
>>> layer_2 = Flatten() 
>>> model.add(layer_2) 
>>> layer_2.input_shape (None, 8, 16) 
>>> layer_2.output_shape (None, 128) 

where, the second layer input shape is (None, 8, 16) and it gets flattened into (None, 128).