AI Logic

Evaluation Metrics

Mean Intersection over Union (mIoU)

Updated๏ผš

Computing mIoU. Top: ground truth and prediction on a 10 ร— 7 pixel image (background, person, car). Bottom: for each of background, person and car, the TP, FP and FN pixels are colored, and the resulting IoU (background 0.80, person 0.67, car 0.29) is shown. Right: their mean, mIoU 0.59, and for reference the pixel accuracy 0.84

Background and overview

mIoU (mean intersection over union) is an evaluation metric for semantic segmentation, which assigns a class to every pixel of an image, that computes the overlap (IoU) between the predicted region and the ground-truth region for each class and averages it over classes. It ranges from 0 to 1, and values closer to 1 mean closer agreement with the ground-truth regions. Papers usually multiply it by 100 and write it as a percentage.

IoUc=TPcTPc+FPc+FNc,mIoU=1Cโˆ‘c=1CIoUc\mathrm{IoU}_c = \frac{\mathrm{TP}_c}{\mathrm{TP}_c + \mathrm{FP}_c + \mathrm{FN}_c}, \qquad \mathrm{mIoU} = \frac{1}{C} \sum_{c=1}^{C} \mathrm{IoU}_c

TPc\mathrm{TP}_c is the number of pixels that are class cc in both the ground truth and the prediction, FPc\mathrm{FP}_c the number that are class cc only in the prediction, and FNc\mathrm{FN}_c the number that are class cc only in the ground truth. The numerator is the area of the intersection of the two regions and the denominator the area of their union, so IoU is "the fraction of overlap". It is also called the Jaccard index.

mIoU became the official metric of the PASCAL VOC segmentation task in 2008. The earlier VOC2007 used, for each class, "the fraction of ground-truth pixels predicted correctly", which had the flaw that labeling every pixel as "car" would give the car class a perfect score. The challenge therefore switched to IoU, which also penalizes pixels that are that class only in the prediction (FP). The FCN paper also reported this metric under the name mean IU, and it remains the main metric for segmentation today.

Definition and computation

mIoU is computed over the whole test set in the following steps.

  1. Over the pixels of all test images, count each pair of ground-truth class ii and predicted class jj to build the confusion matrix nijn_{ij} (the number of pixels whose ground truth is ii and prediction is jj). Pixels marked "void" in the ground truth (ambiguous pixels such as boundaries) are not counted.
  2. For each class ii, compute TPi=nii\mathrm{TP}_i = n_{ii}, FNi=โˆ‘jnijโˆ’nii\mathrm{FN}_i = \sum_j n_{ij} - n_{ii} (pixels with ground truth ii that were missed), and FPi=โˆ‘jnjiโˆ’nii\mathrm{FP}_i = \sum_j n_{ji} - n_{ii} (pixels predicted as ii that are actually something else).
  3. Compute the IoU of each class. In the notation of the FCN paper, with ti=โˆ‘jnijt_i = \sum_j n_{ij} (the number of pixels with ground truth ii), it is as follows.
IoUi=niiti+โˆ‘jnjiโˆ’nii\mathrm{IoU}_i = \frac{n_{ii}}{t_i + \sum_j n_{ji} - n_{ii}}
  1. Average over the number of classes ncln_{\mathrm{cl}}. PASCAL VOC2012 averages over 21 classes: 20 object classes plus background.

In the example in the figure at the top, on an image of 10 ร— 7 = 70 pixels, the person is painted one column too wide (6 FP pixels) and more than half of the car is missed. The IoU is 0.80 for background, 0.67 for person and 0.29 for car, and the mIoU is 0.59. Meanwhile, the fraction of pixels with the correct class (pixel accuracy) is 59/70 = 0.84. The correct predictions on the large background area hide the missed car.

Alongside mIoU, the FCN paper also defines the following three metrics.

