Losses

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

A loss turns the model output and the target into the scalar that gradients are taken of. This page is the Keras 3 contract for each built-in loss: whether it expects logits or probabilities, what shape and dtype the target must have, how reduction and weights combine, and how to write a custom loss. The mathematics (maximum likelihood, cross-entropy, KL divergence, Huber) is in Loss Functions & Information Theory. Losses are passed to compile() (see compile, fit, evaluate & predict); the quantities you monitor but do not optimise are on Metrics, and the update rule is on Optimizers & Learning-Rate Schedules. The same contract in PyTorch is on Loss Functions.

Targets: Python 3.13, TensorFlow 2.21 with Keras 3.15 (TensorFlow 2.22 is upcoming), checked against the keras.io API pages 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 loss catalogue

The Keras 3 keras.losses page lists these classes (each also has a lowercase function form such as keras.losses.mean_squared_error):

Family Classes Typical use

Probabilistic

BinaryCrossentropy, BinaryFocalCrossentropy, CategoricalCrossentropy, CategoricalFocalCrossentropy, SparseCategoricalCrossentropy, Poisson, CTC, KLDivergence

Classification, count data, sequence alignment, distribution matching

Regression

MeanSquaredError, MeanAbsoluteError, MeanAbsolutePercentageError, MeanSquaredLogarithmicError, CosineSimilarity, Huber, LogCosh, Tversky, Dice

Continuous targets, embeddings, segmentation overlap

Hinge

Hinge, SquaredHinge, CategoricalHinge, CategoricalGeneralizedCrossEntropy, Circle

Maximum-margin classification, noisy labels, metric learning

The base class is keras.losses.Loss, subclassed for custom losses (see below). Which loss goes with which output layer:

Task Last layer Target Loss

Binary or multi-label classification

Dense(n) without activation (logits) or activation="sigmoid"

float or int in \([0, 1]\), same shape as output

BinaryCrossentropy(from_logits=True) for logits

Multi-class, integer labels

Dense© (logits) or softmax

integer class index, shape (batch,)

SparseCategoricalCrossentropy(from_logits=True)

Multi-class, one-hot or soft labels

Dense© (logits) or softmax

float (batch, C)

CategoricalCrossentropy(from_logits=True)

Regression

Dense(n), no activation

float, same shape as output

MeanSquaredError, MeanAbsoluteError or Huber

Class or function, string or instance

import keras
import numpy as np

# 1. Instance: configurable, reduces to a scalar
loss = keras.losses.SparseCategoricalCrossentropy(from_logits=True)

# 2. String: default arguments, resolved by name
model = keras.Sequential([keras.Input((20,)), keras.layers.Dense(3)])
model.compile(optimizer="adam", loss="sparse_categorical_crossentropy")  # default from_logits=False!

# 3. Function: returns per-sample values, no reduction
y_true = np.array([0, 2])
logits = np.array([[2.0, 0.1, 0.1], [0.2, 0.2, 1.5]], dtype="float32")
per_sample = keras.losses.sparse_categorical_crossentropy(y_true, logits, from_logits=True)
print(per_sample.shape)          # (2,)
print(float(loss(y_true, logits)))  # scalar mean

Pitfall: a string identifier uses default arguments, so loss="sparse_categorical_crossentropy" assumes the model outputs probabilities. If the last layer has no softmax, either add from_logits=True through the instance form or the model silently trains on mis-normalised values. Keras 3 loss classes can be called standalone (as above) and with y_true, y_pred in that order; swapping them gives wrong values without an error for symmetric losses and shape errors for others.

Logits versus probabilities (from_logits)

The cross-entropy classes accept from_logits. With from_logits=True the loss applies the sigmoid or softmax internally in a numerically stable fused form; with the default False it expects probabilities and clips them to avoid log(0). Preferring logits is the usual recommendation: the model ends with a plain Dense, and the activation is applied only at inference.

import keras
from keras import layers

# Logits head: the recommended pattern for training
model = keras.Sequential([
    keras.Input((28, 28)),
    layers.Flatten(),
    layers.Dense(128, activation="relu"),
    layers.Dense(10),                     # logits
])
model.compile(
    optimizer=keras.optimizers.Adam(1e-3),
    loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
    metrics=[keras.metrics.SparseCategoricalAccuracy()],
)

# Add the softmax only for inference
probability_model = keras.Sequential([model, keras.layers.Softmax()])

