Core Keras Layers

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

Layers are the building blocks of every Keras model. This page surveys the ones used most often, with their input and output shapes, the arguments that matter, and the pitfalls that appear in practice, and then lists the naming and behaviour changes that Keras 3 introduced. Assembling layers into models is on Sequential & Functional Models, writing your own on Subclassing & Custom Layers, and preprocessing layers on Keras Preprocessing Layers. Full CNN, text and attention workflows are on Image Classification with CNNs, Text, RNNs & Embeddings and Attention & Transformers.

It targets Python 3.13 and TensorFlow 2.21 with Keras 3.15 (TensorFlow 2.22 is upcoming), and was checked against the official keras.io API reference on 2026-10-30. Examples were run on Python 3.13 with TensorFlow 2.21 and Keras 3.15 (CPU) on 2026-10-31. The theory is in Neural Network Fundamentals, Convolutional Neural Networks, Recurrent Networks & Sequences and Attention & Transformers; the PyTorch equivalents are Linear & Convolution Layers, Recurrent Layers and Embedding, Normalization, Dropout & Activations.

Layer families: Dense, Conv2D and pooling, normalization and dropout, embedding, recurrent, and attention, with their shapes
Figure 1. Layer families and the shapes they map (channels-last layout).

Conventions shared by all layers

  • The batch dimension is written None in symbolic shapes, and keras.Input(shape=...) takes the shape without it.

  • The default image layout is channels-last, (batch, height, width, channels). The data_format argument ("channels_last" or "channels_first") and the global setting keras.config.image_data_format() control it. Keep channels-last unless a backend or kernel requires otherwise.

  • Activations can be given as strings ("relu"), functions (keras.activations.gelu) or Activation layers. activation=None leaves the output linear, which is what you want before a loss with from_logits=True.

  • Common keyword arguments: kernel_initializer, bias_initializer, kernel_regularizer, bias_regularizer, activity_regularizer, kernel_constraint, use_bias, name, dtype, trainable.

  • Every layer has weights, trainable_weights, non_trainable_weights, output (once connected), count_params() and get_config().

  • The default weight initializer for Dense and convolution kernels is Glorot uniform and biases start at zero; override with "he_normal" for ReLU networks if you want to follow He initialization (see Training Deep Networks).

Dense

Dense(units) computes activation(inputs @ kernel + bias) on the last axis and leaves the other axes alone, so it works on (batch, features) and on (batch, time, features) alike.

import keras
from keras import layers, ops

dense = layers.Dense(
    64,
    activation="relu",
    kernel_initializer="he_normal",
    kernel_regularizer=keras.regularizers.L2(1e-4),
)
x = ops.ones((8, 20))
y = dense(x)
print(y.shape, [tuple(w.shape) for w in dense.weights])   # (8, 64) [(20, 64), (64,)]

seq = layers.Dense(10)(ops.ones((8, 5, 20)))        # applied at each time step
print(seq.shape)                                    # (8, 5, 10)

Related core layers:

  • Flatten collapses all axes after the batch axis; Reshape(target_shape) reshapes without the batch axis; Permute reorders axes; RepeatVector(n) tiles a vector along a new time axis.

  • Activation, ReLU, LeakyReLU, PReLU, ELU, Softmax are layers, useful inside Sequential models and when the activation has parameters.

  • Lambda(fn) wraps a function but is awkward to serialize; prefer a small custom layer. Identity is a no-op, useful as a placeholder.

  • EinsumDense applies an einsum equation, which expresses per-head projections in transformer code in one layer.

  • In Keras 3.15 a built Dense layer supports low-rank adaptation and quantization: dense.enable_lora(rank) freezes the kernel and adds trainable lora_kernel_a and lora_kernel_b weights, and dense.quantize("int8") replaces the kernel with an int8 kernel plus a kernel_scale; see Quantization & Model Optimization.

Convolution layers

Conv1D, Conv2D and Conv3D slide learned filters over the spatial axes. For Conv2D the input is (batch, H, W, C) and the output is (batch, H', W', filters).

conv = layers.Conv2D(
    filters=32,
    kernel_size=3,
    strides=1,
    padding="same",          # "valid" (default) or "same"
    activation="relu",
)
y = conv(ops.ones((4, 64, 64, 3)))
print(y.shape)               # (4, 64, 64, 32)

valid = layers.Conv2D(32, 3)(ops.ones((4, 64, 64, 3)))
print(valid.shape)           # (4, 62, 62, 32)

strided = layers.Conv2D(32, 3, strides=2, padding="same")(ops.ones((4, 64, 64, 3)))
print(strided.shape)         # (4, 32, 32, 32)

The output size is \(\lfloor (n - k + 2p)/s \rfloor + 1\) for "valid" (with \(p = 0\)) and \(\lceil n / s \rceil\) for "same". Other convolution layers:

Layer Use

SeparableConv2D, DepthwiseConv2D

Depthwise followed by pointwise convolution, far fewer parameters (MobileNet style)

