Sign in

Label smoothing

Label-smoothed cross-entropy

Cross-entropy against softened targets: the true class gets most of the probability and a small share is spread evenly over all classes.

Overview

Ordinary cross-entropy tells the model the right class has probability 1 and the others 0. The only way to match that is to make the true logit infinitely larger than the rest, so the model is pushed to be ever more confident. Label smoothing changes the target slightly. The true class gets a probability a little below 1, and the remainder is divided evenly among all classes. Now the best prediction is confident but finite. The model stops inflating its logits, tends to be better calibrated, and is less damaged by an occasional wrong label.

A short history

Christian Szegedy and colleagues introduced label smoothing in the 2015 paper 'Rethinking the Inception Architecture for Computer Vision'. One-hot targets push a classifier to make its winning score ever larger, which leads to overconfidence. Moving a small share of the target probability to the other classes removes that pressure. The original Transformer used it in 2017, and Müller, Kornblith and Hinton analysed in 2019 why it improves calibration.

How it works

  1. Take the logits, shape (N, C), and the target class index for each row.
  2. Build the smoothed target qq: every class gets s/Cs/C, and the true class gets an extra 1−s1 - s. smoothed_targets returns this.
  3. Compute the log-softmax of the logits.
  4. The loss for a row is the cross-entropy between qq and the prediction: minus the sum of qq times the log-probabilities.
  5. Reduce over rows with reduction.
  6. In backward, each row's gradient is softmax minus qq, divided by NN for the mean.

Watch out for

  • The loss can no longer reach zero. Its floor is the entropy of the smoothed target, so loss values are not comparable with unsmoothed runs.
  • Smoothing makes the outputs for wrong classes more uniform. That removes information a student model would learn from, so smoothed teachers can distil worse.
  • Conventions differ. Here the true class gets 1−s+s/C1 - s + s/C. Some libraries spread ss over the other C−1C - 1 classes only, which gives slightly different numbers.
  • Too much smoothing makes the model underconfident and can lower accuracy. Values much above 0.2 are rarely helpful.

Use cases

When to use it

Classification with many classes or somewhat noisy labels, where overconfidence hurts: image classifiers and sequence models commonly use a smoothing of 0.1.

In industry

Machine translation
The original Transformer was trained with label smoothing of 0.1, and it has remained a common setting for translation models.
Image classification
ImageNet training recipes for convolutional networks and vision transformers routinely include label smoothing.
Speech recognition
Attention-based speech recognisers use label smoothing to stop the decoder becoming overconfident in its next token.

Choosing it: what must hold

  • A multi-class problem trained with softmax cross-entropy.
  • A model that is overconfident, or labels with some noise in them.
  • No plan to use the model as a teacher for distillation, since smoothing removes information the student would learn from.

When to choose something else

IfUse instead
Labels are clean and you need the sharpest possible probabilitiesPlain softmax cross-entropy
The model will be distilled into a smaller onePlain cross-entropy for the teacher, then KL divergence for the student
The main problem is class imbalance, not overconfidenceFocal loss

Math foundations

  1. The smoothed target

    qc=(1−s) 1[c=y]+sCq_c = (1 - s)\,\mathbf{1}[c = y] + \frac{s}{C}

    A mix of the one-hot label and the uniform distribution. The true class gets 1−s+s/C1 - s + s/C, every other class gets s/Cs/C, and the total is 1.

  2. The loss

    ℓ=−∑c=1Cqcln⁡pc\ell = -\sum_{c=1}^{C} q_c \ln p_c

    Cross-entropy between the smoothed target and the predicted distribution pp. With s=0s = 0 it is ordinary cross-entropy.

  3. Split into two familiar parts

    ℓ=(1−s) (−ln⁡py)  +  s (−1C∑c=1Cln⁡pc)\ell = (1 - s)\,\big(-\ln p_y\big) \;+\; s\,\Big(-\frac{1}{C}\sum_{c=1}^{C} \ln p_c\Big)

    Ordinary cross-entropy, scaled down, plus a term that is the cross-entropy against a uniform target. The second term punishes giving any class a very low probability.

  4. Gradient with respect to the logits

    ∂ℓ∂zc=pc−qc\frac{\partial \ell}{\partial z_c} = p_c - q_c

    Predicted minus smoothed target. It is zero when p=qp = q, which happens at finite logits.

  5. Where the optimum sits

    zy−zc=ln⁡qyqc=ln⁡ ⁣(1+C (1−s)s)(c≠y)z_y - z_c = \ln\frac{q_y}{q_c} = \ln\!\Big(1 + \frac{C\,(1 - s)}{s}\Big) \qquad (c \ne y)

    At the minimum the true logit exceeds each other logit by this fixed, finite gap. Without smoothing the gap would be pushed toward infinity.

Symbols

ss
the smoothing share, smoothing in the config, default 0.1
CC
the number of classes
yy
the index of the true class
qcq_c
the smoothed target probability of class c
pcp_c
the predicted probability of class c, softmax of the logits
zcz_c
the logit of class c
ℓ\ell
the loss for one example
1[c=y]\mathbf{1}[c = y]
1 when c is the true class, otherwise 0

Worked by hand

Four classes, smoothing s=0.1s = 0.1, true class 0. Suppose the softmax output is p=(0.7,0.1,0.1,0.1)p = (0.7, 0.1, 0.1, 0.1). Use ln⁡0.7=−0.3567\ln 0.7 = -0.3567 and ln⁡0.1=−2.3026\ln 0.1 = -2.3026.

