AI Logic

Loss Functions

PolyLoss

Updated:

Graphs of PolyLoss. On the left, the horizontal axis is the probability p_t of the correct class and the vertical axis is the loss, overlaying cross-entropy, Poly-1 (ε1 = 1 and −1), and Focal Loss (γ = 1 and 2). ε1 = 1 is steeper than cross-entropy and ε1 = −1 is flatter. On the right, the coefficients α_j of (1 − p_t)^j are plotted for each degree j: cross-entropy is 1/j, Focal Loss shifts the coefficients to the right, and PolyLoss moves only α_1 up or down. The legend is at the bottom

Background and Overview

PolyLoss is a loss-function framework that rewrites cross-entropy and Focal Loss as sums of polynomials in (1−pt)j(1 - p_t)^j so that their coefficients can be tuned to the task. It was proposed by Leng et al. in 2022. The form used in practice is Poly-1, which adds just one term to cross-entropy.

LPoly-1=−log⁡pt+ε1(1−pt)L_{\mathrm{Poly\text{-}1}} = -\log p_t + \varepsilon_1 (1 - p_t)

ptp_t is the probability the model assigns to the correct class. ε1\varepsilon_1 is the one new value (a hyperparameter); with ε1=0\varepsilon_1 = 0, the loss is identical to cross-entropy.

The motivation was that the choice of classification loss had become almost binary.

  • The loss is almost always cross-entropy or Focal Loss: Cross-entropy is standard for image classification, and Focal Loss is standard for object detection with heavy class imbalance. But nothing guarantees that the best loss for every task and dataset is one of these two.
  • Designing a loss freely leaves too many options: Any differentiable function can serve as a loss, so searching without guidance is hard.

PolyLoss uses the idea of the Taylor expansion, which approximates a function by a sum of polynomials, to put these two losses in the same form. The left side of the figure at the top shows the relationship between ptp_t and the loss, and the right side shows the coefficients αj\alpha_j when each loss is written as polynomials. The coefficients of cross-entropy are 1/j1/j, and Focal Loss shifts this sequence of coefficients to the right (toward higher degrees). Poly-1 of PolyLoss moves only the first coefficient α1\alpha_1 up or down. With ε1>0\varepsilon_1 > 0 the loss becomes steeper than cross-entropy, and with ε1<0\varepsilon_1 < 0 it becomes flatter.

As an analogy, the method treats cross-entropy and Focal Loss as two settings of an audio device with the same knobs (coefficients), and turns just one knob to tune the sound to the task.

Theory (Rewriting as Polynomials)

PolyLoss is built in the following steps.

  1. Expand cross-entropy into polynomials in (1−pt)(1 - p_t). Taylor-expanding −log⁡pt-\log p_t around pt=1p_t = 1 gives an infinite sum with coefficients 1/j1/j (Eq. (1) in the paper). LCE=−log⁡pt=∑j=1∞1j(1−pt)j=(1−pt)+12(1−pt)2+⋯L_{\mathrm{CE}} = -\log p_t = \sum_{j=1}^{\infty} \frac{1}{j} (1 - p_t)^j = (1 - p_t) + \frac{1}{2}(1 - p_t)^2 + \cdots
  2. Expand Focal Loss into the same form. Multiplying by the modulating factor (1−pt)γ(1 - p_t)^{\gamma} raises the degree of every term by γ\gamma (Eq. (2)). In terms of the coefficient sequence, it is the cross-entropy coefficients shifted sideways by γ\gamma. LFL=−(1−pt)γlog⁡pt=∑j=1∞1j(1−pt)j+γ=(1−pt)1+γ+12(1−pt)2+γ+⋯L_{\mathrm{FL}} = -(1 - p_t)^{\gamma} \log p_t = \sum_{j=1}^{\infty} \frac{1}{j} (1 - p_t)^{j + \gamma} = (1 - p_t)^{1 + \gamma} + \frac{1}{2}(1 - p_t)^{2 + \gamma} + \cdots
  3. Consider a general form with free coefficients. A loss whose coefficients αj\alpha_j are chosen per task is PolyLoss (Eq. (5)). The paper considers the case where all αj≥0\alpha_j \geq 0 and jj is a positive integer. LPoly=∑j=1∞αj(1−pt)jL_{\mathrm{Poly}} = \sum_{j=1}^{\infty} \alpha_j (1 - p_t)^j
  4. Adjust only the first NN coefficients (Poly-N). Tuning infinitely many coefficients is impossible, so εj\varepsilon_j is added only to the first NN of the cross-entropy coefficients 1/j1/j (Eq. (6), εj≥−1/j\varepsilon_j \geq -1/j). LPoly-N=−log⁡pt+∑j=1Nεj(1−pt)jL_{\mathrm{Poly\text{-}N}} = -\log p_t + \sum_{j=1}^{N} \varepsilon_j (1 - p_t)^j
  5. Adjust only the first coefficient (Poly-1). Setting N=1N = 1 gives the form the paper ultimately recommends (Eq. (7)). It takes a single line added to a cross-entropy implementation: ε1(1−pt)\varepsilon_1 (1 - p_t). LPoly-1=(1+ε1)(1−pt)+12(1−pt)2+⋯=−log⁡pt+ε1(1−pt)L_{\mathrm{Poly\text{-}1}} = (1 + \varepsilon_1)(1 - p_t) + \frac{1}{2}(1 - p_t)^2 + \cdots = -\log p_t + \varepsilon_1 (1 - p_t)

