Skip to content

← Loss Functions step 5 of 8

Easy Research

Label Smoothing

Implement label_smoothing: convert class IDs into probability distributions by mixing each one-hot target with the uniform distribution over all classes. This gives some target probability to other classes instead of assigning the entire mass to one class. The function returns targets, not predictions or loss.

Contract

  • labels: shape (B,), integer-valued class IDs delivered as a floating-point tensor. Each ID is in [0, K).
  • n_classes: a positive integer K.
  • epsilon: a finite smoothing coefficient in [0, 1].

Return shape (B, K), preserving the floating-point dtype and device of labels. Leave labels unchanged. B may be zero; then return an empty (0, K) tensor.

For each row, put epsilon/K in every column, then add 1-epsilon at its true class ID. Equivalently:

true-class probability = 1 - epsilon + epsilon/K
other-class probability = epsilon/K

The uniform part includes the true class. Do not distribute epsilon only among the K-1 incorrect classes. Every row sums to one, apart from floating-point rounding. Repeated class IDs produce repeated rows.

For labels=[1,0], K=3 and epsilon=0.3, return:

[[0.1, 0.8, 0.1],
 [0.8, 0.1, 0.1]]

With epsilon=0, the result is one-hot. With epsilon=1, each row is uniform. With K=1, every nonempty row is [1] for any allowed epsilon. Build the target tensor directly; do not call a loss function.