Conv2DTranspose

Learned upsampling in decoders and segmentation heads

Conv1D

Sequences and audio; input (batch, steps, channels); padding="causal" is available for temporal models

dilation_rate argument

Wider receptive field without more parameters; combining it with strides greater than 1 is not supported by every backend

groups argument

Grouped convolutions; filters and the input channels must be divisible by groups

Pitfalls: "same" padding with stride 2 pads asymmetrically in TensorFlow, which matters when comparing against PyTorch’s symmetric integer padding; a missing channel axis on grayscale images (use (28, 28, 1), not (28, 28)); and forgetting that the default padding="valid" shrinks the feature map.

Pooling

x = ops.ones((4, 32, 32, 16))

print(layers.MaxPooling2D(pool_size=2)(x).shape)          # (4, 16, 16, 16)
print(layers.AveragePooling2D(pool_size=2)(x).shape)      # (4, 16, 16, 16)
print(layers.GlobalAveragePooling2D()(x).shape)           # (4, 16)
print(layers.GlobalAveragePooling2D(keepdims=True)(x).shape)  # (4, 1, 1, 16)
print(layers.GlobalMaxPooling2D()(x).shape)               # (4, 16)

strides defaults to pool_size, so a pooling window does not overlap unless you say so. Global pooling replaces Flatten in modern CNN heads: it removes the dependence on image size and the huge dense layer that comes with flattening.

Normalization

bn = layers.BatchNormalization(axis=-1, momentum=0.99, epsilon=1e-3)
y_train = bn(ops.ones((8, 10)), training=True)    # uses batch statistics
y_infer = bn(ops.ones((8, 10)), training=False)   # uses moving averages

ln = layers.LayerNormalization(axis=-1)           # statistics per sample
gn = layers.GroupNormalization(groups=8)          # channel groups, batch-size independent
  • BatchNormalization keeps four weights per feature: gamma and beta (trainable) and a moving mean and variance (non-trainable, updated in training). Moving averages are updated only when training=True.

  • Setting bn.trainable = False makes the layer run in inference mode, using the moving statistics, and freezes gamma and beta. This is the behaviour TensorFlow 2 chose for fine-tuning and is relied on in Transfer Learning & Fine-Tuning. Compile again after changing trainable.

  • LayerNormalization is the default in transformers; GroupNormalization is used with small batches; UnitNormalization scales vectors to unit length; RMSNormalization is available in recent Keras 3 releases and is not present in Keras 2.

  • Place normalization consistently (before or after the activation) and keep the batch size above a handful when using BatchNormalization, or the statistics become noisy.

Dropout and noise

drop = layers.Dropout(rate=0.3)             # rate is the fraction DROPPED
y = drop(ops.ones((4, 10)), training=True)  # kept units are scaled by 1/(1-rate)

sd = layers.SpatialDropout2D(0.2)           # drops whole feature maps
noise = layers.GaussianNoise(0.1)           # active only in training

Dropout, SpatialDropout1D/2D/3D, AlphaDropout, GaussianNoise, GaussianDropout and ActivityRegularization are active only during training; Keras supplies training when you use fit. Dropout is inverted: surviving activations are scaled at training time so nothing changes at inference. Pass seed= or use a keras.random.SeedGenerator for reproducible masks; see Generalization & Regularization.

Embedding

Embedding(input_dim, output_dim) is a trainable lookup table that maps integer ids to vectors. The input must be integers from 0 up to, but excluding, input_dim.

emb = layers.Embedding(input_dim=10_000, output_dim=64, mask_zero=True)
ids = ops.convert_to_tensor([[5, 7, 0, 0], [1, 2, 3, 0]])
vectors = emb(ids)
print(vectors.shape)                  # (2, 4, 64)
mask = emb.compute_mask(ids)          # False where the id is 0

With mask_zero=True, id 0 is reserved for padding, so input_dim must be the vocabulary size plus one, and downstream recurrent and attention layers can skip padded steps. Pretrained vectors are loaded through embeddings_initializer=keras.initializers.Constant(matrix) and frozen with trainable=False. The surrounding text pipeline is on Text, RNNs & Embeddings and the idea in Embeddings & Representation Learning.

Recurrent layers

SimpleRNN, LSTM and GRU process (batch, time, features) inputs. By default they return only the last output; set return_sequences=True to get one output per step, which is needed to stack recurrent layers.

x = ops.ones((8, 20, 16))

print(layers.LSTM(32)(x).shape)                          # (8, 32)
print(layers.LSTM(32, return_sequences=True)(x).shape)   # (8, 20, 32)

out, h, c = layers.LSTM(32, return_state=True)(x)        # last output, h, c
print(out.shape, h.shape, c.shape)                       # (8, 32) (8, 32) (8, 32)

bi = layers.Bidirectional(layers.GRU(32, return_sequences=True))
print(bi(x).shape)                                       # (8, 20, 64)

