Sign in

NLL

Negative Log-Likelihood

The negative log-likelihood for class labels: minus the log-probability the model assigned to the correct class, given log-probabilities as input.

Overview

A probabilistic classifier assigns a probability to every class. A good one gives high probability to what actually happened. The likelihood of the training labels is the product of the probabilities given to each correct class, and taking the negative log turns that product into a sum to be minimised. Per example, the loss is simply minus the log-probability of the right class. This template expects the model to output log-probabilities already. Paired with log_softmax on logits it is exactly softmax cross-entropy, split into its two halves.

A short history

Ronald Fisher developed the method of maximum likelihood between 1912 and 1922: choose the parameters under which the observed data is most probable. Taking the negative logarithm turns a product of probabilities into a sum that can be minimised. Most standard losses are special cases: squared error for Gaussian noise and cross-entropy for class labels.

How it works

  1. Take log-probabilities of shape (N, C) and a target class index for each row. Use log_softmax to get them from logits.
  2. For each row, read off the entry at the target class and negate it.
  3. Skip rows whose target equals ignore_index: zero loss, zero gradient.
  4. Reduce with reduction. The mean divides by the number of counted rows.
  5. In backward, the gradient is −1-1 at the target class of each counted row and 0 elsewhere, divided by the number of counted rows for the mean.

Watch out for

  • The input must be log-probabilities. Passing raw logits gives a loss that can be driven to minus infinity, and passing probabilities gives values between −1-1 and 0. Neither raises an error.
  • Computing softmax and then taking the log separately loses precision. Use the provided log_softmax, which works on the logits directly.
  • The loss is unbounded as the true-class probability approaches zero, so a few mislabelled examples can dominate.
  • The gradient with respect to the log-probabilities is not predicted minus target. That simpler form only appears after chaining through the log-softmax.

Use cases

When to use it

When the model already produces log-probabilities, for example after a log-softmax layer or from a model whose outputs are combined in log space, such as a mixture or a sequence model.

In industry

Language models
Language models are evaluated by negative log-likelihood per token, and perplexity is its exponential.
Speech recognition
Acoustic and sequence models are trained to maximise the log-probability of the correct transcript given the audio.
Insurance and risk
Actuarial models for claim counts are fitted by maximum likelihood under a Poisson or similar distribution.

Choosing it: what must hold

  • A model whose outputs are valid log-probabilities, for example the result of a log-softmax.
  • One correct class index per example.
  • A reason to keep the log-softmax separate from the loss, such as reusing the log-probabilities elsewhere.

When to choose something else

IfUse instead
The model outputs raw scoresSoftmax cross-entropy, which applies the log-softmax for you
The labels are independent yes or no answersBinary cross-entropy
The target is a full distribution, not one classKL divergence

Math foundations

  1. The likelihood of the labels

    ∏i=1Npi, yi\prod_{i=1}^{N} p_{i,\,y_i}

    The probability the model gives to the whole set of observed labels, assuming the examples are independent. Training aims to make it large.

  2. The loss for one example

    ℓi=−ln⁡pi, yi=− Li, yi\ell_i = -\ln p_{i,\,y_i} = -\,L_{i,\,y_i}

    Minus the log-probability of the correct class. With log-probabilities LL as input it is a lookup and a sign change.

  3. The mean over counted rows

    L=−1∣V∣∑i∈VLi, yi\mathcal{L} = -\frac{1}{\lvert V \rvert}\sum_{i \in V} L_{i,\,y_i}

    The log turns the product into a sum, and maximising the likelihood becomes minimising this average. VV is the set of rows not ignored.

  4. The gradient

    ∂ℓi∂Li,c=− 1[c=yi]\frac{\partial \ell_i}{\partial L_{i,c}} = -\,\mathbf{1}[c = y_i]

    Only the entry at the true class matters, and the loss falls one for one as that entry rises.

  5. Composed with log-softmax

    Li,c=zi,c−ln⁡∑k=1Cezi,k    ⟹    ∂ℓi∂zi,c=pi,c−1[c=yi]L_{i,c} = z_{i,c} - \ln\sum_{k=1}^{C} e^{z_{i,k}} \;\;\Longrightarrow\;\; \frac{\partial \ell_i}{\partial z_{i,c}} = p_{i,c} - \mathbf{1}[c = y_i]

    Feeding log-softmax of the logits into this loss gives softmax cross-entropy, and the chain rule produces the familiar predicted minus target.

Symbols

pi,cp_{i,c}
the predicted probability of class c for example i
Li,cL_{i,c}
the log of that probability, log_probs
zi,cz_{i,c}
the logit of class c for example i
yiy_i
the true class of example i, target
N,CN, C
the number of examples and of classes
VV
the set of rows whose target is not ignore_index
ℓi\ell_i
the loss for example i
L\mathcal{L}
the mean loss
1[c=yi]\mathbf{1}[c = y_i]
1 when c is the true class, otherwise 0