For tasks that use Focal Loss, the coefficient of the leading term (1−pt)γ+1(1 - p_t)^{\gamma + 1} of the Focal Loss expansion is adjusted instead.

LFL-Poly-1=−(1−pt)γlog⁡pt+ε1(1−pt)γ+1L_{\mathrm{FL\text{-}Poly\text{-}1}} = -(1 - p_t)^{\gamma} \log p_t + \varepsilon_1 (1 - p_t)^{\gamma + 1}

In the paper's Poly-N experiment (ResNet-50, ImageNet-1K), N=1N = 1 raised accuracy from 76.3% to 76.7%, and increasing to N=2N = 2 gave 76.8%. Since adding more coefficients brings little extra gain, Poly-1, with only one value to tune, was chosen.

Why It Works (Through the Gradient)

How PolyLoss works becomes clear from the gradient of the loss with respect to ptp_t.

  • The cross-entropy gradient has a constant term 1: When cross-entropy is differentiated, the coefficient 1/j1/j and the degree jj cancel, and the gradient becomes a simple sum of powers of (1−pt)(1 - p_t) (Eq. (3)). −dLCEdpt=∑j=1∞(1−pt)j−1=1+(1−pt)+(1−pt)2+⋯-\frac{dL_{\mathrm{CE}}}{dp_t} = \sum_{j=1}^{\infty} (1 - p_t)^{j-1} = 1 + (1 - p_t) + (1 - p_t)^2 + \cdots The leading 1 is a constant gradient that remains no matter how close ptp_t is to 1. This term comes from the first polynomial (1−pt)(1 - p_t). Conversely, the higher-degree terms shrink quickly as ptp_t approaches 1.
  • Focal Loss removes this constant term: For Focal Loss with γ>0\gamma > 0, the leading term of the gradient is (1+γ)(1−pt)γ(1 + \gamma)(1 - p_t)^{\gamma}, and the constant 1 disappears (Eq. (4)). As a result, the gradient of majority examples that are already predicted confidently becomes small.
  • Poly-1 changes the size of this constant term: The Poly-1 gradient is the cross-entropy gradient with its leading term changed from 11 to 1+ε11 + \varepsilon_1. With ε1>0\varepsilon_1 > 0, the push of the correct-class probability toward 1 becomes stronger and predictions become more confident. With ε1<0\varepsilon_1 < 0, the push that further raises already-confident predictions becomes weaker. At ε1=−1\varepsilon_1 = -1 the constant term vanishes, and the behavior becomes close to Focal Loss with γ=1\gamma = 1.

In the paper, when ResNet-50 was trained on ImageNet-1K, the first polynomial (1−pt)(1 - p_t) accounted for more than half of the cross-entropy gradient during the last 65% of training. This is why adjusting only the first coefficient has a large effect.

On the other hand, reducing the number of terms by dropping the higher-degree ones (truncation, proposed earlier) did not work well. Matching cross-entropy's accuracy on ImageNet-1K required more than 600 terms. Early in training, ptp_t is close to 0, so the gradients of the higher-degree terms are also large. For example, at pt≈0.001p_t \approx 0.001, the gradient coefficient of the 500th term is as large as 0.999499≈0.60.999^{499} \approx 0.6.

Experimental Results

The paper kept the training settings of each task's public implementation unchanged and replaced only the classification loss with Poly-1. The training settings had been tuned for the original loss (cross-entropy or Focal Loss), which puts Poly-1 at a disadvantage.