model = keras.Sequential([
    keras.Input(shape=(20, 16)),
    layers.LSTM(64, return_sequences=True),
    layers.LSTM(32),
    layers.Dense(1),
])
  • LSTM and GRU accept dropout (inputs) and recurrent_dropout (state); the latter disables the fastest GPU kernel on some backends.

  • On the TensorFlow backend the cuDNN kernel is used when the layer has default activations and recurrent_dropout=0, which is much faster on a GPU. Changing these arguments silently selects a slower generic implementation.

  • RNN(cell) runs a custom cell (a layer with state_size and a call(inputs, states)); ConvLSTM1D/2D/3D combine convolution and recurrence; TimeDistributed(layer) applies a layer to each time slice.

  • Masks produced by Embedding(mask_zero=True) or Masking make recurrent layers ignore padded steps.

  • Use stateful=True only with a fixed batch size and call reset_states() between sequences.

Attention

MultiHeadAttention(num_heads, key_dim) projects queries, keys and values into several heads, applies scaled dot-product attention and merges the heads. The call takes query, value and optionally key (defaulting to value).

mha = layers.MultiHeadAttention(num_heads=4, key_dim=16)

q = ops.ones((2, 10, 64))     # (batch, target length, dim)
v = ops.ones((2, 12, 64))     # (batch, source length, dim)

cross = mha(query=q, value=v)                                  # (2, 10, 64)
self_out, scores = mha(q, q, use_causal_mask=True,
                       return_attention_scores=True)
print(cross.shape, scores.shape)                               # scores: (2, 4, 10, 10)

use_causal_mask=True blocks attention to later positions in decoder self-attention; attention_mask supplies an arbitrary boolean mask; the output dimension defaults to the query’s last dimension unless output_shape is set. The simpler Attention (dot-product) and AdditiveAttention (Bahdanau) layers have no learned projections. Position information is not added by these layers, so transformers add positional embeddings separately; full blocks are on Attention & Transformers.

Merging layers and utilities

  • Add, Subtract, Multiply, Average, Maximum, Minimum, Concatenate, Dot combine a list of tensors; they are the joints of branched Functional models.

  • Cropping2D, ZeroPadding2D, UpSampling2D change spatial size; Resizing and Rescaling belong to preprocessing.

  • Input and InputLayer declare model inputs; StackedRNNCells stacks recurrent cells.

Keras 3 naming and behaviour changes

The keras package is a rewrite with a multi-backend core. Compared with the Keras 2 tf.keras API that older books and tutorials describe, the changes below matter when you read or port layer code. The full checklist is on Migrating from Keras 2 to Keras 3.

Older Keras 2 code Keras 3 Notes

tf.keras.layers.* with TensorFlow-only internals

keras.layers.* backed by keras.ops

Layers run on TensorFlow, JAX and PyTorch; custom layers must use keras.ops

input_shape= argument on the first layer

keras.Input(shape=...) as the first element

The older argument is discouraged and triggers a warning

tf.Variable for weights

keras.Variable via add_weight

Weights are backend-neutral wrappers; read with .value

Layer.add_weight(name, shape, ...) positional

keyword form add_weight(shape=..., initializer=..., name=...)

Keras 3 uses keyword arguments

SavedModel as the default saved format

.keras zip archive and export for SavedModel

Covered on the saving page

layers.experimental.preprocessing.*

layers.Resizing, layers.Rescaling, layers.Normalization …​

Preprocessing layers moved to keras.layers; some are backend-agnostic

Ragged and sparse inputs everywhere

Supported mainly on the TensorFlow backend

Check backend support before relying on them

Lambda layers saved freely

Lambda deserialization needs safe mode off

Safe mode blocks arbitrary code in files

Other practical differences: BatchNormalization and other stateful layers behave the same, but the optimizer API is new (see Optimizers & Learning-Rate Schedules); model.summary() prints a different table; keras.layers.Layer.add_metric from Keras 2 is gone in favour of metric objects. Whether a particular Keras 2 layer argument still exists is best confirmed against https://keras.io/api/layers/ for the installed version.

Choosing layers: a short guide

Data Typical stack

Tabular vectors

Dense + BatchNormalization or LayerNormalization + Dropout

Images

Conv2D blocks with pooling or strides, GlobalAveragePooling2D, Dense head

Token ids

Embedding followed by LSTM, GRU, Conv1D or attention blocks

Long sequences, translation

Embedding + positional embedding + MultiHeadAttention + Dense feed-forward

Common pitfalls

  • Softmax in the last layer together with from_logits=True in the loss, which applies softmax twice.

  • Embedding.input_dim too small, producing out-of-range lookups; ids at or above input_dim are not an error on every backend.

  • Using Flatten after a large feature map and ending with millions of dense parameters.

  • Expecting Dropout to act in predict; it is off unless you pass training=True.

  • Treating BatchNormalization.trainable = False as only freezing the weights; it also changes the layer to inference mode.

  • Mixing channels-first data with a channels-last model.