Neural network formulas: a cheat sheet · Losses — classification

Categorical cross-entropy

The main loss of classification and of language models. We take it apart bone by bone: why the penalty is minus a logarithm, how cross-entropy splits into entropy and KL divergence, why together with softmax the gradient is simply s − y, what the loss landscape looks like, why labels are smoothed, and what perplexity is.

Javharbek Abdulatipov · 35 min read
$$\mathrm{CE}=-\sum_{k=1}^{K}y_k\log\hat{y}_k$$

Why we need it

A model has output class probabilities — say $(0.665,\,0.245,\,0.090)$ for “cat”, “dog”, “bird” — and the picture shows a cat. How good is that? We need one number that gets smaller as the probability of the correct answer grows, and that gradient descent can minimize. The standard answer is categorical cross-entropy (CE): here $\mathrm{CE}=-\ln0.665\approx0.408$.

Where it appears:

  • training multi-class classifiers — from logistic regression to ResNet and ViT: the last layer outputs logits, softmax turns them into probabilities, CE scores the answer;
  • language models — pre-training GPT, LLaMA, Qwen means minimizing the CE of the next token: the classes are vocabulary tokens, and $e^{\mathrm{CE}}$ is the famous perplexity;
  • knowledge distillation — the student minimizes CE against the teacher’s “soft” probabilities;
  • statistics — minimizing CE is equivalent to maximum likelihood for the categorical distribution;
  • information theory — CE is the mean code length when data come from a distribution $p$ but are encoded according to a model $q$.
The essentials in a minute

$\mathrm{CE}=-\sum_k y_k\ln\hat y_k$; for a one-hot label it is minus the log-probability of the correct class. A confident mistake is expensive: $-\ln0.1\approx2.303$ versus $-\ln0.9\approx0.105$. Together with softmax the gradient with respect to the logits is simply $s-y$, with no saturation. Cross-entropy = entropy + KL divergence, and $e^{\mathrm{CE}}$ is perplexity.

Intuition: a penalty for surprise

Suppose the model announces its probabilities in advance and then learns the correct answer. If it gave the correct class probability $p$, its “surprise” is $-\ln p$: at $p=1$ there is no surprise, at $p=0.5$ it is $\ln2\approx0.693$, and as $p\to0$ it grows to infinity. Cross-entropy is the model’s mean surprise on the data.

Why a logarithm? First, it turns the product of probabilities of independent examples into a sum. Second, it rewards honesty: among penalties that depend only on the probability the model assigned to the outcome that happened, with three or more outcomes only the logarithmic one (up to a positive factor and a constant) is minimized on average when the model reports its true probabilities.

Figure 1. Top: the penalty $-\ln p$ (blue) and the squared error $(1-p)^2$ for comparison; bottom: their derivatives in $p$. Drag the point. At $p=0.665$ the loss is $0.408$ nats, or $0.589$ bits, and the derivative is $-1.504$. Marked are a confident right answer ($p=0.9$, penalty $0.105$) and a confident mistake ($p=0.1$, penalty $2.303$).
What to notice

A confident mistake ($p=0.1$) costs 22 times more than a confident right answer ($p=0.9$). At $p=0.01$ the penalty is already $4.605$ and grows without bound, while the squared error $(1-p)^2$ stays below one ($0.980$). The derivative $-1/p$ grows without bound in magnitude as $p\to0$: the worse the answer, the harder the push.

The formula, bone by bone

$$\mathrm{CE}(y,\hat y)=-\sum_{k=1}^{K}y_k\ln\hat y_k$$
$y=(y_1,\dots,y_K)$
the true distribution; usually one-hot: $y_c=1$ for the correct class $c$ and $0$ for the rest;
$\hat y_k$
the predicted probability of class $k$, usually $\hat y=s=\operatorname{softmax}(z)$;
$\ln$
the natural logarithm: CE is measured in nats; with $\log_2$, in bits, $1$ nat $\approx1.443$ bits;
$-$
the log of a probability is negative; the minus makes the loss non-negative.

