Sign in

Cross entropy

Softmax cross-entropy (categorical cross-entropy)

The standard multi-class loss: softmax over the scores, then the negative log of the probability given to the correct class.

Overview

A classifier produces one score per class. Cross-entropy turns the scores into probabilities with softmax and then looks at one number: the probability assigned to the right class. The loss is the negative log of that number. A probability of 1 costs nothing, a probability of one half costs about 0.69, and a probability near zero costs a great deal. Minimising it is the same as maximising the likelihood of the training labels. Its gradient on the scores is simply the predicted probabilities minus the true one-hot vector.

A short history

Cross-entropy was defined in Claude Shannon's 1948 information theory. Minimising it against one-hot labels is the same as maximum likelihood for a categorical model, the method behind multinomial logistic regression. Neural networks adopted it for classification once softmax outputs came into use, because unlike squared error its gradient does not vanish when the model is confidently wrong.

How it works

  1. Take the logits, shape (N, C), and the target class index for each row.
  2. Compute the log-softmax of each row, which is the log-probability of every class, in a way that cannot overflow.
  3. Pick out the log-probability of the target class and negate it. That is the loss for the row.
  4. Skip rows whose target equals ignore_index: they get zero loss and zero gradient.
  5. Reduce with reduction. The mean divides by the number of rows that were not ignored.
  6. In backward, each counted row's gradient is its softmax probabilities with 1 subtracted at the target class.

Watch out for

  • The loss expects raw logits. Passing probabilities or log-probabilities applies softmax twice and trains a blurred, underconfident model without any error.
  • A single confidently wrong prediction can dominate the batch, because the loss is unbounded as the true-class probability approaches zero. Mislabelled data causes exactly this.
  • With imbalanced classes the frequent classes dominate the mean. The template has no class weights, so rebalance the data or use focal loss.
  • The loss can only reach zero with infinite logits. A model trained to very low loss becomes overconfident, which label smoothing is designed to limit.

Use cases

When to use it

Any classification task with exactly one correct class per example: image classes, next-token prediction, intent detection. Use ignore_index to mask padding in sequences.

In industry

Language models
Large language models are trained with cross-entropy between the predicted distribution over the vocabulary and the token that actually came next.
Image classification
Classifiers trained on labelled photo collections such as ImageNet minimise cross-entropy over the set of categories.
Customer support
Intent classifiers that route a message to one of a fixed set of queues are trained with cross-entropy on labelled past messages.

Choosing it: what must hold

  • Exactly one correct class per example, from a fixed set of classes.
  • A model that outputs one raw score per class, with the softmax applied inside the loss.
  • Labels that are mostly correct, since the loss punishes confident disagreement with the label heavily.

When to choose something else

IfUse instead
Several labels can be true for one exampleBinary cross-entropy on each label
The model becomes overconfident or the labels are noisyLabel-smoothed cross-entropy
A few classes are rare and the easy majority dominates trainingFocal loss
There are millions of classesSampled softmax

Math foundations

  1. Probabilities from logits

    pc=ezc∑k=1Cezkp_c = \frac{e^{z_c}}{\sum_{k=1}^{C} e^{z_k}}

    Softmax turns the row of scores into a distribution over the CC classes.

  2. The loss for one example

    ℓ=−ln⁡py=−zy+ln⁡∑k=1Cezk\ell = -\ln p_y = -z_y + \ln \sum_{k=1}^{C} e^{z_k}

    The negative log-probability of the true class yy. The second form, a log-sum-exp minus the true score, is what is computed so that no probability is ever rounded to zero.

  3. Why it is called cross-entropy

    H(q,p)=−∑c=1Cqcln⁡pcH(q, p) = -\sum_{c=1}^{C} q_c \ln p_c

    The cross-entropy between a target distribution qq and the prediction pp. With a one-hot qq only the true class survives in the sum, which gives −ln⁡py-\ln p_y.

  4. The mean over counted rows

    L=1∣V∣∑i∈Vℓi\mathcal{L} = \frac{1}{\lvert V \rvert}\sum_{i \in V} \ell_i

    VV is the set of rows whose target is not ignore_index. Ignored rows do not dilute the average.

  5. Gradient with respect to the logits

    ∂ℓ∂zc=pc−1[c=y]\frac{\partial \ell}{\partial z_c} = p_c - \mathbf{1}[c = y]

    Predicted minus target. The true class is pushed up by 1−py1 - p_y and every other class is pushed down by its own probability. The entries sum to zero.

Symbols

zcz_c
the logit (raw score) for class c
pcp_c
the predicted probability of class c
yy
the index of the true class
CC
the number of classes
qcq_c
the target probability of class c (1 for the true class, 0 otherwise)
ℓ\ell
the loss for one example
L\mathcal{L}
the reduced loss
VV
the set of rows not ignored
1[c=y]\mathbf{1}[c = y]
1 when c is the true class, otherwise 0

Worked by hand

One example with logits (2,1,0)(2, 1, 0) and true class 0. Softmax gives p=(0.6652,0.2447,0.0900)p = (0.6652, 0.2447, 0.0900).

ℓ=−ln⁡0.6652=0.4076\ell = -\ln 0.6652 = 0.4076
∂ℓ∂z=(0.6652−1,  0.2447,  0.0900)=(−0.3348,  0.2447,  0.0900)\frac{\partial \ell}{\partial z} = (0.6652 - 1,\; 0.2447,\; 0.0900) = (-0.3348,\; 0.2447,\; 0.0900)
if the true class were 2:ℓ=−ln⁡0.0900=2.4076\text{if the true class were 2:} \quad \ell = -\ln 0.0900 = 2.4076