Worked by hand

Two examples share the predicted probabilities (0.7,0.2,0.1)(0.7, 0.2, 0.1). The first has true class 0 and the second has true class 2. Use ln⁡0.7=−0.3567\ln 0.7 = -0.3567 and ln⁡0.1=−2.3026\ln 0.1 = -2.3026.

ℓ1=−ln⁡0.7=0.3567\ell_1 = -\ln 0.7 = 0.3567
ℓ2=−ln⁡0.1=2.3026\ell_2 = -\ln 0.1 = 2.3026
L=0.3567+2.30262=1.3296\mathcal{L} = \frac{0.3567 + 2.3026}{2} = 1.3296

The mean loss is 1.3296. The second example, where the model gave the truth only 10 percent, contributes more than six times as much as the first.

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 NLLLoss, log_softmax
from config import NLLLossConfig

loss = NLLLoss(NLLLossConfig())
log_probs = log_softmax(np.array([[2.0, 1.0, 0.1], [0.5, 2.5, 0.3]]))   # (N=2, C=3)
target = np.array([0, 1])
print(loss.forward(log_probs, target))      # 0.3185, the same as cross-entropy on the logits
print(loss.backward(log_probs, target))     # -0.5 at the correct class of each row, 0 elsewhere
Read the implementation (62 lines)
"""Negative log-likelihood for categorical targets: loss = -log_probs[target].

NumPy only. `forward` returns the loss, `backward` its gradient with respect to the log-probabilities, and
`log_softmax` turns logits into the log-probabilities this loss expects.
"""
from __future__ import annotations

import numpy as np

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

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


class NLLLoss:
    """Minus the log-probability of the correct class, for inputs that are log-probabilities."""

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

    def _prepare(self, log_probs, target) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
        """Checked inputs: log_probs (N, C) as floats, mask of counted rows (N,), targets safe for indexing (N,)."""
        log_probs, target = np.asarray(log_probs, dtype=float), np.asarray(target)
        if log_probs.ndim != 2 or target.shape != (log_probs.shape[0],):
            raise ValueError(f"expected log_probs (N, C) and target (N,), got {log_probs.shape} and {target.shape}")
        target = target.astype(int)
        valid = target != self.config.ignore_index
        safe = np.where(valid, target, 0)
        if safe.min(initial=0) < 0 or safe.max(initial=0) >= log_probs.shape[1]:
            raise ValueError(f"target classes must lie in [0, {log_probs.shape[1]})")
        return log_probs, valid, safe

    def forward(self, log_probs: np.ndarray, target: np.ndarray):
        """log_probs: (N, C) log-probabilities. target: (N,) class indices. Returns a float, or (N,) for "none"."""
        log_probs, valid, safe = self._prepare(log_probs, target)
        per_row = -log_probs[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, log_probs: np.ndarray, target: np.ndarray) -> np.ndarray:
        """Gradient of the reduced loss with respect to log_probs, shape (N, C).

        -1 at the correct class of every counted row (divided by the number of counted rows for "mean"),
        0 everywhere else. For "none" the per-row gradient is returned unscaled.
        """
        log_probs, valid, safe = self._prepare(log_probs, target)
        grad = np.zeros_like(log_probs)
        grad[np.arange(len(safe)), safe] = -1.0 * valid
        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 NLLLoss(NLLLossConfig()), pass logits (2,1,0)(2, 1, 0) through the template's log_softmax, and call forward and backward with target 0. Compare the loss with 0.4076. Then add a second row with target -100 and confirm it changes neither the loss nor the divisor.

Check on learning

  1. Why work with the sum of log-probabilities instead of the product of probabilities?
    A way to think about it

    Multiply a thousand numbers below 1 in floating point and see what you get. Then consider which is easier to differentiate, a product or a sum.

  2. Someone passes raw logits to this loss by mistake. Training loss falls rapidly to large negative values. What is the model doing?
    A way to think about it

    The loss is minus the entry at the true class. With no normalisation the model can just make that entry enormous. A valid log-probability can never exceed 0.

  3. The gradient here is −1-1 at the true class, yet cross-entropy on logits has gradient p−1p - \mathbf{1}. Where does the pp come from?
    A way to think about it

    Differentiate the log-softmax: raising one logit lowers every log-probability through the shared normaliser. Chain that with the −1-1.

  4. Why split cross-entropy into log-softmax and this loss at all?
    A way to think about it

    Some models need the log-probabilities for other purposes, such as adding them along a sequence or mixing several predictors, before any loss is taken.