If the model already ends with softmax or sigmoid, keep from_logits=False. Mixing the two (a softmax head plus from_logits=True) applies the normalisation twice and flattens the gradients. Metrics have the same switch: SparseCategoricalAccuracy works on either logits or probabilities because only the argmax matters, whereas AUC and BinaryCrossentropy metrics need from_logits or logits handling set to match (see Metrics).

Target formats for the three cross-entropies

Class Target shape and dtype Notes

SparseCategoricalCrossentropy

integer indices (batch,) (or (batch, d1, ...) for per-token or per-pixel prediction)

Supports ignore_class to skip a label (for example a padding or "void" id)

CategoricalCrossentropy

one-hot or soft probabilities (batch, C)

Supports label_smoothing

BinaryCrossentropy

(batch,) or (batch, K) with values in \([0, 1]\)

Used for multi-label problems: one independent sigmoid per label

label_smoothing (on the binary and categorical classes) replaces hard targets with softened ones. For \(C\) classes and smoothing \(\epsilon\) the one-hot target \(y\) becomes \(y(1-\epsilon) + \epsilon / C\). It regularises over-confident models and is documented in the cross-entropy API pages; see Generalization & Regularization for why. SparseCategoricalCrossentropy has no label_smoothing argument in Keras 3.15 (its constructor takes from_logits, ignore_class, reduction, axis, name and dtype): one-hot encode the labels and use the categorical class if you need it.

import keras
import numpy as np

y_true = np.array([[0, 1, 0], [0, 0, 1]], dtype="float32")
logits = np.array([[0.1, 2.0, 0.3], [0.5, 0.2, 1.9]], dtype="float32")

plain = keras.losses.CategoricalCrossentropy(from_logits=True)
smooth = keras.losses.CategoricalCrossentropy(from_logits=True, label_smoothing=0.1)
print(float(plain(y_true, logits)), float(smooth(y_true, logits)))

# Ignore a padding label (id 0) in a per-token loss
tok_loss = keras.losses.SparseCategoricalCrossentropy(from_logits=True, ignore_class=0)

Reductions

Every loss class takes reduction. The keras.io losses page documents these values:

Value Behaviour

"sum_over_batch_size" (default)

Sum of per-sample losses divided by the batch size, the usual mean

"mean"

Same as "sum_over_batch_size"

"sum"

Sum of per-sample losses

"mean_with_sample_weight"

Sum of weighted losses divided by the sum of the sample weights

"none" or None

No aggregation: one loss per sample (or per element)

Function forms such as keras.losses.mean_squared_error do not reduce over the batch; they return the loss per sample, averaged only over the last axis. Class instances return a scalar by default. Use reduction="none" when you want per-sample losses to log, to mask or to mine hard examples.

In distributed training the "average over the batch" is the average over the global batch; with a plain TensorFlow loop and tf.distribute you must scale by the global batch size yourself, which is why the custom-loop pages use reduction="none" followed by tf.nn.compute_average_loss. See Writing a Training Loop from Scratch and Distributed Training.

Sample weights and class weights

Weights enter in two places, both through fit():

import numpy as np
import keras

x = np.random.rand(1000, 20).astype("float32")
y = (np.random.rand(1000) < 0.05).astype("int32")      # 5 percent positives

model = keras.Sequential([keras.Input((20,)), keras.layers.Dense(16, activation="relu"), keras.layers.Dense(1)])
model.compile(optimizer="adam", loss=keras.losses.BinaryCrossentropy(from_logits=True))

# Class weights: keyed by class id, multiplied into each sample's loss
model.fit(x, y, epochs=3, class_weight={0: 1.0, 1: 19.0}, verbose=0)

# Sample weights: one number per sample (instance importance, recency, noise level)
w = np.where(y == 1, 19.0, 1.0).astype("float32")
model.fit(x, y, epochs=3, sample_weight=w, verbose=0)

class_weight suits single-output classification where classes are integer ids; sample_weight is the general mechanism and the one to use for per-token masks, multi-label problems, or tf.data datasets (provide (x, y, sample_weight) tuples). With reduction="mean_with_sample_weight" the loss is normalised by the weight sum, so weights change the relative emphasis but not the overall scale. See Tabular Data & Gradient Boosting and Problem Framing & ML Projects for when re-weighting is preferable to resampling.