The loss is 0.4076 and the gradient entries sum to zero. Had the true class been the lowest scored one, the loss would be 2.4076, exactly 2 higher, the gap between the two logits.

Visual example

Loading the example.

Try this

  • Move across the curve: the height is what the model is charged.
  • Move each control and watch which part of the curve it changes.

Code sample

import numpy as np
from impl import CrossEntropy
from config import CrossEntropyConfig

loss = CrossEntropy(CrossEntropyConfig())
logits = np.array([[2.0, 1.0, 0.1], [0.5, 2.5, 0.3]])   # (N=2, C=3)
target = np.array([0, 1])                                # correct class per row
print(loss.forward(logits, target))                      # 0.3185
print(loss.backward(logits, target))                     # (softmax - one_hot) / 2
Read the implementation (67 lines)
"""Softmax cross-entropy for multi-class classification: loss = -log(softmax(logits)[target]).

NumPy only. `forward` returns the loss, `backward` its gradient with respect to the logits.
"""
from __future__ import annotations

import numpy as np

try:
    from .config import CrossEntropyConfig
except ImportError:  # run from the template's own folder
    from config import CrossEntropyConfig

def _log_softmax(z: np.ndarray, axis: int = -1) -> np.ndarray:
    """log(softmax(z)) along `axis`, with the maximum subtracted first so exp cannot overflow."""
    shifted = z - z.max(axis=axis, keepdims=True)
    return shifted - np.log(np.exp(shifted).sum(axis=axis, keepdims=True))


def _check(logits, target) -> tuple[np.ndarray, np.ndarray]:
    """Logits as a float array (N, C) and class indices as an int array (N,). Raises ValueError otherwise."""
    logits, target = np.asarray(logits, dtype=float), np.asarray(target)
    if logits.ndim != 2 or target.shape != (logits.shape[0],):
        raise ValueError(f"expected logits (N, C) and target (N,), got {logits.shape} and {target.shape}")
    return logits, target.astype(int)


class CrossEntropy:
    """Negative log-probability of the correct class under softmax(logits)."""

    def __init__(self, config: CrossEntropyConfig | None = None) -> None:
        self.config = config or CrossEntropyConfig()

    def _valid(self, logits: np.ndarray, target: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
        """Mask of the rows that count, and the targets with ignored rows pointed at class 0 so indexing works."""
        valid = target != self.config.ignore_index
        safe = np.where(valid, target, 0)
        if safe.min(initial=0) < 0 or safe.max(initial=0) >= logits.shape[1]:
            raise ValueError(f"target classes must lie in [0, {logits.shape[1]})")
        return valid, safe

    def forward(self, logits: np.ndarray, target: np.ndarray):
        """logits: (N, C) raw scores. target: (N,) class indices. Returns a float, or (N,) for "none"."""
        logits, target = _check(logits, target)
        valid, safe = self._valid(logits, target)
        per_row = -_log_softmax(logits)[np.arange(len(safe)), safe] * valid
        if self.config.reduction == "none":
            return per_row
        total = float(per_row.sum())
        return total / max(int(valid.sum()), 1) if self.config.reduction == "mean" else total

    def backward(self, logits: np.ndarray, target: np.ndarray) -> np.ndarray:
        """Gradient of the reduced loss with respect to the logits, shape (N, C).

        Per row it is softmax(logits) - one_hot(target), zero for ignored rows, divided by the number of
        counted rows for "mean". For "none" the per-row gradient is returned unscaled.
        """
        logits, target = _check(logits, target)
        valid, safe = self._valid(logits, target)
        grad = np.exp(_log_softmax(logits))
        grad[np.arange(len(safe)), safe] -= 1.0
        grad *= valid[:, None]
        if self.config.reduction == "mean":
            grad /= max(int(valid.sum()), 1)
        return grad

    __call__ = forward
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
7, run with python3 -m unittest -v

Practice

Build CrossEntropy(CrossEntropyConfig()) and call forward and backward on two rows of logits with targets 0 and 2. Then set the second target to -100 and confirm its gradient row is zero and the mean is taken over one row. Finally compare the loss of all-zero logits with ln⁡C\ln C.

Check on learning

  1. At the start of training a 1000-class model has a loss of about 6.9. Is that a good sign, a bad sign, or neither?
    A way to think about it

    Compute ln⁡1000\ln 1000. A model that knows nothing and spreads probability evenly has exactly this loss, so it is a useful check that the initialisation is sane.

  2. The gradient on the logits is predicted minus target. What does that imply about examples the model already classifies with probability 0.999?
    A way to think about it

    Their gradient is close to zero. Training effort flows to the examples that are still wrong or uncertain. Consider what happens if some of those are mislabelled.

  3. Validation accuracy keeps rising while validation loss also rises. How can both be true?
    A way to think about it

    Accuracy looks only at the top class. The loss also measures confidence. A few wrong answers given with growing certainty can outweigh many small gains.

  4. Why is padding handled with ignore_index instead of giving padded positions a real class?
    A way to think about it

    Count how many positions in a padded batch are padding. If they contributed, the model would be rewarded for predicting something trivial and the mean would be diluted.

  5. Adding the same constant to every logit of a row leaves the loss unchanged. What does that mean for the gradient?
    A way to think about it

    If moving along the all-ones direction changes nothing, the gradient has no component along it. Check this against the formula.