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
- Take log-probabilities of shape (N, C) and a target class index for each row. Use
log_softmaxto get them from logits. - For each row, read off the entry at the target class and negate it.
- Skip rows whose target equals
ignore_index: zero loss, zero gradient. - Reduce with
reduction. The mean divides by the number of counted rows. - In
backward, the gradient is 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 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
| If | Use instead |
|---|---|
| The model outputs raw scores | Softmax cross-entropy, which applies the log-softmax for you |
| The labels are independent yes or no answers | Binary cross-entropy |
| The target is a full distribution, not one class | KL divergence |
Math foundations
The likelihood of the labels
The probability the model gives to the whole set of observed labels, assuming the examples are independent. Training aims to make it large.
The loss for one example
Minus the log-probability of the correct class. With log-probabilities as input it is a lookup and a sign change.
The mean over counted rows
The log turns the product into a sum, and maximising the likelihood becomes minimising this average. is the set of rows not ignored.
The gradient
Only the entry at the true class matters, and the loss falls one for one as that entry rises.
Composed with log-softmax
Feeding log-softmax of the logits into this loss gives softmax cross-entropy, and the chain rule produces the familiar predicted minus target.
Symbols
- the predicted probability of class c for example i
- the log of that probability,
log_probs - the logit of class c for example i
- the true class of example i,
target - the number of examples and of classes
- the set of rows whose target is not
ignore_index - the loss for example i
- the mean loss
- 1 when c is the true class, otherwise 0
Worked by hand
Two examples share the predicted probabilities . The first has true class 0 and the second has true class 2. Use and .
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 elsewhereRead 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 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
- 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.
- 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.
- The gradient here is at the true class, yet cross-entropy on logits has gradient . Where does the 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 .
- 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.