AI Logic

Regularization

Label Smoothing

Updated:

The flow of Label Smoothing and how labels are built. Left: one training step, in which the target labels of the mini-batch are smoothed and the cross-entropy with the model's prediction is used as the loss. Right: an example with K = 5 and ε = 0.1. Multiplying the target label (1 only for the correct class C) by 1 − ε and adding ε times the uniform distribution (0.2 for every class) yields a label with 0.92 for the correct class and 0.02 for the others

Background and overview

When a classification model is trained with cross-entropy, it keeps pushing the probability of the correct class toward 1. As a result, it tends to become an "overconfident" model that fits the training data with full confidence but fails on new data (overfitting), and even when wrong it outputs high probabilities.

Label Smoothing is a regularization method that prevents this problem by slightly blurring the target labels. Instead of a one-hot label with 1 for the correct class and 0 for the others, the target lowers the correct class to 1−ε1-\varepsilon and distributes that ε\varepsilon evenly over all classes. It was proposed in 2016 by Szegedy et al. in Section 7 of the paper on the image classification model Inception-v3 (an improvement on GoogLeNet (Inception)).

It does not change the model architecture, only the target used when computing the loss, so it can be added to any classification model with one line. Besides image classification, it is widely used in machine translation with the Transformer and in speech recognition.

Theory (constructing labels and the loss)

The explanation follows the equations in Section 7 of the original paper. Let KK be the number of classes, yy the correct class of a training example xx, and zkz_k the model outputs (logits).

  1. The model's prediction is the logits converted to probabilities with softmax. p(k)=exp⁡(zk)∑i=1Kexp⁡(zi)p(k) = \frac{\exp(z_k)}{\sum_{i=1}^{K} \exp(z_i)}
  2. The ordinary target label qq is one-hot (δk,y\delta_{k,y} is 1 when k=yk = y and 0 otherwise). q(k)=δk,yq(k) = \delta_{k,y}
  3. Mix it with a distribution u(k)u(k) fixed independently of the data, using the smoothing strength ε\varepsilon. In the paper's experiments, uu is the uniform distribution u(k)=1/Ku(k) = 1/K. q′(k)=(1−ε) δk,y+ε u(k)=(1−ε) δk,y+εKq'(k) = (1-\varepsilon)\,\delta_{k,y} + \varepsilon\,u(k) = (1-\varepsilon)\,\delta_{k,y} + \frac{\varepsilon}{K}
  4. Use the cross-entropy between the smoothed label q′q' and the prediction pp as the loss. ℓ=−∑k=1Kq′(k) log⁡p(k)\ell = -\sum_{k=1}^{K} q'(k)\,\log p(k)

As a result of step 3, the target for the correct class becomes 1−ε+ε/K1-\varepsilon+\varepsilon/K and the target for the other classes becomes ε/K\varepsilon/K. In the example in the figure above (K=5K=5, ε=0.1\varepsilon=0.1), the correct class gets 0.92 and the others 0.02. The paper's ImageNet experiments (K=1000K=1000) used ε=0.1\varepsilon=0.1, giving 0.9001 for the correct class and 0.0001 for the others.

The loss in step 4 can be split into the sum of two cross-entropies as follows (Section 7 of the paper).

