AI Logic

Loss Functions

Tversky Loss

Updated:

Graph of Tversky loss. The horizontal axis is the predicted foreground size k (with the true foreground set to 1) and the vertical axis is the loss; to the left of k = 1, missed foreground (FN) increases, and to the right, excess foreground (FP) increases. Curves for α = β = 0.5 (same as Dice loss, dotted), α = 0.3, β = 0.7 (solid), and α = 0.1, β = 0.9 (dashed) are overlaid: the larger β is, the higher the loss on the left and the lower the loss on the right. On the right are the legend and the loss values at k = 0.5 and 1.5

Background and Overview

Tversky loss is a loss function built from the Tversky index, which measures the overlap between the predicted region and the true region, allowing separate weights for excess foreground (FP) and missed foreground (FN). It generalizes the Dice loss and was proposed by Salehi et al. in 2017 for segmenting multiple sclerosis lesions in 3D MRI images.

With GG the set of true foreground pixels and PP the set of predicted foreground pixels, the Tversky index is as follows.

S(P,G; α,β)=∣P∩G∣∣P∩G∣+α ∣P∖G∣+β ∣G∖P∣S(P, G;\ \alpha, \beta) = \frac{|P \cap G|}{|P \cap G| + \alpha\, |P \setminus G| + \beta\, |G \setminus P|}
  • ∣P∩G∣|P \cap G| (TP): the number of pixels correctly predicted as foreground
  • ∣P∖G∣|P \setminus G| (FP): the number of background pixels predicted as foreground, weighted by α\alpha
  • ∣G∖P∣|G \setminus P| (FN): the number of foreground pixels missed, weighted by β\beta

With α=β=0.5\alpha = \beta = 0.5, it equals the Dice coefficient and counts FP and FN with the same weight.

The motivation lies in two problems common in medical image segmentation.

  • Extremely little foreground: In lesion detection, it is not unusual for non-lesion pixels to outnumber lesion pixels by 500 times or more. Training on such imbalanced data pulls predictions toward the background.
  • Misses are worse: Training on imbalanced data tends to give predictions with high precision (the fraction of predicted foreground that is correct) but low recall (the fraction of true foreground that is found). In diagnostic support, missing a lesion (FN) is considered less acceptable than an extra detection (FP).

The Dice loss handles class imbalance without weight tuning, but it corresponds to the harmonic mean of precision and recall (the F1 score) and treats FP and FN equally. Tversky loss lets β\beta exceed α\alpha to penalize misses more strongly, making the balance between precision and recall adjustable.

The figure at the top shows the loss as the predicted foreground size kk varies, with the true foreground size set to 1. With β=0.7\beta = 0.7, compared with α=β=0.5\alpha = \beta = 0.5 (Dice loss), the loss for missed foreground (left side) becomes larger and the loss for excess foreground (right side) becomes smaller.

Theory (How the Loss Is Computed)

The paper computes the Tversky index from the network's output probabilities with the following equation.

T(α,β)=∑i=1Np0i g0i∑i=1Np0i g0i+α∑i=1Np0i g1i+β∑i=1Np1i g0iT(\alpha, \beta) = \frac{\sum_{i=1}^{N} p_{0i}\, g_{0i}}{\sum_{i=1}^{N} p_{0i}\, g_{0i} + \alpha \sum_{i=1}^{N} p_{0i}\, g_{1i} + \beta \sum_{i=1}^{N} p_{1i}\, g_{0i}}