q=(0.9+0.025,  0.025,  0.025,  0.025)=(0.925,  0.025,  0.025,  0.025)q = \big(0.9 + 0.025,\; 0.025,\; 0.025,\; 0.025\big) = (0.925,\; 0.025,\; 0.025,\; 0.025)
ℓ=0.925×0.3567+3×0.025×2.3026=0.3299+0.1727=0.5026\ell = 0.925 \times 0.3567 + 3 \times 0.025 \times 2.3026 = 0.3299 + 0.1727 = 0.5026
∂ℓ∂z=p−q=(−0.225,  0.075,  0.075,  0.075)\frac{\partial \ell}{\partial z} = p - q = (-0.225,\; 0.075,\; 0.075,\; 0.075)

The loss is 0.5026, against 0.3567 for plain cross-entropy. The gradient on the true class is −0.225-0.225 instead of −0.3-0.3, so the push toward more confidence is weaker.

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 LabelSmoothingCrossEntropy
from config import LabelSmoothingCrossEntropyConfig

loss = LabelSmoothingCrossEntropy(LabelSmoothingCrossEntropyConfig(smoothing=0.1))
logits = 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.smoothed_targets(target, 3))                  # rows like [0.9333, 0.0333, 0.0333]
print(loss.forward(logits, target))                      # a little above the plain cross-entropy 0.3185
print(loss.backward(logits, target))                     # (softmax - smoothed targets) / 2
Read the implementation (63 lines)
"""Label-smoothed cross-entropy: cross-entropy against q = (1 - s) * one_hot + s / C.

NumPy only. `forward` returns the loss, `backward` its gradient with respect to the logits.
"""
from __future__ import annotations

import numpy as np

try:
    from .config import LabelSmoothingCrossEntropyConfig
except ImportError:  # run from the template's own folder
    from config import LabelSmoothingCrossEntropyConfig

def _log_softmax(z: np.ndarray, axis: int = -1) -> np.ndarray:
    """log(softmax(z)) along `axis`, with the maximum subtracted first so exp cannot overflow."""
    shifted = z - z.max(axis=axis, keepdims=True)
    return shifted - np.log(np.exp(shifted).sum(axis=axis, keepdims=True))


def _check(logits, target) -> tuple[np.ndarray, np.ndarray]:
    """Logits as a float array (N, C) and class indices as an int array (N,). Raises ValueError otherwise."""
    logits, target = np.asarray(logits, dtype=float), np.asarray(target)
    if logits.ndim != 2 or target.shape != (logits.shape[0],):
        raise ValueError(f"expected logits (N, C) and target (N,), got {logits.shape} and {target.shape}")
    return logits, target.astype(int)


class LabelSmoothingCrossEntropy:
    """Softmax cross-entropy against targets softened by the smoothing share."""

    def __init__(self, config: LabelSmoothingCrossEntropyConfig | None = None) -> None:
        self.config = config or LabelSmoothingCrossEntropyConfig()

    def smoothed_targets(self, target: np.ndarray, num_classes: int) -> np.ndarray:
        """Target distribution q. target: (N,) class indices. Returns (N, num_classes), rows summing to 1."""
        target = np.asarray(target).astype(int)
        if target.size and (target.min() < 0 or target.max() >= num_classes):
            raise ValueError(f"target classes must lie in [0, {num_classes})")
        s = self.config.smoothing
        q = np.full((len(target), num_classes), s / num_classes)
        q[np.arange(len(target)), target] += 1.0 - s
        return q

    def forward(self, logits: np.ndarray, target: np.ndarray):
        """logits: (N, C) raw scores. target: (N,) class indices. Returns a float, or (N,) for "none"."""
        logits, target = _check(logits, target)
        q = self.smoothed_targets(target, logits.shape[1])
        per_row = -(q * _log_softmax(logits)).sum(axis=1)
        if self.config.reduction == "none":
            return per_row
        return float(per_row.mean()) if self.config.reduction == "mean" else float(per_row.sum())

    def backward(self, logits: np.ndarray, target: np.ndarray) -> np.ndarray:
        """Gradient of the reduced loss with respect to the logits, shape (N, C).

        Per row it is softmax(logits) - q, divided by N for "mean". For "none" the per-row gradient is
        returned unscaled.
        """
        logits, target = _check(logits, target)
        grad = np.exp(_log_softmax(logits)) - self.smoothed_targets(target, logits.shape[1])
        return grad / len(target) if self.config.reduction == "mean" else grad

    __call__ = forward
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
7, run with python3 -m unittest -v

Practice

Build LabelSmoothingCrossEntropy(LabelSmoothingCrossEntropyConfig(smoothing=0.1)) and print smoothed_targets for target 0 with 4 classes. Then evaluate forward on logits (k,0,0,0)(k, 0, 0, 0) for kk from 0 to 12, find the kk with the lowest loss, and compare it with the formula for the optimal gap.

Check on learning

  1. With hard targets the loss keeps falling as the true logit grows. With smoothed targets it eventually rises again. Why?
    A way to think about it

    Use the two-part form. As the model grows more confident, the probabilities of the other classes shrink, and the uniform term charges for their logs.

  2. For 1000 classes and a smoothing of 0.1, what logit gap does the optimum ask for, and what probability does the true class then receive?
    A way to think about it

    Plug into the gap formula, then note that at the optimum p=qp = q, so the true-class probability is simply qyq_y.

  3. About 5 percent of your training labels are wrong. Why might smoothing help more than it would on clean data?
    A way to think about it

    A mislabelled example with a hard target produces a strong, persistent push in the wrong direction. Compare the size of the gradient once the target admits some doubt.

  4. A teacher trained with smoothing gives worse distillation results than one trained without. What information did smoothing remove?
    A way to think about it

    Distillation relies on the relative sizes of the wrong-class probabilities, which encode which classes resemble each other. Smoothing pulls those toward one common value.