AI Logic

Loss Functions

Lovász-Softmax

Updated:

Computation of Lovász-Softmax. The left side is a bottom-to-top flow: network output, softmax, pixel errors, sorting by decreasing error, the Lovász extension (a sum weighted by the increments of the Jaccard loss), and averaging over classes present in the ground truth. The right side is a table for a 6-pixel, 1-class example: the errors sorted in decreasing order, the intersection and union when the top i are wrong, the Jaccard loss, the increment g_i, and the product of error and weight, totaling 0.453

Background and Overview

Lovász-Softmax is a loss function that makes it possible to directly minimize IoU (the Jaccard index), the metric used to evaluate segmentation, as a training loss. Berman et al. proposed it in 2018. IoU is "overlap ÷ combined area" of the predicted and ground-truth regions, and it is not differentiable as is. Lovász-Softmax uses the "Lovász extension," which extends the IoU loss to continuous values, and computes it in a differentiable form from softmax probabilities.

The Jaccard index of class cc and its loss are as follows (Eqs. (3)(4) of the paper).

Jc(y∗,y~)=∣{y∗=c}∩{y~=c}∣∣{y∗=c}∪{y~=c}∣,ΔJc=1−JcJ_c(y^*, \tilde{y}) = \frac{|\{y^* = c\} \cap \{\tilde{y} = c\}|}{|\{y^* = c\} \cup \{\tilde{y} = c\}|}, \qquad \Delta_{J_c} = 1 - J_c

y∗y^* is the ground-truth class of each pixel and y~\tilde{y} is the predicted class. The average of JcJ_c over classes is mIoU, the standard evaluation metric for segmentation.

The motivation is the mismatch between the training loss and the evaluation metric.

  • Training uses cross-entropy, evaluation uses IoU: Per-pixel cross-entropy is pulled toward large objects and background, which contain many pixels. IoU, by contrast, measures the overlap ratio per class, so small objects are weighted the same as large ones. The paper points out that the cross-entropy value on validation data is not a very reliable indicator of segmentation quality.
  • IoU cannot be used for training as is: IoU is determined by a set, namely "which pixels were wrong," so small changes to the prediction change its value only in discrete jumps, and no gradient is available.

The left side of the figure at the top shows the computation flow, and the right side computes the Lovász extension for a 6-pixel example. The pixel errors are sorted in decreasing order, and the weighted sum of the errors is taken, where each weight is how much the Jaccard loss increases (the increment gig_i) when the pixels are counted as "wrong" one at a time from the top.

As an analogy, it is like re-grading a test not by "the total number of correct answers" but by weighting each question according to "how much it lowers the final grade (IoU)."

Theory (Computing the Loss)

