AI Logic

Loss Functions

Cross-Entropy

Updated:

Diagram of cross-entropy. Left: the flow of turning logits into probabilities with softmax and taking −log of the probability of the correct class to obtain the loss (a three-class example). Right: a graph of the loss −log p against the probability p of the correct class, where the loss rises sharply as p approaches 0

What is cross-entropy?

Cross-entropy is a loss function that measures how far the probability distribution pp output by a model is from the target distribution yy. It is the most widely used loss for training classifiers.

L=−∑k=1Kyklog⁡pkL = -\sum_{k=1}^{K} y_k \log p_k

Here, KK is the number of classes, pkp_k is the probability the model assigns to class kk, and yky_k is the target distribution. log is the natural logarithm. When the target is a single class cc (one-hot, with yc=1y_c = 1 and all others 0), only the term for the correct class remains in the sum, so it simplifies to:

L=−log⁡pcL = -\log p_c

In other words, the higher the probability assigned to the correct class, the smaller the loss, and the lower it is, the more sharply the loss grows. Concrete values are as follows.

Probability of the correct class pcp_c0.990.90.50.10.01
Loss −log⁡pc-\log p_c0.010.110.692.304.61

Raising 0.9 to 0.99 reduces the loss by only 0.1, but dropping 0.1 to 0.01 increases the loss by 2.3. A defining feature of cross-entropy is that it penalizes confident wrong predictions most heavily.

The name comes from information theory. It is the average "surprise" experienced by someone who believes in distribution pp when observing data generated from distribution yy, and it is minimized when pp matches yy. Cross-entropy is the sum of the entropy of yy itself and the KL divergence, and since the target distribution does not change during training, minimizing cross-entropy is equivalent to minimizing the KL divergence. It also equals the negative logarithm of the probability (likelihood) of the correct labels (the negative log-likelihood), so training with cross-entropy is equivalent to maximum likelihood estimation.

Combining with softmax

The values zkz_k output by the network's last fully connected layer (logits) are not probabilities. They are therefore converted into probabilities with the softmax function before computing the cross-entropy.

pk=ezk∑j=1Kezjp_k = \frac{e^{z_k}}{\sum_{j=1}^{K} e^{z_j}}

Check this with the example on the left of the diagram at the top.

  1. Suppose the logits are z=(2.0, 1.0, 0.1)z = (2.0,\ 1.0,\ 0.1).
  2. Softmax turns them into probabilities p=(0.66, 0.24, 0.10)p = (0.66,\ 0.24,\ 0.10) (summing to 1).
  3. If the correct answer is class 1, the loss is −log⁡0.66≈0.42-\log 0.66 \approx 0.42.

Combining softmax with cross-entropy gives a very simple gradient with respect to the logits:

∂L∂zk=pk−yk\frac{\partial L}{\partial z_k} = p_k - y_k

In the example above, the gradient is (0.66−1, 0.24, 0.10)=(−0.34, 0.24, 0.10)(0.66 - 1,\ 0.24,\ 0.10) = (-0.34,\ 0.24,\ 0.10). The correct logit is pushed upward and the others downward, by the size of the "difference between prediction and target." The further off the prediction, the larger the gradient, so learning does not stall while the model is wrong.

Using MSE (mean squared error) on probability outputs makes the gradient nearly 0 when softmax or the sigmoid function saturates (outputs stuck at 0 or 1), so learning barely progresses even when the prediction is badly wrong. In cross-entropy, the log cancels out softmax's exponential, so this problem is unlikely, and cross-entropy is the standard choice for classification.

For binary classification, the sigmoid function outputs a single probability pp, and the following binary cross-entropy is used.

L=−[ ylog⁡p+(1−y)log⁡(1−p) ]L = -\left[\, y \log p + (1-y) \log (1-p) \,\right]

Caveats when using it in PyTorch

Pass logits, before softmax is applied, to nn.CrossEntropyLoss. This function computes the log of the softmax (log-softmax) and −log⁡-\log together internally. Applying softmax yourself before passing the values applies softmax twice, making both the loss and the gradient incorrect.