Other built-in losses

  • Huber(delta=1.0) is quadratic for small errors and linear beyond delta; a robust alternative to MeanSquaredError. LogCosh behaves similarly.

  • MeanAbsolutePercentageError and MeanSquaredLogarithmicError suit targets spanning orders of magnitude; both are undefined or unstable for zero or negative targets.

  • CosineSimilarity returns the negative cosine similarity along an axis so that minimising it aligns vectors.

  • BinaryFocalCrossentropy and CategoricalFocalCrossentropy take gamma (and alpha) and down-weight easy examples; useful with heavy class imbalance, for example dense object detection.

  • Dice and Tversky are overlap losses for segmentation, typically combined with cross-entropy.

  • Hinge, SquaredHinge and CategoricalHinge expect targets in \(\{-1, 1\}\) for the binary forms (labels in \(\{0, 1\}\) are converted) and give max-margin behaviour.

  • CTC aligns unsegmented sequences (speech, handwriting) and needs input and label lengths.

  • Poisson suits non-negative count targets, KLDivergence compares distributions (distillation).

Each class page on keras.io gives the exact constructor arguments.

Custom losses

A loss can be a plain function of (y_true, y_pred) returning one value per sample, or a subclass of keras.losses.Loss when it has hyperparameters. Write the maths with keras.ops so it runs on every backend (see Keras Multi-Backend).

import keras
from keras import ops


def asymmetric_mse(y_true, y_pred):
    # Penalise under-prediction three times more than over-prediction
    err = y_true - y_pred
    weight = ops.where(err > 0, 3.0, 1.0)
    return ops.mean(weight * ops.square(err), axis=-1)   # shape (batch,)


class WeightedHuber(keras.losses.Loss):
    def __init__(self, delta=1.0, name="weighted_huber", **kwargs):
        super().__init__(name=name, **kwargs)
        self.delta = delta

    def call(self, y_true, y_pred):
        err = ops.abs(y_true - y_pred)
        quad = ops.minimum(err, self.delta)
        lin = err - quad
        return ops.mean(0.5 * ops.square(quad) + self.delta * lin, axis=-1)

    def get_config(self):
        cfg = super().get_config()
        cfg["delta"] = self.delta
        return cfg


model = keras.Sequential([keras.Input((8,)), keras.layers.Dense(1)])
model.compile(optimizer="adam", loss=WeightedHuber(delta=2.0))

Source: https://keras.io/api/losses/ (the Loss base class)

Rules that avoid common failures:

  • Return a per-sample tensor with the batch axis first and let the reduction argument aggregate; do not average over the batch yourself.

  • Implement get_config() for every constructor argument, otherwise the loss cannot be restored with the model (see Saving Keras Models). When loading a .keras file, pass custom classes through custom_objects or register them with keras.saving.register_keras_serializable.

  • Cast to the compute dtype when mixing integers and floats (ops.cast), especially under mixed precision (see Mixed Precision).

  • Keep the computation differentiable; ops.argmax, rounding and comparisons give zero gradients.

  • A loss that needs the layer outputs or extra tensors rather than (y_true, y_pred) belongs in train_step or in a layer with add_loss, covered in Customizing fit() with train_step.

Multiple outputs and extra loss terms

import keras
from keras import layers

inp = keras.Input((32,))
h = layers.Dense(64, activation="relu", activity_regularizer=keras.regularizers.L1(1e-5))(inp)
cls = layers.Dense(5, name="cls")(h)
reg = layers.Dense(1, name="reg")(h)
model = keras.Model(inp, {"cls": cls, "reg": reg})

model.compile(
    optimizer="adam",
    loss={
        "cls": keras.losses.SparseCategoricalCrossentropy(from_logits=True),
        "reg": keras.losses.Huber(),
    },
    loss_weights={"cls": 1.0, "reg": 0.5},
)

With several outputs, loss may be a single loss, a list in output order or a dict keyed by output name, and loss_weights scales each term. Regularisation penalties (kernel_regularizer, activity_regularizer) and layer.add_loss(...) terms are added to the total automatically, so the reported training loss can be larger than the compiled loss alone.

Common mistakes

  • Forgetting from_logits=True with a linear last layer, or setting it with a softmax last layer.

  • Integer labels with CategoricalCrossentropy (use the sparse class) or one-hot labels with the sparse class.

  • Float labels for SparseCategoricalCrossentropy of the wrong shape, for example (batch, 1) against (batch,): shapes that broadcast silently can give a wrong mean.

  • Using MeanSquaredError on classification outputs, or cross-entropy on a regression target.

  • Comparing loss values across reduction settings or across weighted and unweighted runs.

  • Pre-Keras-3 habits: tf.keras.losses mean Keras 2 only if you installed the tf_keras package; in current TensorFlow tf.keras resolves to Keras 3 (see Migrating from Keras 2 to Keras 3).