Lovász-Softmax is computed over the pixels of an image (or a mini-batch) in the following steps.

  1. Convert to probabilities with a softmax: From the score Fi(c)F_i(c) of pixel ii for class cc, compute the probability fi(c)f_i(c) (Eq. (2)).
  2. Form the pixel errors: For each class cc, the error is "the amount by which cc was not predicted" for pixels whose ground truth is cc, and "the amount by which cc was wrongly predicted" for all other pixels (Eq. (11)). mi(c)={1−fi(c)(c=yi∗)fi(c)(otherwise)m_i(c) = \begin{cases} 1 - f_i(c) & (c = y_i^*) \\ f_i(c) & (\text{otherwise}) \end{cases}
  3. Sort the errors in decreasing order: Denote the sorted order by π1,π2,…,πp\pi_1, \pi_2, \dots, \pi_p (pp is the number of pixels).
  4. Use the increments of the Jaccard loss as weights: Compute in turn the Jaccard loss ΔJc({π1,…,πi})\Delta_{J_c}(\{\pi_1, \dots, \pi_i\}) when the top ii pixels are all wrong, and take the difference from the previous one as the weight gig_i (Eq. (9)). All gig_i can be computed together just by counting cumulative pixels (Algorithm 1 of the paper). gi=ΔJc({π1,…,πi})−ΔJc({π1,…,πi−1})g_i = \Delta_{J_c}(\{\pi_1, \dots, \pi_i\}) - \Delta_{J_c}(\{\pi_1, \dots, \pi_{i-1}\})
  5. Take the weighted sum (the Lovász extension): Multiply the sorted errors by the weights and add them up (Eq. (8)). ΔJc‾(m(c))=∑i=1pmπi(c) gi\overline{\Delta_{J_c}}(m(c)) = \sum_{i=1}^{p} m_{\pi_i}(c)\, g_i
  6. Average over classes: The average of the per-class values is the Lovász-Softmax loss (Eq. (13)). In the paper's experiments, the average is taken only over classes present in the mini-batch's ground truth. loss(f)=1∣C∣∑c∈CΔJc‾(m(c))\mathrm{loss}(f) = \frac{1}{|C|} \sum_{c \in C} \overline{\Delta_{J_c}}(m(c))

Only the sort takes O(plog⁡p)O(p \log p) time; the rest is cumulative sums and inner products. Everything can be computed on a GPU and differentiated directly in deep learning frameworks.

For two classes (foreground and background), the paper also presents the Lovász hinge, which uses the hinge loss of the scores, mi=max⁡(1−Fi(x) yi∗,0)m_i = \max(1 - F_i(x)\, y_i^*, 0) (yi∗∈{−1,1}y_i^* \in \{-1, 1\}), as the error instead of a softmax (Eq. (10)). When the prediction consists of a single pixel, it reduces to the ordinary hinge loss.

Why It Can Stand In for IoU

Lovász-Softmax is a good stand-in for IoU because the Jaccard loss has a property called "submodularity."

  • Submodular set functions have a tight convex extension: Viewed as a function whose input is the set of misclassified pixels (a set function), the Jaccard loss is submodular (the larger the set of wrong pixels, the smaller the increase in loss when one more mistake is added; the same meaning as Definition 1 in the paper). For submodular functions, the tightest way to extend values defined only on "0 or 1" inputs convexly to continuous inputs (the convex closure) can be computed in polynomial time as the Lovász extension. For general set functions, this computation is NP-hard.
  • At 0/1 points, it matches the original Jaccard loss: If all errors are 0 or 1, the value of the Lovász extension equals the actual Jaccard loss. In between, it is piecewise linear, so it can be minimized by gradient descent.
  • The weights express the effect on IoU: The weight gig_i is how much a mistake on that pixel increases the Jaccard loss. In the example in the figure at the top, missing one of the 3 pixels whose ground truth is class cc lowers IoU by 1/3, so it receives a large weight. The smaller a class's region, the larger the weight of a single pixel, so training is driven by overlap ratios rather than pixel counts.

In the paper's two-class experiments, training with the Lovász hinge filled in missing parts of the segmentation and also picked up small objects.

The more confident the network's outputs become (probabilities close to 0 or 1), the closer the value of Lovász-Softmax gets to the actual Jaccard loss (from the description of Figure 2 in the paper).

Experimental Results

The paper compares losses using DeepLab-v2 (a segmentation network built on ResNet-101) and ENet. For the IoU and mIoU metrics, higher is better.

PASCAL VOC multiclass segmentation (DeepLab-v2, dataset-wide mIoU)

Training lossVal: single-scaleVal: multi-scale + CRFTest: multi-scale + CRF
Cross-entropy74.6476.5376.44
Cross-entropy + equibatch75.5377.3178.05
Lovász-Softmax76.5677.99-
Lovász-Softmax + equibatch (30K iterations)77.4179.1279.00

Equibatch is a technique that selects training images so as to cycle through all classes in turn, and CRF is the post-processing used by DeepLab-v2.

  • Just changing the loss raised mIoU by about 2 points: In single-scale validation, it went from 74.64 to 76.56.
  • The gap widened with longer training: The improvement appeared late in training, and increasing the iterations from 20K to 30K raised Lovász-Softmax further. For cross-entropy + equibatch, increasing to 30K lowered single-scale mIoU from 75.53 to 74.97.
  • IoU also improved for two classes: In two-class segmentation with each of the 20 PASCAL VOC classes taken as the foreground in turn, the mean per-image IoU was 77.14 with cross-entropy, 75.8 with the hinge loss, and 80.5 with the Lovász hinge.

Cityscapes (ENet, test)

MetricENet trained with weighted cross-entropyFine-tuned with Lovász-Softmax
Class IoU58.2963.06
Class iIoU34.3634.06
Category IoU80.4083.58
Category iIoU63.9961.05

The optimized IoU (Class IoU) rose by 4.77 points. On the other hand, iIoU, which weights by object size, dropped slightly. The paper suggests that changing the weights in the loss average could also target differently weighted metrics such as iIoU.

Practical Considerations

Because it is computed on mini-batches, it does not directly optimize the dataset-wide mIoU. The evaluation mIoU is computed over all pixels of the test data together, whereas Lovász-Softmax is computed over the pixels of a single image or a mini-batch. The paper reports that optimizing per-image mIoU often lowers the dataset-wide mIoU below that of cross-entropy. This is because predicting even one pixel of a class that does not appear in the image makes that class's per-image loss jump from 0 to 1. As a countermeasure, the paper recommends averaging only over classes present in the mini-batch's ground truth.

Keep the following points in mind as well.

  • Larger mini-batches help: In the paper's ENet experiments, the larger the batch size, the better the approximation of the dataset-wide IoU and the larger the improvement.
  • Start from weights trained with cross-entropy: The paper's experiments start from weights pretrained or trained with cross-entropy (or weighted cross-entropy). Results of training with this loss alone from the start are not reported.
  • PyTorch has no built-in version: Use the authors' implementation (published on GitHub) or write it yourself following Algorithm 1. No gradient flows through the sort order itself; the gradient flows through the sorted errors mm.
  • It helps late in training: The improvement appeared in the second half of training, after the learning rate had become small. Increasing the number of iterations can raise it further.

Comparison with Other Loss Functions

The table below compares losses used for segmentation from the same viewpoints.

Loss functionWhat it minimizesClasses with small regionsRelation to evaluation IoU
Per-pixel cross-entropyAverage per-pixel probability errorLittle influence because they have few pixels (weights need tuning)Indirect
Focal LossCross-entropy with easy pixels down-weightedThe loss of easy background becomes smallIndirect
Dice loss1 − Dice coefficient (computed on probabilities)Measured as a ratio, so less affectedDirectly targets the Dice coefficient (F1)
Tversky lossA generalization of the Dice coefficient with different weights for misses and false detectionsMeasured as a ratio; misses can be weighted moreCan tune the balance between recall and precision
Lovász-SoftmaxLovász extension of the Jaccard loss (convex, matching at 0/1 points)A single pixel gets a larger weightDirectly targets IoU

Rough guidelines for choosing among them:

  • If evaluation uses mIoU, finish a model trained with cross-entropy using Lovász-Softmax: This is close to how the paper uses it, and just changing the loss raises IoU.
  • For two-class problems with a small foreground evaluated by the Dice coefficient, use the Dice loss: The evaluation metric and the training objective line up.
  • If you especially want to reduce misses, use the Tversky loss: It can count misses (false negatives) more heavily.

PyTorch example

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


def lovasz_grad(fg_sorted):
    """Algorithm 1 of the paper: compute the Jaccard-loss increments g from the ground truth (1 = class c) sorted by decreasing error"""
    gts = fg_sorted.sum()
    intersection = gts - fg_sorted.cumsum(0)          # intersection when the top i are wrong
    union = gts + (1 - fg_sorted).cumsum(0)           # union when the top i are wrong
    jaccard = 1.0 - intersection / union              # Jaccard loss when the top i are wrong
    if fg_sorted.numel() > 1:
        jaccard[1:] = jaccard[1:] - jaccard[:-1]      # difference from the previous one = g_i (Eq. (9))
    return jaccard


def lovasz_softmax(logits, labels, ignore_index=255):
    """logits: (N, C, H, W), labels: (N, H, W). Computed over the whole mini-batch and averaged only over classes present in the ground truth"""
    probas = F.softmax(logits, dim=1)
    C = probas.size(1)
    probas = probas.permute(0, 2, 3, 1).reshape(-1, C)   # (num pixels, C)
    labels = labels.reshape(-1)
    valid = labels != ignore_index
    probas, labels = probas[valid], labels[valid]
    losses = []
    for c in range(C):
        fg = (labels == c).float()
        if fg.sum() == 0:                                # classes absent from the ground truth are not averaged
            continue
        errors = (fg - probas[:, c]).abs()               # Eq. (11): 1 − f (ground truth is c), f (otherwise)
        errors_sorted, perm = torch.sort(errors, descending=True)
        g = lovasz_grad(fg[perm])                        # no gradient flows through the sort order
        losses.append(torch.dot(errors_sorted, g))       # Eq. (8): Σ m_i g_i
    return torch.stack(losses).mean()                    # Eq. (13)


# Example from the top figure: 6 pixels, 3 of which have ground-truth class c
fg = torch.tensor([1.0, 1.0, 1.0, 0.0, 0.0, 0.0])
f_c = torch.tensor([0.9, 0.6, 0.2, 0.3, 0.15, 0.05])     # probability of class c
errors = (fg - f_c).abs()
errors_sorted, perm = torch.sort(errors, descending=True)
print(torch.dot(errors_sorted, lovasz_grad(fg[perm])).item())  # about 0.453

# Usage in training (e.g., 21-class segmentation)
logits = torch.randn(2, 21, 64, 64, requires_grad=True)
labels = torch.randint(0, 21, (2, 64, 64))
loss = lovasz_softmax(logits, labels)
loss.backward()

FAQ

Q. How does it differ from the Dice loss?
A.

The Dice loss makes the Dice coefficient differentiable by replacing the 0/1 predictions in its formula with probabilities. Lovász-Softmax extends the IoU (Jaccard index) loss continuously with the Lovász extension; it is guaranteed to match the actual Jaccard loss when all errors are 0 or 1 and to be convex in between. If evaluation uses IoU, Lovász-Softmax aligns the training objective with the evaluation metric; if it uses the Dice coefficient, the Dice loss does.

Q. Can I train with this loss alone from the start, instead of cross-entropy?
A.

All of the paper's experiments start from weights trained with cross-entropy (or weighted cross-entropy) and then continue training with the loss switched to Lovász-Softmax. The paper has no results for training with this loss alone from the start. Using it first to finish a model trained with cross-entropy follows the paper.

Q. Is it better to compute it per image or over the whole mini-batch?
A.

If evaluation uses dataset-wide mIoU, the paper recommends computing over the whole mini-batch and averaging only over classes present in the ground truth. Computing per image makes the loss jump sharply when a class absent from the image is predicted even slightly, which can actually lower the dataset-wide mIoU. If evaluation uses per-image mIoU, per-image computation is the right fit.

References

  1. M. Berman, A. Rannen Triki, and M. B. Blaschko, "The Lovász-Softmax loss: A tractable surrogate for the optimization of the intersection-over-union measure in neural networks," CVPR, 2018.
  2. M. Berman, "LovaszSoftmax" (implementation by the paper's author), GitHub.