API reference
Keras API reference
Keras high-level deep learning API
- Identifiers
- 106
- With full guides
- 104
- Types
- 3
Topics covered
- Sequential API
- Functional API
- Layers
- compile & fit
- Callbacks
- Optimizers & losses
- Saving models
- Custom layers
Class
| Name | What it does |
|---|---|
Sequential | Keras Sequential builds a Model from a linear stack of layers. It suits straightforward single-input, single-output architectures and supports training and inference. |
Model | Keras Model groups layers into an object that supports training and inference. Create one with the Functional API, by subclassing Model, or through the Sequential specialization. |
Dense | Dense is Keras's standard fully connected layer. It transforms the final input axis into a chosen number of outputs using learned weights, an optional bias, and an optional activation. |
Conv2D | Conv2D applies learned filters across an input's height and width to produce 2D feature maps. Strides, padding, dilation, groups, bias, and activation control how the transformation is performed. |
LSTM | Keras LSTM is a recurrent layer for 3D sequence inputs. It can produce the last timestep, the complete sequence, and optionally the final hidden and cell states. |
Dropout | Dropout is a regularization layer that randomly zeroes input units during training to help reduce overfitting. Surviving units are rescaled, while inference passes inputs through unchanged. |
Embedding | Maps nonnegative integer indices to dense vectors through a trainable embedding matrix. Each input position receives one vector of size output_dim. |
Adam | Adam is a Keras optimizer based on adaptive estimates of first- and second-order gradient moments. Configure its learning rate, moment decay, clipping, EMA, and related optimization options before compiling a model. |
layers.Dense | Dense is a fully connected Keras layer that maps each input feature vector to a chosen number of output units. It combines a learned kernel and optional bias, then applies an optional activation. |
layers.Conv2D | Conv2D applies a learnable two-dimensional convolution across height and width. It produces a configurable number of output channels and can add a bias and activation. |
layers.Conv1D | Conv1D applies a learnable one-dimensional convolution across a sequence or single spatial axis. It produces the requested number of output filters and can optionally add bias and activation. |
layers.Conv3D | Conv3D applies a learned kernel across three spatial or temporal dimensions to produce volumetric feature maps. It supports configurable filters, kernel size, strides, padding, dilation, activation, bias, grouping, initialization, regularization, and constraints. |
layers.SeparableConv2D | SeparableConv2D applies a depthwise spatial convolution followed by a pointwise channel-mixing convolution. It optionally adds bias and applies an activation. |
layers.MaxPooling2D | MaxPooling2D downsamples 2D spatial data by taking channel-wise maxima over moving windows. Configure the window, stride, padding, and channel layout to control the resulting feature-map size. |
layers.AveragePooling2D | AveragePooling2D downsamples 2D spatial data by replacing local height–width windows with channel-wise averages. Configure the window, stride, padding, and channel layout to control the resulting feature-map size. |
layers.GlobalAveragePooling2D | GlobalAveragePooling2D averages each channel across an image feature map's height and width. It normally returns one value per channel per example, or preserves singleton spatial axes when keepdims=True. |
layers.Flatten | 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. |
layers.Reshape | keras.layers.Reshape changes each input sample to a specified shape while preserving the batch axis. One target dimension may be -1 for automatic size inference. |
layers.Dropout | Dropout randomly removes input units during training to reduce overfitting, then rescales the units that remain. It does nothing during inference. |
layers.BatchNormalization | BatchNormalization normalizes activations using batch statistics during training and moving statistics during inference. It can apply learned scale and offset parameters after normalization. |
layers.LayerNormalization | LayerNormalization normalizes each example independently across selected axes, rather than using batch-wide statistics. Optional trainable gamma scaling and beta centering refine the normalized output. |
layers.GroupNormalization | GroupNormalization divides feature channels into groups and normalizes each group using its own mean and variance. Optional beta and gamma parameters then offset and scale the result. |
layers.LSTM | Keras LSTM processes 3D sequences with recurrent state updates. Configure it to return the final output, every timestep, and optionally the final hidden and cell states. |
layers.GRU | keras.layers.GRU processes sequence data with gated recurrent updates and produces either the final output or outputs for every timestep. It supports configurable activations, dropout, state handling, direction, and recurrent-kernel conventions. |
layers.SimpleRNN | SimpleRNN is a fully connected recurrent layer that feeds each output back as the next input. It consumes 3D sequence tensors and can return the final output, the full sequence, and optionally the final state. |
layers.Bidirectional | Bidirectional wraps a sequence-processing RNN or compatible layer to read inputs in forward and reverse directions. It combines the two results using a selectable merge mode, defaulting to concatenation. |
layers.TimeDistributed | TimeDistributed applies one Keras layer independently to every temporal slice of an input. The same layer instance—and therefore the same weights—is reused at each time step. |
layers.Embedding | keras.layers.Embedding maps nonnegative integer indexes to dense vectors through a trainable embedding matrix. Configure the vocabulary capacity with input_dim and the vector width with output_dim. |
layers.Attention | Keras Attention is a Luong-style dot-product attention layer. It converts query-key scores into weights and uses them to combine value vectors. |
layers.MultiHeadAttention | MultiHeadAttention implements scaled multi-head attention for self-attention or cross-attention. It projects query, key, and value across several heads, combines the attended values, and optionally projects the result to a chosen output shape. |
layers.Concatenate | Keras Concatenate joins a list of tensors along one chosen axis. Inputs must have matching shapes on every other axis, and the default join axis is the last one. |
layers.Add | keras.layers.Add merges a list of same-shaped tensors by adding them elementwise. It returns one tensor with that same shape. |
layers.Multiply | Keras Multiply performs elementwise multiplication on a list of same-shaped tensors and returns one tensor with that shape. It is useful for combining parallel branches or applying tensor-valued gates. |
layers.Average | keras.layers.Average computes the element-wise mean of a list of same-shaped tensors. It returns one tensor with the same shape, making it useful for merging parallel Keras branches. |
layers.Dot | keras.layers.Dot computes a dot product between two input tensors over selected axes. It can optionally normalize the inputs first, producing cosine proximity. |
layers.Activation | Keras layers.Activation applies a selected activation function as a layer. Choose a built-in activation by name or provide a callable. |
layers.ReLU | keras.layers.ReLU is an element-wise rectified-linear activation layer. Its parameters support an upper cap, a nonzero below-threshold slope, and a nonzero threshold. |
layers.LeakyReLU | LeakyReLU is a Keras activation layer that keeps a small, configurable slope for negative inputs and passes nonnegative inputs through unchanged. It preserves the input shape. |
layers.PReLU | PReLU is a trainable activation that keeps nonnegative values unchanged and applies a learned alpha slope to negative values. Its alpha parameters can be initialized, regularized, constrained, and shared across selected axes. |
layers.ELU | layers.ELU applies the Exponential Linear Unit activation as a Keras layer. It leaves nonnegative values unchanged and uses an alpha-scaled exponential branch for negative values. |
layers.Softmax | A Keras layer that converts logits into normalized softmax values along one or more selected axes. It supports an optional broadcastable mask for excluding positions. |
layers.Lambda | keras.layers.Lambda wraps an arbitrary callable as a Keras layer for use in Sequential or Functional models. It is intended mainly for simple operations and rapid experimentation. |
layers.Masking | Masks sequence timesteps whose feature values all equal a chosen sentinel, allowing compatible downstream layers to skip them. It is commonly used to ignore padded rows before an LSTM or other masking-aware layer. |
layers.RepeatVector | RepeatVector copies each input vector n times, turning a 2D batch of feature vectors into a 3D sequence tensor. The new middle dimension has length n. |
layers.Permute | Reorders an input tensor's non-batch dimensions using a one-based permutation tuple. The output preserves the same dimensions but presents them in the requested order. |
layers.UpSampling2D | UpSampling2D enlarges the two spatial dimensions of a 4D image or feature-map tensor while preserving channels. It supports separate row and column factors plus several interpolation modes. |
layers.Resizing | Keras layers.Resizing converts 3D or 4D image tensors to a chosen height and width. It supports multiple interpolation methods, optional aspect-ratio-preserving cropping or padding, and both channel layouts. |
layers.Rescaling | Keras' Rescaling layer applies the same linear transformation to every input value: multiply by scale, then add offset. It is commonly used to convert image values such as [0, 255] into a model-friendly range such as [0, 1] or [-1, 1]. |
layers.RandomFlip | RandomFlip randomly mirrors images horizontally, vertically, or in both directions during training. It preserves image dimensions and returns the original input during inference. |
layers.RandomRotation | RandomRotation is a Keras preprocessing layer that randomly rotates images during training. It supports configurable angle limits, boundary filling, interpolation, seeding, and channel layout. |
layers.RandomZoom | RandomZoom randomly zooms images during training, independently sampling the vertical and horizontal axes. It supports zoom-in or zoom-out factors and configurable filling for regions outside the source image. |
layers.Normalization | Keras Normalization standardizes continuous features using stored mean and variance. Statistics may be supplied directly or learned from data with adapt(). |
layers.TextVectorization | TextVectorization turns batches of strings into integer token sequences or dense text-feature vectors. It standardizes, splits, optionally creates n-grams, indexes tokens, and applies the selected output mode. |
layers.CategoryEncoding | CategoryEncoding turns integer features into one-hot, multi-hot, or count vectors when the number of supported tokens is known. It can produce dense or sparse outputs. |
layers.StringLookup | StringLookup maps categorical strings to vocabulary indices or encoded vectors. Supply a vocabulary directly or learn one with adapt(). |
layers.IntegerLookup | IntegerLookup maps arbitrary integer tokens to contiguous vocabulary indices or categorical encodings. It can use a supplied vocabulary or learn one with adapt(). |
keras.Model | keras.Model groups layers into a trainable object with built-in training and inference features. Create it with the Functional API, by subclassing it, or use Sequential for a simple layer stack. |
keras.Sequential | keras.Sequential creates a Keras Model from an ordered linear stack of layers. It supports construction from a layer list or incremental assembly with add(). |
optimizers.Adam | Adam is a Keras optimizer based on adaptive first- and second-moment estimates. Configure its learning rate, moment decay, numerical stability, clipping, weight decay, EMA, and accumulation behavior. |
optimizers.SGD | keras.optimizers.SGD performs gradient descent with optional momentum and Nesterov acceleration. It supports schedules, weight decay, gradient clipping, EMA, loss scaling, and gradient accumulation. |
optimizers.RMSprop | RMSprop is a Keras optimizer that scales gradients using a discounted moving average of their squared values. It optionally uses centered variance normalization, plain momentum, weight decay, clipping, EMA, loss scaling, and gradient accumulation. |
optimizers.AdamW | AdamW is Keras's adaptive optimizer with decoupled weight decay. It extends Adam-style first- and second-moment estimation with configurable clipping, EMA, loss scaling, and gradient accumulation. |
optimizers.Nadam | Nadam is an adaptive Keras optimizer that applies Adam-style updates with Nesterov momentum. It supports configurable learning rates, moment decay, clipping, weight decay, EMA, and optional XLA compilation. |
optimizers.Lion | Lion is a Keras optimizer that uses a sign-based momentum update instead of Adam-style second-moment adaptation. It can reduce optimizer-state memory while supporting standard options such as weight decay, clipping, EMA, and gradient accumulation. |
losses.BinaryCrossentropy | |
losses.CategoricalCrossentropy | CategoricalCrossentropy computes classification loss for one-hot labels across two or more classes. Configure logits handling, label smoothing, class axis, and reduction through its constructor. |
losses.SparseCategoricalCrossentropy | SparseCategoricalCrossentropy computes classification crossentropy when targets are integer class IDs. Configure it for probability outputs or logits, and optionally ignore a class or choose the reduction. |
losses.MeanSquaredError | MeanSquaredError is a Keras regression loss that averages squared differences between targets and predictions. Its instance-level reduction controls whether those per-sample values are averaged, summed, weighted, or left unaggregated. |
losses.Huber | Huber is a regression loss that combines squared-error behavior for small errors with absolute-error behavior for large errors. The delta parameter sets the transition between these regions. |
metrics.Accuracy | keras.metrics.Accuracy measures how often predictions exactly equal their corresponding labels. It maintains running match and sample counts and returns their ratio. |
metrics.Precision | keras.metrics.Precision measures the fraction of predicted positives that are correct. It accumulates true and false positives and supports threshold-based, top-k, and class-specific evaluation. |
metrics.Recall | keras.metrics.Recall measures the fraction of actual positives that are detected. It supports threshold-based classification, top-k ranking, optional class selection, and sample weighting. |
metrics.AUC | keras.metrics.AUC estimates the area under a ROC or precision-recall curve for binary or multi-label classification. It accumulates thresholded confusion statistics and returns the approximated area as a scalar metric. |
metrics.F1Score | Keras F1Score computes the harmonic mean of precision and recall for multiclass or multilabel classification. Configure average for per-class, micro, macro, or weighted aggregation, and threshold for binary label decisions. |
callbacks.EarlyStopping | EarlyStopping stops model training when a monitored metric stops improving. It supports patience, improvement thresholds, warm-up epochs, baselines, and optional restoration of the best weights. |
callbacks.ModelCheckpoint | ModelCheckpoint saves a Keras model or its weights during fit() training. It can save every epoch or after a batch interval, optionally keeping only checkpoints that improve a monitored metric. |
callbacks.ReduceLROnPlateau | ReduceLROnPlateau lowers an optimizer's learning rate when a monitored metric stops improving. Configure the monitored metric, improvement direction, patience, reduction factor, cooldown, and minimum learning rate. |
callbacks.TensorBoard | keras.callbacks.TensorBoard records Keras training events for TensorBoard, including metrics, graphs, weight histograms, and profiling data. Configure its log directory and logging options, then pass it to model.fit(). |
callbacks.CSVLogger | CSVLogger records epoch results from model training in a CSV file. You can choose the output path, delimiter, and whether existing logs are appended or overwritten. |
applications.ResNet50 | ResNet50 builds the 50-layer ResNet image model as a Keras model. It supports ImageNet or custom weights, optional classification layers, global pooling, and configurable input settings. |
applications.VGG16 | Builds the VGG16 convolutional network with optional ImageNet weights and classifier. It supports standard classification or feature extraction with custom inputs and pooling. |
applications.MobileNetV2 | MobileNetV2 is a lightweight Keras image-classification architecture based on inverted residual bottleneck blocks. It supports ImageNet initialization, configurable classifier inclusion, input scaling, and optional feature pooling. |
applications.EfficientNetB0 | EfficientNetB0 creates the B0 EfficientNet image-classification model, optionally using ImageNet-pretrained weights. Its options support standard classification, custom inputs, and feature extraction without the top classifier. |
applications.InceptionV3 | InceptionV3 builds the Inception v3 image-classification architecture, optionally initialized with ImageNet weights. Exclude its classifier and optionally pool the output to use it as a feature extractor. |
Function
| Name | What it does |
|---|---|
compile | Configures a Keras model for training by selecting its optimizer, loss, metrics, and execution settings. Call it before fit(), evaluate(), or other built-in training methods. |
fit | Model.fit trains a compiled Keras model for a chosen number of epochs using array-, tensor-, or dataset-like inputs. It supports batching, validation, weighting, callbacks, and step controls. |
Input | keras.Input() creates a symbolic Keras tensor for defining model inputs. Its shape describes each sample, while optional arguments configure batching, dtype, sparse or ragged inputs, naming, wrapping an existing tensor, and optional inputs. |
keras.Input | keras.Input creates a symbolic Keras tensor that serves as the starting point for a model graph. Define its shape and related input properties, connect layers to it, and use the resulting tensors to build a Functional API model. |
keras.models.load_model | Loads a Keras model from a saved model file or Orbax checkpoint. It can restore compilation and resolve custom serialized objects while protecting against unsafe lambda deserialization by default. |
keras.models.clone_model | Creates a new Functional or Sequential model with the same structure but newly instantiated layers and weights. Optional callbacks can customize layer cloning, layer invocation, and recursive handling of nested models. |
Module
| Name | What it does |
|---|---|
callbacks | Keras callbacks are objects that run actions at selected stages of model execution. Pass them as a list to model methods such as fit() to add logging, checkpointing, early stopping, or custom behavior. |
model.compile | Configures a Keras model for training by selecting its optimizer, loss, metrics, and execution behavior. After compilation, the model can be trained and evaluated with the standard Keras APIs. |
model.fit | Model.fit trains a compiled Keras model over batches for a chosen number of epochs. It accepts arrays, tensors, mappings, and dataset-like inputs, and can run validation during training. |
model.evaluate | Evaluates a compiled Keras model in test mode and returns its loss and configured metric values. It accepts arrays, tensors, named-input mappings, and supported data pipelines, with optional batching, weighting, callbacks, and named results. |
model.predict | model.predict() runs inference on input samples in batches and returns NumPy prediction array(s). It is intended for batch processing of large inputs, not repeated tiny calls inside loops. |
model.save | model.save() stores a complete Keras model in the native .keras format. It preserves architecture, weights, and optimizer state when present, so the model can later be reconstructed. |
model.summary | Prints a readable summary of a built Keras model, including its layers and network information. Options can expand nested models, show trainability, redirect output, and restrict the displayed layer range. |
model.get_weights | Model.get_weights() retrieves a model's current weights as a flat list of NumPy arrays. It is useful for inspecting or transferring weight values in memory. |
model.set_weights | Model.set_weights assigns a layer or model's weights from a list of NumPy arrays. The arrays must match the target's weight count, shapes, and creation order. |
keras.ops | |
keras.activations | keras.activations provides built-in nonlinear and linear functions for transforming tensors. Use them directly, pass them to layer activation arguments, or select built-ins by string name. |
keras.initializers | keras.initializers provides built-in and custom strategies for creating initial layer-weight tensors. Use initializer objects or supported string names through layer-specific arguments such as kernel_initializer and bias_initializer. |
keras.regularizers | Keras regularizers add scalar penalties for layer weights or activity to the loss used during optimization. The module provides built-in L1, L2, combined L1/L2, and orthogonality-based regularizers, while also accepting custom callable functions. |
keras.constraints | Keras constraints are projection callables that enforce rules on layer variables after gradient updates. Built-ins cover norm limits, non-negativity, and unit norms, and layers expose arguments such as kernel_constraint and bias_constraint. |
keras.utils.to_categorical | Converts integer class labels into a binary, one-hot-style matrix. The number of classes can be supplied explicitly or inferred from the largest label. |
keras.utils.image_dataset_from_directory | Creates a dataset from images stored in a directory, optionally inferring labels from class-specific subdirectories. It decodes, resizes, shuffles, batches, and can split the files for training and validation. |
Search across every package and filter by type in your dashboard.
Start learning