← All tutorials

Cross-Entropy Loss

Cross-entropy scores a predicted probability against the true label: confident and right costs almost nothing, confident and wrong costs a lot. The labels decide which form to use, and KL Divergence picks up when the target is itself a set of chances.

On this page

1 Binary cross-entropy (BCE) 2 Categorical cross-entropy 3 Softmax competes, sigmoid does not 4 Why classification uses cross-entropy, not MSE 5 The scoring pipeline, end to end 6 KL divergence 7 Cross-entropy variants 8 References
LabelsSquashLoss
several classes can be truesigmoid per classbinary cross-entropy (BCE)
exactly one class is truesoftmax over classescategorical cross-entropy
a soft target (chances, not one class)softmax over classescross-entropy as the target's own spread plus KL

1 Binary cross-entropy (BCE)

BCE scores a yes-or-no prediction. The model says how likely a class is present, and BCE measures how wrong that probability was.

In RLHF (reinforcement learning from human feedback), a reward model learns which of two answers people preferred, and this card is its loss (Ouyang et al. 2022). The gap is its score for the first answer minus its score for the second. A sigmoid, an S-shaped curve that turns any score into a number between 0 and 1 (0 becomes 0.5, large positive scores land near 1, large negative ones near 0; its equation is in Section 3), turns the gap into a probability p, and label 1 means people preferred the first answer.

illustrative gapploss
+2.00.8810.13
−2.0, the pair backwards0.1192.13
BCE charges the negative log of the probability the model put on the true answer.
ℓi = −log pi
When the label yi is 1. pi is the predicted probability for example i: its logit z, the model's raw score, squashed by a sigmoid into a value between 0 and 1. The loss is near 0 when pi is near 1 and huge when pi is near 0: the table's 0.13 and 2.13.
ℓi = −log(1 − pi)
For label 0 the same charge falls on one minus pi, the probability of no.
ℓi = −[yi log pi + (1 − yi) log(1 − pi)]
Both cases in one line, the line the listing computes. yi is 1 or 0, so one term always vanishes: label 1 keeps the first line above, label 0 the second.
L = 1N Σi ℓi
The batch loss L averages the N examples (the listing also averages over classes). The loss is near 0 when the true answer got a high chance and grows fast when it got a low one; the categorical card in Section 2 keeps only the first line, and KL Divergence reads the same −log as surprise.

Each class is its own yes-or-no bet, so BCE handles classes that co-occur. The target is a multi-hot vector, one 0 or 1 per class, a 1 for every class present. Sigmoid plus BCE is exactly the loss logistic regression trains on.

import torch

def bce_with_logits_loss(
        logits, y):
    # logits, y: (N, C);
    # y is multi-hot 0 or 1
    p = torch.sigmoid(logits)
    lp = torch.log(p)
    lq = torch.log(1 - p)
    ll = y * lp + (1 - y) * lq
    return -ll.mean()
  1. 1Squashes each logit into p, the sigmoid, eq card in Section 3, line 1.
  2. 2The two charges, eq card in Section 1, lines 1 and 2.
  3. 3Keeps the log that matches each label, the bracket of the eq card in Section 1, line 3.
  4. 4Flips the sign and averages over examples and classes, eq card in Section 1, lines 3 and 4.

PyTorch's nn.BCEWithLogitsLoss computes the same from the logits in a numerically safer form.

2 Categorical cross-entropy

Categorical cross-entropy (CE) keeps only BCE's yes term, minus the log of the probability, for the one true class, because exactly one class can be true. A softmax exponentiates each logit and divides by the sum of those exponentials, so the C classes get positive chances that share one total of 1 (its equation is in Section 3).

The categorical loss reads only the correct class.
L = −log py
y is the correct class; only its probability py enters the loss. With a one-hot target this loss is all KL divergence, the extra cost of predicting with the model instead of the true distribution (Section 6). Section 3 works it for a cat photo.

The label can be a one-hot vector (all zeros except a single 1) or just the index of that 1. PyTorch takes both:

BCE, several tags can be true1cat0dog1car0birdmulti-hotCE, exactly one class is true0index1cat0dog0car0birdone-hot
Figure 1. Multi-hot for BCE, a 1 for each tag in the photo; one index, cat's 0, for CE.
import torch
from torch import nn

# the teacher's logits for
# cat, dog, car, bird
logits = torch.tensor(
    [[4.6, 2.2, 0.8, 0.0]])
# BCE: tags cat and car
multi_hot = torch.tensor(
    [[1., 0., 1., 0.]])
# CE: the one class, cat
index = torch.tensor([0])

bce = nn.BCEWithLogitsLoss()(
    logits, multi_hot)
ce = nn.CrossEntropyLoss()(
    logits, index)
  1. 1One example's logits, the table in Section 3.
  2. 2The two target shapes, the two rows of Figure 1.
  3. 3Computes both losses from the logits; bce averages four bets to 0.84, ce is 0.12, minus the log of cat's 0.890.

CE is the negative log likelihood of the true class: lower loss means higher probability. Maximum Likelihood and EM, section 6 derives it. CTC loss uses the same negative log over whole sequences, and contrastive learning's InfoNCE loss is categorical cross-entropy with the positive pair as the correct class (Contrastive Learning).

import torch

def cross_entropy_loss(
        logits, target):
    # logits: (N, C)
    # target: (N,) class ids
    probs = torch.softmax(
        logits, dim=1)
    n = len(target)
    rows = torch.arange(n)
    p_true = probs[rows, target]
    nll = -torch.log(p_true)
    return nll.mean()
  1. 1Turns each row of logits into chances that add to 1, the softmax, eq card in Section 3, line 2.
  2. 2Picks each example's chance of its correct class, py in the eq card in Section 2.
  3. 3Charges minus its log, eq card in Section 2, line 1, then averages over the batch.

3 Softmax competes, sigmoid does not

Softmax is a competition with a fixed prize: one class's probability grows only by taking probability from the others. Sigmoid is the opposite: the same logits become separate yes-or-no bets, the BCE case for labels that co-occur.

Use softmax when exactly one label is right, sigmoid when labels can co-occur. Pick the wrong one and the loss teaches the wrong lesson.

The teacher on the Knowledge Distillation page, a large trained model whose chances a small student model learns to copy, scores a cat photo for cat, dog, car and bird with illustrative logits, and the softmax turns them into chances.

classlogit zkexp(zk)chance pk
cat4.699.480.890
dog2.29.030.081
car0.82.230.020
bird0.01.000.009
sum111.731.000
Two ways to turn logits into probabilities.
p = 11 + exp(−z)
The sigmoid squashes one logit z into a probability p on its own. A large positive z drives p toward 1; a large negative z drives it toward 0. The reward model's gap of +2.0 in Section 1 becomes 0.881.
pk = exp(zk)Σc exp(zc)
The softmax exponentiates every logit and divides by their sum over the C classes, giving pk, the probability of class k, the table's last column. The classes share exactly 1, so when one class gets more confident, the others must get less. The same logits, flattened by a temperature, give the teacher's soft targets in KL Divergence.

With label cat, the loss of Section 2 is 0.12 for the teacher's 0.890 and 0.80 for an illustrative weaker model that puts 0.451 on cat.

With softmax the four bars share one total of 1.0
sum of the four bars: 1.00, always

Figure 2. Softmax bars share one total; sigmoid bars each bet alone.

4 Why classification uses cross-entropy, not MSE

Why not mean squared error (MSE), the average squared gap, for classification? Take one example with true label 1 and predicted probability p. (Regression uses squared error because its targets are numbers, not classes.)

Turned the wrong way round, the reward pair of Section 1 gives the preferred answer a probability of 0.119.