The meaning of the symbols and the computation follow the steps below. As an example, take the same 10-pixel 1D image as in the Dice loss article, with ground truth g=(0,0,1,1,1,1,0,0,0,0)g = (0, 0, 1, 1, 1, 1, 0, 0, 0, 0) and predicted foreground probabilities p=(0,0.1,0.9,0.8,0.6,0.2,0.1,0,0,0)p = (0, 0.1, 0.9, 0.8, 0.6, 0.2, 0.1, 0, 0, 0).

  1. Turn the network output into probabilities with softmax: The paper's 3D U-Net outputs two channels, lesion and non-lesion tissue, and applies softmax per pixel (voxel). Let p0ip_{0i} be the probability that pixel ii is a lesion and p1i=1−p0ip_{1i} = 1 - p_{0i} the probability that it is not. The ground truth is g0i=1g_{0i} = 1, g1i=0g_{1i} = 0 for a lesion, and the reverse otherwise.
  2. Count TP, FP, and FN with probabilities: Instead of rounding to 0 or 1, count with sums of probabilities.
    • TP: ∑ip0i g0i\sum_i p_{0i}\, g_{0i} (in the example, 0.9+0.8+0.6+0.2=2.50.9 + 0.8 + 0.6 + 0.2 = 2.5)
    • FP: ∑ip0i g1i\sum_i p_{0i}\, g_{1i} (in the example, 0.1+0.1=0.20.1 + 0.1 = 0.2)
    • FN: ∑ip1i g0i\sum_i p_{1i}\, g_{0i} (in the example, 0.1+0.2+0.4+0.8=1.50.1 + 0.2 + 0.4 + 0.8 = 1.5)
  3. Compute the Tversky index: Plug TP, FP, and FN into the equation above. In the example, α=β=0.5\alpha = \beta = 0.5 gives T=2.52.5+0.1+0.75≈0.746T = \frac{2.5}{2.5 + 0.1 + 0.75} \approx 0.746, and α=0.3\alpha = 0.3, β=0.7\beta = 0.7 gives T=2.52.5+0.06+1.05≈0.693T = \frac{2.5}{2.5 + 0.06 + 1.05} \approx 0.693.
  4. Train on it as a loss: The paper trains to make TT larger. As a loss to minimize, L=1−TL = 1 - T is used. With α=0.3\alpha = 0.3, β=0.7\beta = 0.7 in the example, L≈0.307L \approx 0.307. For this prediction with many misses (FN = 1.5), increasing β\beta increases the loss.

This expression is differentiable with respect to the probabilities, and the paper also gives the gradients with respect to p0ip_{0i} and p1ip_{1i}. No per-class weights need to be tuned.

Particular choices of α\alpha and β\beta give well-known metrics (Section 2.2 of the paper). α=β=0.5\alpha = \beta = 0.5 is the Dice coefficient (F1 score), α=β=1\alpha = \beta = 1 is the Tanimoto coefficient (the same as IoU), and α+β=1\alpha + \beta = 1 gives the family of FβF_\beta scores. For example, the F2 score 5 TP5 TP+4 FN+FP\frac{5\,\mathrm{TP}}{5\,\mathrm{TP} + 4\,\mathrm{FN} + \mathrm{FP}}, used for evaluations that emphasize recall, equals the Tversky index with α=0.2\alpha = 0.2, β=0.8\beta = 0.8 after dividing the numerator and denominator by 55.

Tversky loss with α=β=0.5\alpha = \beta = 0.5 matches the Dice loss with a sum-of-probabilities denominator, 1−2∑pg∑p+∑g1 - \frac{2\sum p g}{\sum p + \sum g}, and differs in value from the Dice loss in the V-Net paper (whose denominator is a sum of squares, ∑p2+∑g2\sum p^2 + \sum g^2). In the example above, the Dice coefficient is 0.746 for the former and 0.852 for the latter.

Why Misses Decrease

Increasing β\beta reduces misses for three reasons.

  • The "price" of a miss goes up: The FN term in the denominator is weighted by β\beta, so increasing β\beta lowers the Tversky index more for the same number of misses. Conversely, the FP weight α\alpha becomes smaller, so extra foreground predictions barely increase the loss. In the figure at the top, at k=0.5k = 0.5 (missing half the foreground) the loss rises from 0.33 for the Dice loss to 0.41, and at k=1.5k = 1.5 (spilling over by half) it falls from 0.20 to 0.13.
  • Uncertain pixels tip toward foreground: To lower the loss, it pays to predict uncertain pixels as foreground. The predicted boundary expands outward from the foreground, making small lesions easier to catch.
  • Correct background is not counted, as in the Dice loss: The loss depends only on TP, FP, and FN; pixels correctly predicted as background (TN) do not enter the formula. Even with extremely little foreground, the loss is not diluted by correct background.

The paper hypothesizes that training with a larger β\beta on highly imbalanced data also improves generalization, and tests it experimentally.

As an analogy, the Dice loss is grading that "deducts equally for writing too much and for leaving things out," while Tversky loss (β>α\beta > \alpha) is grading that "deducts more for leaving things out." When omissions are costly, test takers also write down what they are unsure of, so omissions decrease at the cost of slightly more overwriting.

Experimental Results