Keep the following points in mind as well.

  • Computing from logits also improves numerical stability: eze^{z} quickly overflows when zz is large, and if a probability is rounded to 0, the result is log⁡0\log 0. Computing log-softmax in one step avoids this with the trick of subtracting the largest logit before exponentiating (log-sum-exp).
  • Targets can be given as class indices or as probability distributions: For indices, pass integers such as torch.tensor([0, 2, ...]); for probabilities, pass a distribution whose length equals the number of classes. When passing probabilities, PyTorch does not check that they sum to 1, so ensure this yourself.
  • Label smoothing can be set with an argument: Specifying label_smoothing=0.1, for example, trains with the target distribution mixed with a uniform distribution (label smoothing).
  • Use nn.BCEWithLogitsLoss for binary and multi-label classification: It computes the sigmoid function and binary cross-entropy together, likewise in a numerically stable form.

Comparison with related loss functions

The table below compares cross-entropy with related loss functions from the same perspectives.

Loss functionWhen to useCharacteristics
Cross-entropyMulti-class classification (one correct answer per sample)Combined with softmax, minimizes −log of the probability of the correct class
Binary cross-entropyBinary classification, multi-label classificationOutputs a probability per class with the sigmoid function and computes each independently
Focal LossClassification with strong class imbalance (e.g., object detection)Reduces the loss of samples that are already classified correctly and focuses on hard samples
KL divergenceWhen two distributions should be brought closer (e.g., knowledge distillation)If the target distribution is fixed, it has the same minimizer as cross-entropy
MSERegression (predicting continuous values)When used for classification, gradients tend to become small when outputs saturate

Rough guidelines for choosing:

  • For multi-class classification, start with cross-entropy: It is the most standard choice, and the published settings of many models assume it.
  • If class imbalance is severe and accuracy on minority classes does not improve, try Focal Loss or per-class weights (the weight argument).

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F

# Example from the text: logits (2.0, 1.0, 0.1), correct answer is class 1 (index 0)
logits = torch.tensor([[2.0, 1.0, 0.1]], requires_grad=True)
target = torch.tensor([0])

loss = F.cross_entropy(logits, target)      # Computes softmax -> −log together internally
print(loss.item())                          # About 0.417 (= −log 0.659)

# The same value written with softmax and −log
p = torch.softmax(logits, dim=1)
print(-torch.log(p[0, 0]).item())           # About 0.417

# The gradient is p − y
loss.backward()
print(logits.grad)                          # About (−0.341, 0.242, 0.099)


# Usage in a classification model: do not put softmax after the output layer
model = nn.Sequential(nn.Flatten(), nn.Linear(28 * 28, 256), nn.ReLU(), nn.Linear(256, 10))
criterion = nn.CrossEntropyLoss(label_smoothing=0.0)   # Set to 0.1 etc. for label smoothing
images = torch.randn(64, 1, 28, 28)        # Dummy mini-batch
labels = torch.randint(0, 10, (64,))
loss = criterion(model(images), labels)     # Pass the logits as is
loss.backward()

# Apply softmax at inference only when prediction probabilities are needed
with torch.no_grad():
    probs = torch.softmax(model(images), dim=1)

FAQ

Q. Why take the log instead of using the probability directly?
A.

Maximizing the product of the correct-class probabilities over all data (the likelihood) becomes, after taking the log, minimizing the sum of −log p over the samples. A product becomes an extremely small number that is hard to handle, while a sum can be computed stably. In addition, the log cancels out softmax's exponential, so the gradient takes the simple form p − y.

Q. Is it a problem that the loss does not reach 0?
A.

No. The loss is 0 only when probability 1 is assigned to the correct class. Softmax always leaves some probability for every class, so even on the training data the loss stays at a small positive value. With label smoothing, it stops at a value even further from 0.

Q. Can the loss value give a rough sense of accuracy?
A.

Roughly, yes. For example, with 10 classes, a model that outputs the same probability 0.1 for every class has a loss of −log 0.1 ≈ 2.30. If the loss at the start of training is far from this value, suspect the initialization or data preprocessing.

References

  1. I. Goodfellow, Y. Bengio, and A. Courville, "Deep Learning," MIT Press, 2016, Chapter 6.
  2. A. Zhang, Z. C. Lipton, M. Li, and A. J. Smola, "Dive into Deep Learning," Section 4.1 Softmax Regression.
  3. PyTorch Documentation, "torch.nn.CrossEntropyLoss."
  4. I. Goodfellow, Y. Bengio, and A. Courville, "Deep Learning," MIT Press, 2016, Section 3.13 Information Theory.
  5. A. Zhang, Z. C. Lipton, M. Li, and A. J. Smola, "Dive into Deep Learning," Section 4.5 Concise Implementation of Softmax Regression (4.5.2 Softmax Revisited).
  6. PyTorch Documentation, "torch.nn.BCEWithLogitsLoss."