For a one-hot label only one term of the sum survives. Substituting $s=\operatorname{softmax}(z)$ gives a formula directly in the logits:

$$\mathrm{CE}=-\ln s_c=-z_c+\ln\sum_{j=1}^{K}e^{z_j}=\operatorname{LSE}(z)-z_c$$

The last form is the one that matters in practice: the loss is computed without an explicit softmax. For a batch of $N$ examples the losses are averaged:

$$\mathcal L=-\frac1N\sum_{n=1}^{N}\ln s^{(n)}_{c_n}$$

The cheat sheet’s example — logits $(2,\,1,\,0)$, the correct class is the first:

$k$$z_k$$s_k$$y_k$$-y_k\ln s_k$$s_k-y_k$
120.66510.408−0.335
210.245000.245
300.090000.090
Σ110.4080

Result: $\mathrm{CE}\approx0.408$, gradient $s-y\approx(-0.335,\,0.245,\,0.090)$. Had the third class been correct, the loss would be $-\ln0.090\approx2.408$ — a confident mistake.

CE and maximum likelihood

Let a model with parameters $\theta$ assign probability $q_\theta(c_n\mid x_n)$ to class $c_n$. The likelihood of the sample is the product $\prod_n q_\theta(c_n\mid x_n)$. The logarithm turns the product into a sum, and flipping the sign turns maximization into minimization:

$$\arg\max_\theta\prod_{n=1}^{N}q_\theta(c_n\mid x_n)=\arg\min_\theta\Bigl(-\frac1N\sum_{n=1}^{N}\ln q_\theta(c_n\mid x_n)\Bigr)=\arg\min_\theta\mathcal L$$

Minimizing the mean CE is the same as finding the maximum-likelihood estimate for the categorical distribution. So CE is not an arbitrary choice but the “native” loss of a probabilistic classifier.

Entropy, cross-entropy and KL divergence

The name comes from information theory. Let events come from a distribution $p$ while we encode them according to a model $q$. Then:

$$H(p)=-\sum_k p_k\ln p_k,\qquad H(p,q)=-\sum_k p_k\ln q_k,\qquad\mathrm{KL}(p\,\|\,q)=\sum_k p_k\ln\frac{p_k}{q_k}$$
$$H(p,q)=H(p)+\mathrm{KL}(p\,\|\,q)$$

$H(p)$ is the irreducible uncertainty of the data themselves (the entropy), and $\mathrm{KL}(p\,\|\,q)\ge0$ is the penalty for the model $q$ differing from the truth (Gibbs’ inequality; equality only when $q=p$). So the minimum of cross-entropy over $q$ is reached at $q=p$ and equals $H(p)$. For a one-hot label $H(y)=0$, and CE coincides with the KL divergence.