The paper trained a 3D U-Net-style network with Tversky loss at various α\alpha, β\beta on the task of segmenting multiple sclerosis lesions from brain MRI of 15 subjects (three types: T1-weighted, T2-weighted, and FLAIR). With two-fold cross-validation, evaluation was done on the held-out images. Pixels with probability 0.5 or higher were labeled as lesion.

α\alpha, β\betaDice coefficientSensitivity (recall)SpecificityF2 scoreArea under the PR curve
α=0.5\alpha = 0.5, β=0.5\beta = 0.5 (Dice loss)53.4249.8599.9351.7752.57
α=0.4\alpha = 0.4, β=0.6\beta = 0.654.5755.8599.9155.4754.34
α=0.3\alpha = 0.3, β=0.7\beta = 0.756.4256.8599.9357.3256.04
α=0.2\alpha = 0.2, β=0.8\beta = 0.848.5761.0099.8954.5353.31
α=0.1\alpha = 0.1, β=0.9\beta = 0.946.4265.5799.8756.1151.65

(All values in %. Bold marks the best value in each column.)

  • The larger β\beta, the fewer misses: Sensitivity rose from 49.85% at β=0.5\beta = 0.5 to 65.57% at β=0.9\beta = 0.9. In exchange, specificity dropped slightly.
  • Overall metrics were best at β=0.7\beta = 0.7: On the Dice coefficient, F2 score, and area under the PR curve alike, α=0.3\alpha = 0.3, β=0.7\beta = 0.7 scored highest, surpassing the Dice loss (β=0.5\beta = 0.5).
  • Even with the Dice coefficient as the metric, it beat the Dice loss: The Dice coefficient itself was higher at β=0.7\beta = 0.7 (56.42) than when training with the Dice loss (53.42). The paper interprets this as improved generalization.

The paper also shows an example of a subject with very few lesions, where the network trained with the Dice loss failed to detect the lesions while β=0.7\beta = 0.7 detected them.

The experiment is a small-scale validation with images from 15 subjects; the paper itself frames it as a proof of concept and does not compare directly with other segmentation methods. It is safest to assume the optimal α\alpha, β\beta depend on the data and evaluation metric.

Practical Considerations

Making β\beta too large increases excess foreground and lowers overall performance. In the paper, raising β\beta to 0.8 and 0.9 kept increasing sensitivity, while the Dice coefficient fell to 48.57% and 46.42%. Choose β\beta according to "how much you want to reduce misses," watching the target metric, such as the Dice coefficient or F2 score, on validation data.

Keep the following points in mind as well.

  • Keep the sum of α\alpha and β\beta fixed: All experiments in the paper use pairs with α+β=1\alpha + \beta = 1. Changing the sum changes the scale of the loss itself, so when comparing, keep the sum fixed and change only the ratio.
  • The value is undefined for images with no foreground: If both the ground truth and prediction are entirely background, the numerator and denominator are both 0. Implementations add a small value ε\varepsilon to the numerator and denominator to avoid division by zero.
  • Compute on probabilities: Count TP, FP, and FN with probabilities after softmax or the sigmoid function; do not pass raw logits.
  • Decide whether to compute per image or over the whole batch: Computing the loss per image and averaging, versus pooling all pixels in the batch into one value, changes how small lesions are treated.
  • PyTorch has no built-in version: torch.nn has no Tversky loss, so it must be written by hand (see the implementation example below).

Comparison with Other Loss Functions

Losses used for segmentation are lined up from the same viewpoint.

Loss functionWhat it measuresTreatment of FP and FNWith little foregroundMain uses
Per-pixel cross-entropyAverage hit or miss of per-pixel probabilitiesAdjusted with class weightsEasily pulled toward backgroundSegmentation with similar amounts of foreground and background
Dice lossFraction of overlap between predicted and true regions (corresponds to the F1 score)Equal weightLess affected because it measures a ratioTwo-class segmentation with small foreground
Tversky lossWeighted fraction of overlap (α\alpha, β\beta)Separate weights via α\alpha and β\betaLess affected because it measures a ratioSegmentation with extremely little foreground where misses must be minimized (such as lesion detection)
Focal LossPer-pixel cross-entropy multiplied by a factor that down-weights easy pixelsWeights by easy vs. hard (does not distinguish FP and FN)Loss of easy background becomes smallClassification with overwhelmingly many easy background examples, such as object detection

Another overlap-based loss is Lovász-Softmax, which targets IoU (the overlap measure underlying mIoU).