Task / modelOriginal lossε1\varepsilon_1MetricOriginal lossPoly-1
ImageNet-1K classification, ResNet-50Cross-entropyGrid searchAccuracy76.376.7
ImageNet-21K pretraining, EfficientNetV2-LCross-entropy2Accuracy45.846.4
ImageNet-1K fine-tuning, EfficientNetV2-LCross-entropy2Accuracy86.887.2
COCO object detection, Mask R-CNNCross-entropy−1Box AP / AR35.0 / 47.235.3 / 49.7
COCO instance segmentation, Mask R-CNNCross-entropy−1Mask AP / AR31.3 / 42.331.6 / 44.4
Waymo Open Dataset 3D detection (vehicle), PointPillarsFocal Loss (γ=2\gamma = 2)−13D AP (L1)63.363.7
Waymo Open Dataset 3D detection (pedestrian), PointPillarsFocal Loss (γ=2\gamma = 2)−13D AP (L1)68.969.6

AP is average precision and AR is average recall; higher is better for both.

  • Even for "imbalanced data," the best sign of ε1\varepsilon_1 was opposite: On ImageNet-21K (about 13 million images, 21,841 classes), ε1=2\varepsilon_1 = 2 worked well, while ε1=−1\varepsilon_1 = -1 lowered accuracy by 0.9 points. The paper explains that with so many classes the prediction confidence ptp_t stays low, so raising confidence helped. With Mask R-CNN on COCO, the opposite held: predictions were overconfident (ptp_t close to 1), and ε1=−1\varepsilon_1 = -1, which lowers confidence, helped.
  • Recall rose substantially: With Mask R-CNN, AP rose by 0.3 points, while AR rose by 2.5 points for boxes and 2.1 points for masks.
  • An effect close to scaling up the model: In ImageNet-21K pretraining, accuracy rose by about 1 point for every EfficientNetV2 size (S, M, L), nearly matching the gain from moving up one model size.
  • Gains even on a state-of-the-art 3D detector: For the two-stage RSN, starting from the "drop the leading term" form that was optimal for Poly-1, the coefficient of the next term (1−pt)4(1 - p_t)^4 was tuned, raising 3D AP (L1) from 78.4 to 78.9 for vehicles and from 79.4 to 80.2 for pedestrians.

Practical Considerations

The sign of ε1\varepsilon_1 flips depending on the task and data. The paper's best values were ε1=2\varepsilon_1 = 2 for ImageNet-21K classification and ε1=−1\varepsilon_1 = -1 for Mask R-CNN on COCO and PointPillars on Waymo. Do not hard-code it; grid-search a range that includes both positive and negative values. As a rule of thumb, look at the average correct-class probability ptp_t during training: try a positive ε1\varepsilon_1 if confidence is too low and a negative one if it is too high.

Keep the following points in mind as well.

  • Keep ε1≥−1\varepsilon_1 \geq -1: With ε1<−1\varepsilon_1 < -1, the leading coefficient 1+ε11 + \varepsilon_1 becomes negative, leaving the range the paper considers, where "all coefficients are 0 or greater." The paper's sample implementation also states epsilon >= -1.
  • PyTorch has no built-in version: Compute the cross-entropy value and ptp_t, and add ε1(1−pt)\varepsilon_1 (1 - p_t) yourself. Take ptp_t from the probabilities after softmax (sigmoid for Focal Loss), and compute cross-entropy directly from the logits for numerical stability.
  • When combining with Label Smoothing, compute 1−pt1 - p_t with the smoothed labels too: The paper's sample implementation uses the smoothed labels yy in the added term ∑cyc(1−pc)\sum_c y_c (1 - p_c).
  • Keep the other training settings from the original loss: The paper's results were obtained with the learning rate and other settings left as tuned for the original loss. The paper's appendix reports that tuning the other hyperparameters for Poly-1 improved accuracy further.

Comparison with Other Loss Functions

The classification losses are lined up from the PolyLoss viewpoint (the coefficients of (1−pt)j(1 - p_t)^j).

Loss functionHow the coefficients αj\alpha_j are setConstant term of the gradientValues to tuneSuited for
Cross-entropy1/j1/j1NoneStandard for classification
Focal Loss1/j1/j shifted right by γ\gammaNone (γ>0\gamma > 0)γ\gamma, α\alphaObject detection with an overwhelming number of easy background examples
Cross-entropy with higher degrees truncated1/j1/j for the first NN only, 0 for the rest1NNWhen robustness to label noise matters
Poly-1Only α1\alpha_1 is 1+ε11 + \varepsilon_1, the rest are 1/j1/j1+ε11 + \varepsilon_1ε1\varepsilon_1Any classification task using cross-entropy or Focal Loss