MetricFormulaMeaning
Pixel accuracyโˆ‘inii/โˆ‘iti\sum_i n_{ii} / \sum_i t_iFraction of pixels with the correct class
Mean accuracy1nclโˆ‘inii/ti\frac{1}{n_{\mathrm{cl}}} \sum_i n_{ii} / t_iMean of per-class recall (equivalent to averaging the VOC2007 per-class metric)
mIoU1nclโˆ‘inii/(ti+โˆ‘jnjiโˆ’nii)\frac{1}{n_{\mathrm{cl}}} \sum_i n_{ii} / (t_i + \sum_j n_{ji} - n_{ii})Mean of per-class IoU
Frequency-weighted IoU(โˆ‘ktk)โˆ’1โˆ‘itinii/(ti+โˆ‘jnjiโˆ’nii)(\sum_k t_k)^{-1} \sum_i t_i n_{ii} / (t_i + \sum_j n_{ji} - n_{ii})Mean of IoU weighted by the number of ground-truth pixels

IoU is related to the Dice coefficient (F1 score), the basis of the Dice loss, by Dice=2โ€‰IoU/(1+IoU)\mathrm{Dice} = 2\,\mathrm{IoU} / (1 + \mathrm{IoU}). The two agree at 0 and 1 and preserve order, so for comparisons on a single class they give the same ranking. The values differ, however: an IoU of 0.5 corresponds to a Dice of about 0.67.

What it measures and its limitations

mIoU measures whether, for every class, there is little of both missed area (FN) and over-painted area (FP). Since both FP and FN appear in the denominator, a prediction that paints everything as one class also lowers that class's IoU. And because classes are averaged with equal weight, classes with few pixels (distant people, signs, etc.) count as much as background or road.

mIoU also has the following limitations.

  • Small objects are judged more harshly: the same one-pixel boundary shift lowers IoU much more for a small region.
  • It does not count individual objects: mIoU looks only at the set of pixels of each class, so it does not distinguish two overlapping objects of the same class. Instance segmentation, which separates individual objects, is evaluated separately with metrics such as mAP.
  • Boundary accuracy matters less for large regions: in a large region, a slightly shifted contour barely lowers IoU.
  • The value depends on how it is aggregated: summing pixels over the whole test set before computing IoU gives a different value from computing IoU per image and averaging. The VOC and FCN definitions sum over the whole set first.

When comparing mIoU values, make sure which classes are included in the average, how void pixels are handled, and whether counts are summed over the whole set before computing are the same. The FCN paper reports values that exclude classes not present in the test set from the average; an earlier version that also included classes appearing only in predictions reported lower mIoU. A class that appears in neither the ground truth nor the prediction has an IoU of 0/0, so implementations differ on whether to exclude it or count it as 0.

Validation in the original paper

The FCN paper reports the results of the same model with four metrics. It shows that mIoU is considerably lower than pixel accuracy.

Dataset (model)Pixel accuracyMean accuracymIoUFrequency-weighted IoU
NYUDv2, 40 classes (FCN-16s RGB-HHA)65.446.134.049.5
SIFT Flow, 33 classes (FCN-16s)85.251.739.576.1

On SIFT Flow, the model predicts the correct class for 85.2% of pixels, yet the mIoU is 39.5. Classes with many pixels (sky, buildings, etc.) are easy to get right, and poor performance on classes with few pixels pulls mIoU down substantially. The frequency-weighted IoU (76.1) weights classes with many pixels more heavily, so it comes out close to pixel accuracy.

The only metric returned by the PASCAL VOC test server is mIoU, and FCN-8s scored 62.2 on the VOC2012 test set (the previous best, SDS, scored 51.6).

Where it is used

mIoU is mainly used in the following settings.

  • Semantic segmentation benchmarks: it is reported as the main metric on PASCAL VOC and many other datasets, including street scenes and indoor scenes. It is the common yardstick for comparing models such as FCN, U-Net, DeepLab v3 and DeepLab v3+.
  • Validation during training: the mIoU on validation data is used to choose when to stop training and to select hyperparameters.
  • Designing loss functions: IoU counts pixels from hard class decisions (argmax), so its gradient cannot be computed as is and it cannot be used directly as a training loss. To optimize IoU directly, differentiable surrogate losses have been devised, such as Lovรกsz-Softmax and the Dice loss, which uses the closely related Dice coefficient.

Comparison with similar metrics

The table compares mIoU with other metrics used to evaluate segmentation and detection from the same viewpoints.