H(q′,p)=(1−ε) H(q,p)+ε H(u,p)H(q', p) = (1-\varepsilon)\,H(q, p) + \varepsilon\,H(u, p)

The first term is the ordinary loss, and the second is a penalty measuring how far the prediction pp is from the uniform distribution uu. In other words, Label Smoothing is a regularizer that pulls the prediction back so it does not concentrate too much on one class, while preserving the ability to predict the correct answer.

Why it prevents overconfidence

Minimizing cross-entropy with one-hot labels requires the probability of the correct class p(y)p(y) to be 1. Softmax never reaches exactly p(y)=1p(y)=1, and the only way to approach it is to make the correct logit zyz_y ever larger than the other logits. The paper points out that this causes two problems.

  • Overfitting: Even if the model learns to assign probability 1 to every training example, that does not guarantee correct predictions on new data.
  • Reduced adaptability: The gradient of cross-entropy with respect to the logits is p(k)−q(k)p(k)-q(k), which is bounded between −1 and 1. Once the gaps between logits have grown large, further training has little corrective effect.

With the Label Smoothing target q′q', every class has a target of at least ε/K\varepsilon/K, so the loss grows if the probability of a single class approaches 1. Therefore, the gaps between logits settle at a finite size and no longer grow without bound.

As an analogy, instead of drilling only the answer "it is definitely this," it trains the model to answer "probably this, but other possibilities are not zero."

Experimental results

Results reported in the original paper and in Müller et al. (2019), which studied how Label Smoothing works.

TaskModelMetricWithoutWith
ImageNet image classificationInception-v2Top-1 error23.1%22.8%
ImageNet image classificationInception-v2Top-5 error6.3%6.1%
English→German translationTransformerBLEU (higher is better)25.325.8
English→German translationTransformerPerplexity (lower is better)4.674.92
  • Accuracy: In the original paper, both the top-1 and top-5 error rates on ImageNet dropped by about 0.2 points (ε=0.1\varepsilon=0.1).
  • Calibration: Calibration means that the probabilities a model outputs match how often it is actually correct (predictions made with probability 0.8 are right about 80% of the time). Müller et al. report that the expected calibration error (ECE, lower is better) of models trained with Label Smoothing dropped from 0.071 to 0.035 for Inception-v4 on ImageNet, and from 0.150 to 0.024 (ε=0.05\varepsilon=0.05) for ResNet-56 on CIFAR-100. This is about as effective as temperature scaling, which adjusts the probabilities after training.
  • Translation: For the Transformer, perplexity got worse while BLEU improved. Müller et al. explain that well-calibrated probabilities help beam search choose candidates better.

Practical considerations

It is safer not to use Label Smoothing for the teacher model in knowledge distillation. Müller et al. showed that knowledge distillation from a teacher trained with Label Smoothing yields a student with lower accuracy than distillation from a teacher trained without it. Because Label Smoothing makes the probabilities of the incorrect classes uniform, information about how similar classes are to each other, such as "this image is a dog but looks a little like a cat," disappears from the output.

  • Start with ε=0.1\varepsilon = 0.1: Both the original paper's ImageNet experiments and the Transformer paper use ε=0.1\varepsilon=0.1. When there are few classes or few label errors in the data, try smaller values such as 0.05. If it is too large, the target for the correct class drops too much and accuracy falls.
  • Check calibration when using the probability values themselves: Label Smoothing improves calibration, but the model is trained so that its probabilities on the training data do not exceed 1−ε+ε/K1-\varepsilon+\varepsilon/K. When using probabilities for decisions such as thresholds, check the relationship between probability and accuracy on validation data.
  • Do nothing at inference: Only the target during training changes. At inference, use the softmax output as usual.
  • Use it only for classification losses: It targets problems that predict class probabilities. It cannot be used as is for regression (predicting numerical values).

Comparison with other methods

All of these "soften the targets or output probabilities," but they differ in what they soften.

MethodWhat is softenedHow mass goes to incorrect classesWhen it is applied
Label SmoothingTarget labelsUniformly ε/K\varepsilon/K to all classesDuring training
Knowledge distillationTarget labels (the teacher's output is the target)According to the similarity the teacher perceivesDuring training (requires a teacher)
MixupBoth inputs and labelsOnly to the class of the mixed partnerDuring training
Temperature scalingPredicted probabilities (logits divided by a temperature)—After training
  • To curb overconfidence easily, Label Smoothing is the simplest: it only takes one extra argument to the loss.
  • To fix only the probabilities of an already trained model, choose temperature scaling, which requires no retraining.
  • To push image classification accuracy further, it is often combined with data augmentation such as Mixup.

PyTorch example

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

K = 5          # Number of classes
eps = 0.1      # Smoothing strength ε

logits = torch.tensor([[1.0, 0.5, 3.0, -1.0, 0.2]])  # Model output (logits)
target = torch.tensor([2])                           # The correct class is 2 (C in the figure)

# 1. PyTorch's cross-entropy applies Label Smoothing via the label_smoothing argument
loss_builtin = nn.CrossEntropyLoss(label_smoothing=eps)(logits, target)

# 2. Build the smoothed label q' as in the paper and compute the loss
one_hot = F.one_hot(target, num_classes=K).float()
q_smooth = (1 - eps) * one_hot + eps / K          # q'(k) = (1 − ε)δ(k,y) + ε/K
print(q_smooth)  # tensor([[0.0200, 0.0200, 0.9200, 0.0200, 0.0200]])
loss_manual = -(q_smooth * F.log_softmax(logits, dim=-1)).sum(dim=-1).mean()

print(loss_builtin.item(), loss_manual.item())  # Same value


# In training: only the loss function changes; the model and inference stay the same
model = nn.Sequential(nn.Flatten(), nn.Linear(28 * 28, 256), nn.ReLU(), nn.Linear(256, 10))
criterion = nn.CrossEntropyLoss(label_smoothing=0.1)
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)

x = torch.randn(32, 1, 28, 28)        # Dummy mini-batch
y = torch.randint(0, 10, (32,))
loss = criterion(model(x), y)
optimizer.zero_grad()
loss.backward()
optimizer.step()

FAQ

Q. How should ε be chosen?
A.

Try 0.1 first. This is the value used in the original paper's ImageNet experiments (1000 classes) and in the Transformer translation paper. Compare accuracy on validation data, and when there are few classes, also try smaller values such as 0.05. If it is too large, the target probability for the correct class drops too much and accuracy falls.

Q. Is PyTorch's label_smoothing the same as the paper's formula?
A.

Yes. nn.CrossEntropyLoss(label_smoothing=ε) computes cross-entropy with a target of 1 − ε + ε/K for the correct class and ε/K for the other classes. This matches q′ in the paper with u set to the uniform distribution. The code example confirms that it gives the same value as the manually computed loss.

Q. Is it a problem that the output probability never reaches 1 with Label Smoothing?
A.

It does not affect classification accuracy, because the class with the highest probability is still chosen. As for the probability values themselves, in Müller et al.'s experiments they were closer to the actual accuracy than those of a normally trained model (improved calibration). However, when using probabilities for decisions such as thresholds, verify them on validation data first.

References

  1. C. Szegedy, V. Vanhoucke, S. Ioffe, J. Shlens, and Z. Wojna, "Rethinking the Inception Architecture for Computer Vision," CVPR, 2016.
  2. R. Müller, S. Kornblith, and G. Hinton, "When Does Label Smoothing Help?," NeurIPS, 2019.
  3. A. Vaswani, N. Shazeer, N. Parmar, J. Uszkoreit, L. Jones, A. N. Gomez, Ł. Kaiser, and I. Polosukhin, "Attention Is All You Need," NeurIPS, 2017.
  4. PyTorch Documentation, "torch.nn.CrossEntropyLoss."