Guidelines for choosing:

  • If training with cross-entropy, try Poly-1: The implementation change is one line, and the only added value is ε1\varepsilon_1. The paper searched ε1\varepsilon_1 in the range 0–7 on ImageNet-21K and −1 to 1 on COCO.
  • If training with Focal Loss, try the Focal Loss version of Poly-1: The added term is (1−pt)γ+1(1 - p_t)^{\gamma + 1}.
  • If predictions are overconfident, use ε1<0\varepsilon_1 < 0 or Label Smoothing: According to the paper, Poly-1 with −1<ε1<0-1 < \varepsilon_1 < 0 lowers the gradient of overconfident predictions, but unlike Label Smoothing it does not spread probability to the non-target classes (encouraging wrong predictions).

PyTorch example

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


def poly1_cross_entropy(logits, targets, epsilon=1.0, label_smoothing=0.0):
    """Eq. (7) of the paper: L = −log(p_t) + ε1 (1 − p_t). logits is (N, C), targets are class indices (N,)"""
    num_classes = logits.size(-1)
    one_hot = F.one_hot(targets, num_classes).to(logits.dtype)
    # With Label Smoothing, compute 1 − p_t with the smoothed labels too (as in the paper's sample implementation)
    labels = one_hot * (1 - label_smoothing) + label_smoothing / num_classes
    probs = F.softmax(logits, dim=-1)
    one_minus_pt = (labels * (1 - probs)).sum(dim=-1)
    ce = F.cross_entropy(logits, targets, reduction="none", label_smoothing=label_smoothing)
    return ce + epsilon * one_minus_pt                  # Per-example loss (epsilon >= -1)


def poly1_focal_loss(logits, targets, epsilon=1.0, gamma=2.0, alpha=0.25):
    """Focal Loss version: FL + ε1 (1 − p_t)^(γ+1). Sigmoid per class, targets are 0 or 1"""
    p = torch.sigmoid(logits)
    pt = targets * p + (1 - targets) * (1 - p)
    ce = F.binary_cross_entropy_with_logits(logits, targets, reduction="none")  # −log(p_t)
    weight = targets * alpha + (1 - targets) * (1 - alpha)
    fl = weight * (1 - pt) ** gamma * ce
    return fl + epsilon * (1 - pt) ** (gamma + 1) * weight


# Example: an input that gives the correct class probability 0.9
logits = torch.log(torch.tensor([[0.9, 0.05, 0.05]]))
targets = torch.tensor([0])
print(F.cross_entropy(logits, targets).item())                   # about 0.105
print(poly1_cross_entropy(logits, targets, epsilon=1.0).item())  # about 0.205 (+ 1 × 0.1)
print(poly1_cross_entropy(logits, targets, epsilon=-1.0).item()) # about 0.005 (− 1 × 0.1)

# Use in training: take the mean, then backward
model_logits = torch.randn(8, 10, requires_grad=True)
labels = torch.randint(0, 10, (8,))
loss = poly1_cross_entropy(model_logits, labels, epsilon=2.0).mean()
loss.backward()

FAQ

Q. How should ε1 be chosen?
A.

The paper grid-searches a small set of candidates per task. ε1=2\varepsilon_1 = 2 was best for ImageNet-21K classification and ε1=−1\varepsilon_1 = -1 for COCO object detection (Mask R-CNN), with even the sign reversed. As a rule of thumb, try a positive value if the average correct-class probability ptp_t during training is low (underconfident) and a negative one if it is close to 1 (overconfident). Search within ε1≥−1\varepsilon_1 \geq -1.

Q. How does it differ from Focal Loss?
A.

Both can be seen as changing the polynomial coefficients of cross-entropy. Focal Loss shifts all coefficients to higher degrees by γ\gamma and removes the constant term of the gradient. Poly-1 moves only the first coefficient up or down, changing the size of the constant term to 1+ε11 + \varepsilon_1. Focal Loss with γ>0\gamma > 0 can only lower the gradient of confident predictions, whereas Poly-1 can also raise it.

Q. Can it be used together with Label Smoothing?
A.

Yes. The paper's sample implementation computes both the cross-entropy and 1−pt1 - p_t with the smoothed labels. Note that Poly-1 with −1<ε1<0-1 < \varepsilon_1 < 0 resembles Label Smoothing in curbing overconfidence, but it does not spread probability to the non-target classes.

References

  1. Z. Leng, M. Tan, C. Liu, E. D. Cubuk, X. Shi, S. Cheng, and D. Anguelov, "PolyLoss: A Polynomial Expansion Perspective of Classification Loss Functions," ICLR, 2022.