MetricHow it countsPenalizes FP (over-painting)?Weight of small classesTypical task
mIoUMean of per-class TP / (TP + FP + FN)YesSame as large classesSemantic segmentation
Pixel accuracyFraction of correct pixelsCounted without distinguishing classesSmall (proportional to pixel count)Auxiliary metric
Mean accuracyMean of per-class TP / (TP + FN)NoSame as large classesAuxiliary metric (VOC2007)
Dice coefficient (F1 score)2TP / (2TP + FP + FN)YesSame if averaged per classMedical image segmentation
mAPJudges correctness per object by IoU, computed from the precision-recall curveYes (false detections)Averaged per classObject detection, instance segmentation

Rough guidelines for choosing:

  • Comparing with prior work in semantic segmentation: compute mIoU with the same set of classes and the same handling of void pixels.
  • Class pixel counts are highly imbalanced and overall correctness also matters: report pixel accuracy and frequency-weighted IoU alongside mIoU.
  • Measuring the region overlap of a single target, as in medical images: the Dice coefficient is commonly used. It ranks the same as IoU, so choose according to convention.
  • Distinguishing individual objects: use mAP, which judges each object separately.

PyTorch example

Show code
python
import torch


def confusion_matrix(pred, target, num_classes, ignore_index=255):
  """Per-pixel confusion matrix n[i, j] (number of pixels with ground truth i and prediction j).
  pred and target are integer tensors of the same shape (class indices). Pixels equal to ignore_index (void) are not counted."""
  keep = target != ignore_index
  idx = target[keep] * num_classes + pred[keep]
  return torch.bincount(idx, minlength=num_classes ** 2).reshape(num_classes, num_classes)


def mean_iou(conf):
  """mean IU from the FCN paper: (1/n_cl) ฮฃ_i n_ii / (t_i + ฮฃ_j n_ji โˆ’ n_ii).
  Classes that appear in neither the ground truth nor the prediction (denominator 0) are excluded from the mean."""
  tp = conf.diag().float()
  denom = conf.sum(dim=1).float() + conf.sum(dim=0).float() - tp  # TP + FN + FP
  iou = tp / denom.clamp(min=1)
  valid = denom > 0
  return iou[valid].mean(), iou


# Sum the confusion matrix over the whole test set, then compute (not the mean of per-image IoU)
num_classes = 21  # PASCAL VOC: 20 classes + background
conf = torch.zeros(num_classes, num_classes, dtype=torch.long)
model.eval()
with torch.no_grad():
  for images, masks in loader:              # masks: (B, H, W), void is 255
    logits = model(images)                  # (B, C, H, W)
    pred = logits.argmax(dim=1)
    conf += confusion_matrix(pred, masks, num_classes)
miou, per_class = mean_iou(conf)
pixel_acc = conf.diag().sum() / conf.sum()  # for reference: pixel accuracy

# With torchmetrics: counts are accumulated on each update, and average="macro" takes the class mean
from torchmetrics.classification import MulticlassJaccardIndex

metric = MulticlassJaccardIndex(num_classes=num_classes, ignore_index=255, average="macro")

FAQ

Q. Should I report mIoU or pixel accuracy?
A.

In semantic segmentation, use mIoU as the main metric. Pixel accuracy is dominated by classes with large areas such as background, so missed small classes barely show up in its value. Reporting pixel accuracy and other metrics alongside, as the FCN paper does, makes the model's tendencies easier to see.

Q. Can I compute IoU per image and average?
A.

Avoid it when comparing with prior work. The PASCAL VOC and FCN definitions compute IoU from a confusion matrix summed over all pixels of the test set. Averaging per image adds the question of how to handle images in which a class does not appear, and changes the value.

Q. Should I use IoU or the Dice coefficient?
A.

Both measure overlap and are related by Dice = 2IoU / (1 + IoU), so they give the same ranking when comparing on a single class. By convention, mIoU is common for general-scene segmentation and the Dice coefficient for medical images, so follow the prior work you want to compare with.

References

  1. Everingham, M., Van Gool, L., Williams, C. K. I., Winn, J., & Zisserman, A. (2010). The PASCAL Visual Object Classes (VOC) Challenge. International Journal of Computer Vision, 88(2), 303โ€“338.
  2. Everingham, M., & Winn, J. The PASCAL Visual Object Classes Challenge 2012 (VOC2012) Development Kit.
  3. Long, J., Shelhamer, E., & Darrell, T. (2015). Fully Convolutional Networks for Semantic Segmentation. CVPR 2015. arXiv:1411.4038.
  4. Lightning AI. torchmetrics.classification.JaccardIndex (API reference).