Guidelines for choosing:

  • If misses are a particular problem, use Tversky loss: Setting β>α\beta > \alpha tilts training toward higher recall. The paper's setting α=0.3\alpha = 0.3, β=0.7\beta = 0.7 is one starting point.
  • If FP and FN can be weighted equally, use the Dice loss: It is the same as Tversky loss with α=β=0.5\alpha = \beta = 0.5 and adds no values to tune.
  • If foreground and background are similar in amount, start with per-pixel cross-entropy: It counts every pixel's loss equally and tends to train stably.

PyTorch example

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


def tversky_loss(probs, target, alpha=0.3, beta=0.7, eps=1e-6):
    """Eq. (3) of the paper: compute T = TP / (TP + α·FP + β·FN) on probabilities and return 1 − T.
    probs are foreground (lesion) probabilities, target is 0 or 1"""
    p = probs.reshape(-1)
    g = target.reshape(-1).float()
    tp = (p * g).sum()
    fp = (p * (1 - g)).sum()          # background predicted as foreground (weight α)
    fn = ((1 - p) * g).sum()          # missed foreground (weight β)
    return 1 - (tp + eps) / (tp + alpha * fp + beta * fn + eps)   # eps: avoid division by zero for images without foreground


# Example from the text (10 pixels)
g = torch.tensor([0, 0, 1, 1, 1, 1, 0, 0, 0, 0])
p = torch.tensor([0, 0.1, 0.9, 0.8, 0.6, 0.2, 0.1, 0, 0, 0])
print(tversky_loss(p, g, 0.5, 0.5).item())   # about 0.254 (T ≈ 0.746, same as the Dice loss with a sum-of-probabilities denominator)
print(tversky_loss(p, g, 0.3, 0.7).item())   # about 0.307 (T ≈ 0.693, misses count more heavily)


class TverskyLoss(nn.Module):
    """Turn the 2-channel (lesion / non-lesion) output into probabilities with softmax"""

    def __init__(self, alpha=0.3, beta=0.7):
        super().__init__()
        self.alpha, self.beta = alpha, beta

    def forward(self, logits, target):
        # logits: (B, 2, D, H, W), target: (B, D, H, W) of 0/1 (1 = lesion)
        probs = F.softmax(logits, dim=1)[:, 1]
        losses = [tversky_loss(probs[b], target[b], self.alpha, self.beta) for b in range(logits.shape[0])]
        return torch.stack(losses).mean()       # compute per image and average


criterion = TverskyLoss(alpha=0.3, beta=0.7)
logits = torch.randn(2, 2, 16, 32, 32, requires_grad=True)   # dummy output
target = (torch.rand(2, 16, 32, 32) > 0.995).long()         # lesions are about 0.5%
loss = criterion(logits, target)
loss.backward()

FAQ

Q. How should α and β be chosen?
A.

To reduce misses (FN), make β\beta larger than α\alpha and keep their sum at 1. In the paper's multiple sclerosis lesion experiment, α=0.3\alpha = 0.3, β=0.7\beta = 0.7 was best on the Dice coefficient, F2 score, and area under the PR curve, and β\beta of 0.8 or more lowered the Dice coefficient. The optimal values depend on the data, so choose them while watching the target metric on validation data.

Q. How do Tversky loss and Dice loss differ?
A.

Tversky loss with α=β=0.5\alpha = \beta = 0.5 is the same as the Dice loss (in the sum-of-probabilities denominator form). The Dice loss counts FP and FN with equal weight, while Tversky loss can give them separate weights via α\alpha and β\beta. The Dice loss is a special case of Tversky loss.

Q. Why does a larger β lower specificity?
A.

A larger β\beta makes the FP weight α\alpha relatively smaller, so wrongly predicting background as foreground barely increases the loss. The network becomes more likely to predict uncertain pixels as foreground, so misses decrease (sensitivity rises) but background errors (FP) increase and specificity drops. In the paper, raising β\beta from 0.5 to 0.9 increased sensitivity from 49.85% to 65.57% and decreased specificity from 99.93% to 99.87%.

References

  1. S. S. M. Salehi, D. Erdogmus, and A. Gholipour, "Tversky loss function for image segmentation using 3D fully convolutional deep networks," arXiv:1706.05721, 2017.
  2. F. Milletari, N. Navab, and S.-A. Ahmadi, "V-Net: Fully Convolutional Neural Networks for Volumetric Medical Image Segmentation," 3DV, 2016.