Figure 2. The target $p$ (black point) and the prediction $q$ (red) in the three-class simplex; both points can be dragged. The shading and level lines show $\mathrm{KL}(p\,\|\,q')$ for every possible prediction $q'$ (levels $0.05$, $0.25$, $0.75$): it is lightest at $p$ itself. On the right, the split $H(p,q)=H(p)+\mathrm{KL}(p\,\|\,q)$. With $p=(0.7,\,0.2,\,0.1)$ and $q=(0.25,\,0.5,\,0.25)$: $H(p)\approx0.802$, $\mathrm{KL}\approx0.446$, $H(p,q)\approx1.248$ nats ($1.800$ bits). Put $q$ on $p$ and the KL vanishes; drag $p$ to a vertex and $H(p)$ vanishes.
Why KL ≥ 0

By Jensen’s inequality for the concave logarithm (sums over $k$ with $p_k>0$):

$$-\mathrm{KL}(p\,\|\,q)=\sum_k p_k\ln\frac{q_k}{p_k}\le\ln\sum_k p_k\frac{q_k}{p_k}=\ln\sum_{k:\,p_k>0}q_k\le\ln1=0$$

Equality holds only when $q_k=p_k$ for every $k$.

Bits or nats

With $\log_2$ cross-entropy is measured in bits — literally the mean number of bits per event under the optimal code built from $q$. Machine learning uses the natural logarithm: derivatives are simpler and the minimum is the same. Conversion: $1$ nat $=1/\ln2\approx1.443$ bits.

The derivative: why softmax + CE give s − y

Let us compute the gradient of the loss with respect to the logits. One can go through the softmax Jacobian, but the form $\mathrm{CE}=\operatorname{LSE}(z)-z_c$ is shorter: the derivative of LSE is softmax (see the softmax page), and the derivative of $z_c$ with respect to $z_k$ is $y_k$.

$$\frac{\partial\,\mathrm{CE}}{\partial z_k}=\frac{\partial\operatorname{LSE}(z)}{\partial z_k}-\frac{\partial z_c}{\partial z_k}=s_k-y_k$$
Derivation through the Jacobian (chain rule)

The derivative with respect to the probabilities: $\partial\,\mathrm{CE}/\partial s_i=-y_i/s_i$. The softmax Jacobian: $\partial s_i/\partial z_k=s_i(\delta_{ik}-s_k)$. By the chain rule:

$$\frac{\partial\,\mathrm{CE}}{\partial z_k}=\sum_i\Bigl(-\frac{y_i}{s_i}\Bigr)s_i(\delta_{ik}-s_k)=-\sum_i y_i\delta_{ik}+s_k\sum_i y_i=s_k-y_k$$

The last step uses $\sum_i y_i=1$. The factors $s_i$ from the Jacobian cancel the denominators $1/s_i$ from the logarithm — the whole matrix collapses into a difference. The formula holds for any target $y$ summing to 1, not only one-hot (for example, with label smoothing).

This formula has three important consequences:

  • the gradient is bounded: every component $s_k-y_k$ lies in $(-1,\,1)$, and they sum to 0 — the correct logit is pulled up exactly as much as the others together are pulled down;
  • no saturation on mistakes: if the model is confidently wrong ($s_c\to0$), the gradient on the correct logit tends to $-1$, not to zero. Compare with MSE on top of softmax, where the Jacobian factors kill the gradient precisely when the error is large (see the section on CE and MSE);
  • fading on success: as $s\to y$ the gradient tends to 0 — well-learned examples barely affect training.
Figure 3. One example with logits $(2,\,1,\,0)$ and the first class correct. On the right the bars are the prediction $s$, the black shelves the target $y$; the arrows go from $s_k$ to $y_k$, and the numbers are $s_k-y_k$ (a step moves the logit $z_k$ by $-\eta(s_k-y_k)$). Press “Step”: the logits are updated by $z\leftarrow z-\eta(s-y)$ with $\eta=1$, and the loss falls: $0.408\to0.258\to0.187\to0.146$, and after 10 steps $0.058$. Make class 3 the correct one — the loss becomes $2.408$ and the gradient $(0.665,\,0.245,\,-0.910)$.
The second derivative: CE is convex in the logits

Differentiate $s_k-y_k$ once more: the Hessian of CE in the logits equals the softmax Jacobian, $\nabla^2_z\,\mathrm{CE}=\operatorname{diag}(s)-ss^\top$. This matrix is positive semi-definite, so CE is a convex function of the logits, and for softmax regression $z=Wx+b$ the loss is convex in $(W,b)$: there are no bad local minima. In the direction $\mathbf 1$ the matrix is singular — shifting all logits does not change the loss.

The loss landscape in 3D

Fix the third logit $z_3=0$ and draw the loss as a function of the other two. For correct class 1:

$$\mathrm{CE}(z_1,z_2)=\ln\bigl(e^{z_1}+e^{z_2}+1\bigr)-z_1=\ln\bigl(1+e^{z_2-z_1}+e^{-z_1}\bigr)$$

Where $z_1$ is much larger than both $z_2$ and zero, both exponentials under the logarithm are small and the loss is close to 0. Where the first class loses, the loss grows almost linearly — roughly as $\max(z_2,0)-z_1$. The result is a convex “valley” that slopes gently down but never reaches zero.

Figure 4. On the left, the surface $\mathrm{CE}(z_1,z_2,0)$ for the chosen correct class (it can be rotated). On the right, the top view: colour and level lines show the loss, the arrows the anti-gradient $-(s-y)$ in $z_1$ and $z_2$. The red point can be dragged. “Play” runs gradient descent on $z_1$, $z_2$ with step $0.8$ from the point $(2,\,1)$: the loss goes $0.408\to0.132$ in 5 steps, $0.079$ in 10 and $0.013$ in 79, while the point keeps moving right and down — the minimum is out of reach.
There is no minimum

For a one-hot target the infimum of CE is 0, but it is reached only with an infinite margin of the correct logit. If a model can separate the training data perfectly, CE keeps decreasing as the logits grow, and the weights run off to infinity. The cures are weight regularization, early stopping and label smoothing.

Label smoothing

Label smoothing replaces the one-hot target with a mixture with the uniform distribution:

$$y^{\mathrm{LS}}_k=(1-\varepsilon)\,y_k+\frac{\varepsilon}{K}$$

The correct class gets $1-\varepsilon+\varepsilon/K$, each of the others $\varepsilon/K$. Now the loss has a genuine minimum: the gradient $s-y^{\mathrm{LS}}$ vanishes when $s=y^{\mathrm{LS}}$. If all wrong logits are equal and the correct one is ahead of them by $m$, the optimal margin is finite:

$$s_c=\frac{e^{m}}{e^{m}+K-1}=1-\varepsilon+\frac{\varepsilon}{K}\quad\Longrightarrow\quad m^{*}=\ln\Bigl(1+\frac{K(1-\varepsilon)}{\varepsilon}\Bigr)$$
Figure 5. The loss and its derivative as functions of the margin $m$ of the correct logit (the other $K-1$ logits are equal). Without smoothing (dashed) the loss decreases monotonically and tends to 0 only as $m\to\infty$; the derivative is always negative. With smoothing $\varepsilon=0.1$ and $K=3$ a minimum appears: $m^*=\ln28\approx3.332$, where the probability of the correct class equals the target $0.9333$ and the loss equals the target’s entropy $H(y^{\mathrm{LS}})\approx0.291$. For $K=10$: $m^*\approx4.511$.

Label smoothing (Szegedy et al., 2016, Inception-v3) limits the growth of the logits and usually improves calibration; it is used, for example, in the original Transformer with $\varepsilon=0.1$. The price: the model is never 100% sure any more, and the information about class similarity in its logits is partly erased, which can hurt distillation (Müller et al., 2019).

CE versus MSE: why classifiers are trained on cross-entropy

Why not train a classifier with the squared error $\|s-y\|^2$ between the probabilities and the one-hot label? Compare the gradients with respect to the logits:

$$\frac{\partial\,\mathrm{CE}}{\partial z}=s-y,\qquad\frac{\partial\,\|s-y\|^2}{\partial z}=J^{\top}\,2(s-y)=2\,s\odot\bigl((s-y)-\langle s-y,\,s\rangle\,\mathbf 1\bigr)$$

The MSE gradient carries a factor $s$ from the Jacobian. If the model is confidently wrong — almost all the mass sits on one wrong class — the gradient nearly vanishes: for small $s_k$ the factor $s_k$ is small, and for the favourite wrong class the bracket is almost zero. The model does not “hear” its own gross mistake. The CE gradient has no such factor.

Figure 6. The same data and the same “confidently wrong” start: the weights point at the centres of other classes, accuracy $3.3\%$. Two copies of softmax regression train in parallel with gradient descent, step $0.5$ — one on CE, the other on MSE. The mean gradient norm in the logits at the start: $1.3$ for CE and $0.13$ for MSE. After 10 steps the accuracy is $85.6\%$ versus $5.6\%$, after 50 it is $93.3\%$ versus $25.6\%$; MSE catches up only by step 100 ($90.0\%$), and by step 200 both models reach $95.6\%$.
When the squared error is still used

The squared error between probabilities and the label is called the Brier score and is useful as a calibration metric. For training classifiers CE is almost always the choice: it is convex in the logits and does not saturate on mistakes.

Language models and perplexity

At every position $t$ a language model predicts the distribution of the next token over a vocabulary of $V$ tokens (tens or hundreds of thousands). This is classification into $V$ classes, and the loss is the mean cross-entropy over positions:

$$\mathcal L=-\frac1T\sum_{t=1}^{T}\ln p_\theta(x_t\mid x_{<t}),\qquad\mathrm{PPL}=e^{\mathcal L}=\Bigl(\prod_{t=1}^{T}\frac{1}{p_\theta(x_t\mid x_{<t})}\Bigr)^{1/T}$$

Perplexity is the exponential of CE, i.e. the geometric mean of the values $1/p_t$. It reads as an “effective number of choices”: a model that always spreads its probability uniformly over $k$ tokens, the correct one always among them, has perplexity exactly $k$. A model that knows nothing about the language (uniform over the vocabulary) has $\mathcal L=\ln V$ and $\mathrm{PPL}=V$.

Figure 7. The loss $-\ln p_t$ on every token of a sentence (a teaching example: the probabilities are set by hand). The orange line is the mean, i.e. CE; the dashed line is $\ln V$ for a vocabulary of $V=50{,}000$. At $\lambda=1$: $\mathrm{CE}\approx1.086$, perplexity $\approx2.963$ — on average the model hesitates between three options; the first word costs most ($p=0.05$, penalty $3.00$). The slider $\lambda$ multiplies the logits: at $\lambda=0.5$ the perplexity is already $\approx263.5$, at $\lambda=0$ the distribution is uniform, $\mathrm{CE}=\ln50{,}000\approx10.82$ and the perplexity is $50{,}000$.
Compare perplexities with care

Perplexity depends on the tokenizer: on the same text a model with larger tokens makes fewer predictions, and each one is harder. Only models with the same vocabulary on the same data can be compared — or switch to bits per character or byte.

In code

The main rule is to compute CE from the logits through log-softmax: $\mathrm{CE}=\operatorname{LSE}(z)-z_c$. The route “softmax, then logarithm” gives $\ln0=-\infty$ on confident mistakes: for logits $(0,\,800,\,0)$ and the first class correct, naive code returns inf, while the stable one returns the exact answer $800$.

pythonimport numpy as np
np.set_printoptions(precision=3)

def log_softmax(z):
    z = z - z.max(axis=-1, keepdims=True)          # stability: the max trick
    return z - np.log(np.exp(z).sum(axis=-1, keepdims=True))

def cross_entropy(logits, y):
    """Mean CE over a batch. logits: (N, K), y: (N,) — class indices."""
    logp = log_softmax(logits)
    return -logp[np.arange(len(y)), y].mean()

def cross_entropy_grad(logits, y):
    # dCE/dz = (softmax(z) − onehot(y)) / N
    s = np.exp(log_softmax(logits))
    s[np.arange(len(y)), y] -= 1
    return s / len(y)

z = np.array([[2.0, 1.0, 0.0]])
print(cross_entropy(z, np.array([0])))        # ≈ 0.4076
print(cross_entropy(z, np.array([2])))        # ≈ 2.4076 — a confident mistake
print(cross_entropy_grad(z, np.array([0])))   # [[-0.335  0.245  0.09 ]]
print(cross_entropy(z + 1000, np.array([0]))) # ≈ 0.4076 — no overflow
pythonimport torch
import torch.nn.functional as F

logits = torch.tensor([[2.0, 1.0, 0.0]], requires_grad=True)
target = torch.tensor([0])                  # a class index, not one-hot
loss = F.cross_entropy(logits, target)      # tensor(0.4076): log_softmax + NLL
loss.backward()
print(logits.grad)                          # tensor([[-0.3348,  0.2447,  0.0900]])

F.cross_entropy(logits, target, label_smoothing=0.1)   # tensor(0.5076)

# A language model: logits (B, T, V), tokens (B, T)
B, T, V = 2, 5, 50000
lm_logits = torch.randn(B, T, V)
tokens = torch.randint(0, V, (B, T))
loss = F.cross_entropy(lm_logits.reshape(-1, V), tokens.reshape(-1))
print(torch.exp(loss))                      # perplexity: of order V for random logits
A PyTorch checklist

F.cross_entropy / nn.CrossEntropyLoss takes logits (no softmax!) and class indices of type long — or probabilities of the same shape as the logits. Useful parameters: label_smoothing, weight (class weights for imbalance), ignore_index (for example, padding). Classes must sit in the second dimension, so logits of shape $(B,T,V)$ are easiest to turn into $(BT,V)$ with reshape.

Common mistakes

  1. A softmax before CrossEntropyLoss — a double softmax: the probabilities are squeezed, the loss cannot reach zero, the gradients are distorted. Pass logits.
  2. np.log(softmax(z)) instead of log-softmax — on a confident mistake the probability rounds to 0, the loss becomes inf and the gradient NaN. The “patch” clip(p, 1e-7, 1) saves you from infinity but cuts off the gradient; LSE is the right way.
  3. Mixing up one-hot and class indices. In Keras these are different functions: categorical_crossentropy expects one-hot, sparse_categorical_crossentropy expects indices. In PyTorch indices must be long, and probability targets must have the same shape as the logits.
  4. Sum instead of mean. With reduction='sum' the loss and gradient grow with the batch size, and a tuned learning rate stops fitting.
  5. Ignoring class imbalance. CE averages over examples, so a rare class barely affects the gradient. Class weights (weight) or Focal Loss help.
  6. Incomparable numbers: losses in nats and in bits, perplexities of models with different tokenizers.
  • Softmax: gives the probabilities $s$; together with CE, the gradient $s-y$, and $\mathrm{CE}=\operatorname{LSE}(z)-z_c$.
  • BCE: the case $K=2$ with one output: $-\bigl[y\ln\hat y+(1-y)\ln(1-\hat y)\bigr]$.
  • Sigmoid: for two classes softmax reduces to the sigmoid, and CE turns into BCE.
  • Focal Loss: $-(1-p_t)^\gamma\ln p_t$ — cross-entropy damped on easy examples.
  • MSE: on top of softmax it saturates on confident mistakes (see the section on the comparison).
  • Adam: the optimizer usually used to minimize CE in deep networks.

Summary

1) For a one-hot label $\mathrm{CE}=-\ln s_c$ — the model’s surprise at the correct answer; its mean over the data is minus the log-likelihood divided by $N$. 2) $H(p,q)=H(p)+\mathrm{KL}(p\,\|\,q)$: the minimum over $q$ is at $q=p$. 3) With softmax the gradient in the logits is $s-y$: bounded, not saturating on mistakes and vanishing on success; CE is convex in the logits. 4) With one-hot targets the minimum is out of reach — the logits grow; label smoothing makes the optimum finite. 5) Compute CE from the logits via log-sum-exp; $e^{\mathrm{CE}}$ is perplexity.

Check yourself

1. The model gave the correct class probability $0.25$. What is the CE?
2. What is the gradient of CE with respect to the logits when the probabilities come from softmax?
3. A model answers uniformly over 10 classes. What are its CE and perplexity?
4. For which prediction $q$ is the cross-entropy $H(p,q)$ smallest?
5. Label smoothing with $\varepsilon=0.1$ and $K=3$. What probability of the correct class does training tend to?