Label smoothing: soften the target, inspect the gradient
标签平滑
Derive the smoothed cross-entropy gradient, compare target conventions, and fit finite logits without claiming better calibration.
label-smoothingStart with the problem
A one-hot target assigns probability 1 to the labeled class and 0 to every other class. For a single unconstrained example, softmax cross-entropy keeps rewarding a larger gap between the correct logit and the others. Label smoothing changes the target distribution: reserve most probability for the label and distribute a small amount across classes.
Szegedy and colleagues, Section 7, describe this regularization in the Inception study. The change is made during training. It is not the same operation as dividing logits by a temperature after training, and it does not certify that a model’s reported probabilities match real-world frequencies.
Definitions and derivation
Let K be the number of mutually exclusive classes, y the class index and ε the smoothing strength. We use the uniform-including-the-correct-class convention:
For K=3, y=1 and ε=0.2, the target is (1/15,13/15,1/15). The labeled class receives both its retained one-hot mass and its share of uniform mass. A different convention distributes ε only among incorrect classes, giving (0.1,0.8,0.1) here. Equal numeric ε therefore does not imply equal targets across these conventions.
Since log pₖ=zₖ−log Σ exp zⱼ and the target masses sum to one, differentiation gives:
The derivative of the log-normalizer contributes pₖ; the target term contributes −qₖ. The gradients sum to zero, reflecting invariance to adding one constant to all logits. At zero logits, this example’s gradient is (4/15,−8/15,4/15). A rate-0.5 update gives (−2/15,4/15,−2/15).
The loss can also be decomposed using the uniform distribution u:
The KL direction is u to p, not p to u. Reversing it produces another regularizer. For positive ε and freely adjustable logits, p=q is optimal: cross-entropy equals the entropy of q plus KL(q∥p), which is minimized at zero. For our three-class target the optimal correct/incorrect logit gap is log 13. This is finite, unlike the limiting one-hot optimum. It does not say a shared-parameter classifier can fit every training target simultaneously.
Run the calculation
The complete Python 3.12 / NumPy 1.26.4 program fits three free logits for one fixed target. It subtracts the largest logit before log-sum-exp to avoid unnecessary exponential overflow. It runs 120 gradient steps, not a classifier benchmark.
import numpy as np
def target_distribution(classes, label, epsilon):
if type(classes) is not int or not 2 <= classes <= 8 or type(label) is not int or not 0 <= label < classes:
raise ValueError('Use 2 to 8 classes and an integer class index.')
if not np.isfinite(epsilon) or not 0 <= epsilon <= 1:
raise ValueError('Smoothing must be in [0, 1].')
q = np.full(classes, epsilon / classes)
q[label] += 1 - epsilon
return q
def loss_grad(logits, label, epsilon):
z = np.asarray(logits, dtype=float)
if z.ndim != 1 or not np.isfinite(z).all():
raise ValueError('Use a finite logit vector.')
q = target_distribution(len(z), label, epsilon)
shifted = z - z.max()
logp = shifted - np.log(np.exp(shifted).sum())
return float(-q @ logp), np.exp(logp) - q, np.exp(logp)
def train(steps=120):
if type(steps) is not int or not 0 <= steps <= 256:
raise ValueError('Use 0 to 256 integer steps.')
z, losses = np.zeros(3), []
for _ in range(steps):
value, grad, _ = loss_grad(z, 1, 0.2)
losses.append(value)
z -= 0.5 * grad
return z, loss_grad(z, 1, 0.2), losses
if __name__ == '__main__':
z, (value, _, p), losses = train()
print('target', target_distribution(3, 1, 0.2).round(9).tolist())
print('first gradient', loss_grad(np.zeros(3), 1, 0.2)[1].round(9).tolist())
print('final probabilities', p.round(9).tolist())
print('initial loss', round(losses[0], 9), 'final loss', round(value, 9))
print('logit gap', round(z[1] - z[0], 9), 'optimal gap', round(float(np.log(13)), 9))
Actual output:
target [0.066666667, 0.866666667, 0.066666667]
first gradient [0.266666667, -0.533333333, 0.266666667]
final probabilities [0.066667999, 0.866664001, 0.066667999]
initial loss 1.098612289 final loss 0.485094091
logit gap 2.564926292 optimal gap 2.564949357
The predicted probabilities approach the smoothed target, and the final gap approaches log 13. The initial loss is log 3 because the initial prediction is uniform. The target distribution and objective stay fixed throughout training. Tests check finite differences, shift invariance, the first literal update and a stationary point constructed from log q.
For K classes, constructing the target and evaluating stable softmax, loss and gradient costs O(K) time and storage in this dense example. Implementations can exploit the algebraic loss decomposition to avoid building a separate dense target for every sample; the classifier’s logits still have to be handled.
When the method fails
Smoothing trades a sharper fit to observed labels for a different training objective. It is not automatically a statistically correct noise model. If true conditional probabilities are not the smoothed targets, fitting those targets exactly does not imply perfect calibration. At ε=1 the label is discarded and every target is uniform; at ε=0 ordinary one-hot cross-entropy is recovered.
Müller, Kornblith and Hinton report improved calibration in their experiments, but also degraded distillation from smoothed teachers. Their representation analysis offers an explanation for those observations. Treat these as experimentally scoped findings, not universal outcomes. Check held-out accuracy, likelihood, calibration and the downstream use of logits separately. Smoothing does not repair mislabeled data automatically, and a smaller training loss across different ε values is not a fair comparison of unchanged objectives.
Exercises with answers
- With K=3 and ε=0.2, how much mass does the labeled class receive?
Answer 1: 1−0.2+0.2/3=13/15. Uniform mass includes the labeled class.
- What is the gradient at p=q?
Answer 2: The zero vector. For positive target masses, logits log q plus any common constant realize this stationary prediction.
- Why is KL(p∥u) not interchangeable with KL(u∥p)?
Answer 3: KL is asymmetric. The decomposition of cross-entropy with uniform targets gives KL(u∥p), while the reverse direction penalizes a different quantity.
- Does reaching the printed target prove improved test accuracy or calibration?
Answer 4: No. This program fits one free probability vector and uses no held-out observations or shared classifier.
Sources and next steps
The Inception paper’s Section 7 defines the target mixture and cross-entropy decomposition. The 2019 paper’s introduction and preliminaries distinguish empirical generalization, calibration and distillation effects. The three-class fit and derivative tests here are original. Revisit cross-entropy for the objective and softmax for the logit map before transferring the method into a larger classifier.
Make a prediction, then check
In this convention, does the labeled class receive uniform smoothing mass?
Learning objectives
- Derive the smoothed target, logit gradient and KL direction.
- Distinguish a finite-logit optimum from an empirical calibration claim.
Prerequisites & connections
Explore related knowledge →References
- Rethinking the Inception Architecture for Computer Vision
Christian Szegedy et al. · 2016 - When Does Label Smoothing Help?
Rafael Müller; Simon Kornblith; Geoffrey Hinton · 2019
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-06 · Codex single-AI-author technical check: primary-source scope, explicit assumptions, original calculations, independent mathematical references and bilingual tests; not independent human or second-agent review.
- Single-AI-author technical check: bounded primary-source reading, explicit assumptions, original calculations, runnable examples and matching bilingual equations, code and exercises. Not an independent human or second-agent review.
- Four focused CPython 3.12.4 tests passed per chapter, including independent derivatives, integrals, normal equations or exact/literal trajectory references as appropriate. NumPy 1.26.4 is used in six programs; PBT and curriculum use standard-library exact fractions. CPU teaching calculations, not framework or GPU benchmarks.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
- Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
Source locations checked:
- Rethinking the Inception Architecture for Computer Vision · Physical pages 6–7, Section 7: uniform label mixture, gradient p−q, cross-entropy and KL(u∥p) decomposition.
- When Does Label Smoothing Help? · Physical pages 1–2, abstract/introduction and Section 1.1; experimentally scoped calibration/distillation claims and label-mixture convention.
Related topics