One example with true label 1 gets two different charges from the two losses.
ℓBCE = −log p
The BCE line for one example with label 1, p the predicted probability: 2.13 for the backwards pair.
ℓMSE = (1 − p)2
MSE charges the squared gap between the bet and 1: only 0.78 for the backwards pair.
Their gradients show how hard each loss pulls back.
∂ℓBCE∂p = 1p
The derivative in the line is how fast the loss changes when p moves, the slope of the loss at p. The absolute value, the two vertical lines, keeps its size and drops the sign: how hard BCE pulls p back up. It grows without limit as p falls: 8.39 for the backwards pair, 100 at a probability of 0.01.
∂ℓMSE∂p = 2(1 − p)
MSE's pull never exceeds 2: 1.76 for the backwards pair, 1.98 at a probability of 0.01. Through the sigmoid, by the chain rule, the push that reaches the logit z is the gap from p to 1 for BCE, while MSE's push is also multiplied by the sigmoid's slope, a factor that goes to zero as the prediction saturates. At a probability of 0.01 that is 0.99 against 0.02, so MSE's push fades exactly when the model is confidently wrong. Both cards build on the BCE card, and Section 5 runs its line step by step.
BCE MSE
0.20

Figure 3. Confidently wrong, BCE pulls on; MSE's pull caps at 2.

BCE pull
MSE pull

5 The scoring pipeline, end to end

Follow the reward pair of Section 1 from logit to loss. Its gap of +2.0 is the logit, the sigmoid of Section 3 turns it into 0.881, and the BCE line charges 0.881 against label 1 for a loss of 0.13.

1. Logit, gap +2.0

−40+4

2. Squash, +2.0 to 0.881

3. Probability 0.881

01

4. Target 1, gap 0.119

target
01

5. Loss 0.13

02.13, pair backwards

Figure 4. The loss grows with the gap between squashed score and target.

The reward pair, squashed and scored.
p = 11 + exp(−z)
The sigmoid turns the logit z, the gap +2.0, into the probability p, 0.881.
ℓ = −log p
Label 1, people preferred the first answer, so the loss is minus the log of p, 0.13 for 0.881, near 0 as p nears 1.
ℓ = −log(1 − p)
With label 0 the same charge falls on one minus p, here 0.119, a loss of 2.13, the backwards pair of Section 1.
z the logit (the green mark)p the probability (the orange bar)ℓ the loss (the red bar)

6 KL divergence

When the target is itself a set of chances, such as a distillation teacher's output or smoothed labels, cross-entropy splits into two parts.

Cross-entropy is the target's own spread plus the KL divergence of the target from the model.
H(y, p) = H(y) + KL(y ‖ p)
Here y is the target's chances over the classes, not one class. H(y, p), the cross-entropy, averages the minus log of the model's chances with the target's chances as weights; for a one-hot target it is the loss of Section 2, minus the log of the correct class's chance. H(y), the entropy, is the target's own spread and does not depend on the model, so minimizing cross-entropy minimizes KL by exactly the same amount. A one-hot target has entropy 0, so the categorical loss is all KL. KL Divergence works the split with numbers and shows why the order of its two slots matters.

7 Cross-entropy variants

Plain cross-entropy assumes the labels are exactly right and every class matters equally. Three variants relax that.

Each is one argument or one call in PyTorch and torchvision:

import torch
import torch.nn.functional as F
from torchvision.ops import (
    sigmoid_focal_loss)
# logits, index and multi_hot
# as in the nn listing above
smooth = F.cross_entropy(
    logits, index,
    label_smoothing=0.1)
focal = sigmoid_focal_loss(
    logits, multi_hot,
    gamma=2.0, reduction="mean")
# illustrative, one per class
class_weights = torch.tensor(
    [1., 2., 2., 4.])
weighted = F.cross_entropy(
    logits, index,
    weight=class_weights)
  1. 1Label smoothing, 0.1 of the target spread over all classes.
  2. 2Focal loss on the multi-hot target, focusing strength 2.
  3. 3Class weighting, a weight per class multiplying its loss.

One prediction, scored against one label. When the target is a set of chances, the next page, KL Divergence, takes over.

8 References

  1. Lin, T.-Y., et al. (2017). Focal Loss for Dense Object Detection. ICCV. arXiv:1708.02002.
  2. Ouyang, L., et al. (2022). Training Language Models to Follow Instructions with Human Feedback. NeurIPS. arXiv:2203.02155.
  3. Szegedy, C., et al. (2016). Rethinking the Inception Architecture for Computer Vision. CVPR. arXiv:1512.00567.