Algorithm Search⌘K

Definitioncore

Mean intersection over union

Also called mIoU, Jaccard score for segmentation.

The intersection over union of predicted and true pixels for each class, averaged over classes, the standard score for semantic segmentation.

Mean intersection over union (mIoU) is the standard score of semantic segmentation. For each class it takes the pixels that are truly of that class and the pixels that are predicted as that class, over the whole data set, and divides the size of their intersection by the size of their union. This is the intersection over union, or Jaccard index, of two pixel sets. The score is the mean of these values over the classes. It is 1 only for a perfect labeling, and every class has the same weight, whatever its size. Pixels marked void in the ground truth do not count.

Definition

Let there be KK classes and a data set of pairs of label images (g,p)(g, p) of the same size, where gg is the ground truth and pp the prediction. A true label is a class 0,…,K−10, \ldots, K - 1 or the void label, which is 255 in PASCAL VOC. Let VV be the set of all non-void pixels of all images. The confusion matrix is

nij=∣{x∈V:g(x)=i, p(x)=j}∣,n_{ij} = \bigl|\{x \in V : g(x) = i,\ p(x) = j\}\bigr|,

the number of pixels of true class ii predicted as class jj. With ti=∑jnijt_i = \sum_j n_{ij}, the number of pixels of true class ii, the IoU of class ii is

IoUi=niiti+∑jnji−nii=TPiTPi+FPi+FNi,\mathrm{IoU}_i = \frac{n_{ii}}{t_i + \sum_j n_{ji} - n_{ii}} = \frac{\mathrm{TP}_i}{\mathrm{TP}_i + \mathrm{FP}_i + \mathrm{FN}_i},

and the mIoU is the mean of IoUi\mathrm{IoU}_i over the classes. Long, Shelhamer and Darrell (2015) write the score in this form, and PASCAL VOC writes it as true positives over the sum of true positives, false positives and false negatives.

  1. MEAN-IOU(pairs, K, void)
  2. 1n ← K × K matrix of zeros
  3. 2for each pair (g, p) and each pixel x of the image do
  4. 3if g(x) = void then skip x
  5. 4n[g(x)][p(x)] ← n[g(x)][p(x)] + 1
  6. 5S ← 0 ; c ← 0
  7. 6for i ← 0 to K - 1 do
  8. 7t ← Σ_j n[i][j] + Σ_j n[j][i] - n[i][i] ▷ TP + FN + FP
  9. 8if t > 0 then S ← S + n[i][i] / t ; c ← c + 1
  10. 9return S / c

The proof file shows that tt in line L7 is the size of the union of the true and the predicted region of class ii, so that each term is an exact Jaccard index (a theorem). It also shows that the score is in [0,1][0, 1] and that it is 1 exactly when the prediction equals the truth on all non-void pixels. The cost is O(N+K2)O(N + K^2) for NN pixels, and the matrix needs O(K2)O(K^2) space for any number of images.

Three conventions change the number and must be stated with a result:

  • Data set or image. The matrix is summed over all images before the division. The mean over images of the mIoU of each image is a different score.
  • Absent classes. A class that is neither true nor predicted anywhere has the ratio 0/00/0. Line L8 leaves it out. A class that is predicted but not true counts with the value 0. Some codes average over all KK classes instead.
  • Void. Void pixels are skipped whatever the prediction there. In PASCAL VOC the void label covers a band of 5 pixels along object borders and unclear regions, so errors at the borders do not count.

Long, Shelhamer and Darrell (2015) report three more scores from the same matrix: the pixel accuracy ∑inii/∑iti\sum_i n_{ii} / \sum_i t_i, the mean accuracy 1K∑inii/ti\frac{1}{K} \sum_i n_{ii} / t_i, and the frequency weighted IU ∑itiIoUi/∑iti\sum_i t_i \mathrm{IoU}_i / \sum_i t_i.

Examples and non-examples

  • A small example. One image with three classes, read row by row: gg = 0 0 1 1 / 0 0 1 1 / 0 0 2 2 / void 0 2 2 and pp = 0 0 0 1 / 0 1 1 1 / 0 0 2 2 / 2 0 0 2. The void pixel is skipped, so 15 pixels count. The confusion matrix has rows (6,1,0)(6, 1, 0), (1,3,0)(1, 3, 0) and (1,0,3)(1, 0, 3). The class IoUs are 6/(7+8−6)=2/36/(7 + 8 - 6) = 2/3, 3/(4+4−3)=3/53/(4 + 4 - 3) = 3/5 and 3/(4+3−3)=3/43/(4 + 3 - 3) = 3/4, and the mIoU is 121/180≈0.672121/180 \approx 0.672. The pixel accuracy is 12/15=0.812/15 = 0.8, the mean accuracy is 11/14≈0.78611/14 \approx 0.786 and the frequency weighted IU is 151/225≈0.671151/225 \approx 0.671.
  • Small classes count fully. In an image of 64 pixels with one pixel of class 1 and all predictions 0, the pixel accuracy is 63/64≈0.9863/64 \approx 0.98, but the mIoU is (63/64+0)/2≈0.49(63/64 + 0)/2 \approx 0.49. This is the reason to report mIoU and not only accuracy (Proposition 5 of the proof).
  • The order of the means. Image A has truth 0 0 0 1 and prediction 0 0 0 0, with mIoU (3/4+0)/2=3/8(3/4 + 0)/2 = 3/8. Image B has truth and prediction 1 1 1 1, with mIoU 1, since class 0 is absent. The mean of the two is 11/1611/16. The summed matrix has rows (3,0)(3, 0) and (1,4)(1, 4), which gives (3/4+4/5)/2=31/40(3/4 + 4/5)/2 = 31/40. The two numbers differ, and papers must say which one they report.
  • Not detection mAP. mIoU looks only at the class of each pixel. It does not know about objects, so two touching objects of one class that are merged into one region get a perfect score. Instance tasks use detection mean average precision on masks or the panoptic quality of panoptic segmentation.
  • Not the Dice score. The Dice score of a class, 2nii/(ti+∑jnji)2 n_{ii} / (t_i + \sum_j n_{ji}), equals 2J/(1+J)2J/(1 + J) for its IoU JJ. It ranks one class in the same order, but the mean of the Dice scores is a different number. In the small example the Dice scores are 4/54/5, 3/43/4 and 6/76/7.

The intersection over union of two boxes or two masks is the ratio for a single pair; the mIoU applies it to the pixel sets of each class and averages. The per-class score is the Jaccard similarity of two sets, and the Dice score is the F1 score of precision and recall on the pixels of the class. Mean accuracy averages the recall of each class, and it ignores false positives. The boundary F-measure scores only the pixels near region borders, which mIoU weights by their small number. For segmentations without class labels, scores that compare partitions, such as the Rand index, are used instead. The panoptic quality of panoptic segmentation averages the IoU of matched segments and adds a count of unmatched ones.

The Python code of this page builds the confusion matrix, computes the class IoUs, the mIoU and the other three scores of Long et al. with exact fractions, and its tests compare each class IoU with a Jaccard index computed on sets of pixels.

Proof: The confusion matrix gives the Jaccard index of each class, and properties of the meanfull

We use the notation of the page. There are KK classes, a data set of image pairs (g,p)(g, p), and a void index. Index the pixels of the data set by (e,u,v)(e, u, v), where ee is the number of the image. Let VV be the set of pixels whose true label is not void. For a class ii let

Gi={x∈V:g(x)=i},Pi={x∈V:p(x)=i}.G_i = \{x \in V : g(x) = i\}, \qquad P_i = \{x \in V : p(x) = i\}.

The procedure MEAN-IOU builds the matrix nn in lines L1 to L4 and averages in lines L5 to L9.

Lemma 1 (the confusion matrix). After line L4, nij=∣Gi∩Pj∣n_{ij} = |G_i \cap P_j| for all classes ii and jj.

Proof. Line L3 skips exactly the pixels outside VV. Each pixel of VV is visited once, in its image, and line L4 adds 1 to the entry (g(x),p(x))(g(x), p(x)) and to no other entry. So nijn_{ij} counts the pixels of VV with g(x)=ig(x) = i and p(x)=jp(x) = j. □\square

The matrix does not depend on the order of the images or on the predicted labels at void pixels, since each pixel adds 1 to one entry and void pixels add nothing.

Theorem 1 (each class score is a Jaccard index). For each class ii, the value tit_i of line L7 is ∣Gi∪Pi∣|G_i \cup P_i|, and if ti>0t_i > 0 then nii/ti=∣Gi∩Pi∣/∣Gi∪Pi∣n_{ii} / t_i = |G_i \cap P_i| / |G_i \cup P_i|.

Proof. The sets GiG_i for i=0,…,K−1i = 0, \ldots, K - 1 partition VV, and so do the sets PjP_j. So ∑jnij=∑j∣Gi∩Pj∣=∣Gi∣\sum_j n_{ij} = \sum_j |G_i \cap P_j| = |G_i| and ∑jnji=∣Pi∣\sum_j n_{ji} = |P_i|. Line L7 gives ti=∣Gi∣+∣Pi∣−∣Gi∩Pi∣=∣Gi∪Pi∣t_i = |G_i| + |P_i| - |G_i \cap P_i| = |G_i \cup P_i|, by inclusion and exclusion, and nii=∣Gi∩Pi∣n_{ii} = |G_i \cap P_i| by Lemma 1. □\square

So the score of class ii is the intersection over union of the true and the predicted region of class ii, both taken over the whole data set as one pixel set. Line L8 counts the class only if ti>0t_i > 0. A class with ti=0t_i = 0 appears neither in the truth nor in the prediction, and its ratio would be 0/00/0. A class that is predicted but never true has ti=∣Pi∣>0t_i = |P_i| > 0 and nii=0n_{ii} = 0, so it counts with the value 0. Line L9 returns the mean of the cc counted values, and the procedure returns no value when c=0c = 0.

Corollary 1 (range and the perfect score). If at least one class is counted, then 0≤mIoU≤10 \le \mathrm{mIoU} \le 1, and mIoU=1\mathrm{mIoU} = 1 if and only if p(x)=g(x)p(x) = g(x) for every x∈Vx \in V.

Proof. Each counted value is in [0,1][0, 1], since Gi∩Pi⊆Gi∪PiG_i \cap P_i \subseteq G_i \cup P_i, so their mean is too. If p=gp = g on VV, then Pi=GiP_i = G_i for all ii and every counted value is 1. Conversely, if the mean is 1, every counted value is 1. If some x∈Vx \in V had g(x)=i≠j=p(x)g(x) = i \ne j = p(x), then x∈Gi∖Pix \in G_i \setminus P_i, so ti>0t_i > 0 and ∣Gi∩Pi∣<∣Gi∪Pi∣|G_i \cap P_i| < |G_i \cup P_i|, and the value of class ii would be below 1. □\square

Corollary 2 (relabeling). If a permutation π\pi of the classes is applied to both gg and pp, the mIoU does not change.

Proof. The new sets are Gπ(i)′=GiG'_{\pi(i)} = G_i and Pπ(i)′=PiP'_{\pi(i)} = P_i, so the new values are the old ones in another order. The mean of a set of numbers does not depend on the order. □\square

Corollary 3 (Dice). For a class with ti>0t_i > 0, the Dice score Di=2∣Gi∩Pi∣/(∣Gi∣+∣Pi∣)D_i = 2 |G_i \cap P_i| / (|G_i| + |P_i|) equals 2Ji/(1+Ji)2 J_i / (1 + J_i), where JiJ_i is the class IoU. So DiD_i is an increasing function of JiJ_i.

Proof. Write a=∣Gi∩Pi∣a = |G_i \cap P_i| and t=∣Gi∪Pi∣t = |G_i \cup P_i|. Then ∣Gi∣+∣Pi∣=t+a|G_i| + |P_i| = t + a, and 2J/(1+J)=2(a/t)/((t+a)/t)=2a/(t+a)2 J / (1 + J) = 2 (a / t) / ((t + a)/t) = 2a / (t + a). The function J↦2J/(1+J)J \mapsto 2J/(1 + J) has derivative 2/(1+J)2>02/(1 + J)^2 > 0. □\square

The mean of the DiD_i and the mean of the JiJ_i need not rank two predictions in the same order, because the map is not linear. The tests check Corollary 3 per class.

Proposition 4 (the data set score is not the mean of the image scores). In general, the mIoU of the confusion matrix summed over the images differs from the mean of the mIoU of each image.

Proof. The example of the page is a counterexample: two images with the scores 3/83/8 and 11 have the mean 11/1611/16, while the summed matrix gives 31/4031/40. □\square

Proposition 5 (pixel accuracy and mIoU). Pixel accuracy, the trace of nn over the sum of nn, can be close to 1 while the mIoU is close to 12\tfrac12.

Proof. Let VV have NN pixels, all of class 0 but one of class 1, and let pp be 0 everywhere. The accuracy is (N−1)/N(N - 1)/N. Class 0 has IoU (N−1)/N(N - 1)/N, class 1 has IoU 0/1=00/1 = 0, so the mIoU is (N−1)/(2N)(N - 1)/(2N). □\square

Cost. Lines L1 to L4 take O(K2+N)O(K^2 + N) time for NN pixels in total. Lines L5 to L9 take O(K2)O(K^2) time as written, or O(K)O(K) with the row and column sums kept during the count. The extra space is O(K2)O(K^2) for the matrix, independent of the number of images.

Code

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

mean_intersection_over_union.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mean-intersection-over-union/. The authors are listed in prov/7XWT5K.jsonl.

"""Mean intersection over union (mIoU) for semantic segmentation.

A label image is a list of rows, img[v][u]. Ground-truth values are class
indices 0 .. K - 1 or the void index (255 by default), which is ignored.
Predicted values must be class indices. All counts are integers and all scores
are Fractions, so results are exact. Standard library only.
"""

from fractions import Fraction

VOID = 255


def confusion_matrix(pairs, k, void=VOID):
    """Return the K x K matrix n with n[i][j] = pixels of true class i predicted as j, over all pairs."""
    n = [[0] * k for _ in range(k)]  # @line L1
    for gt, pred in pairs:  # @line L2
        for grow, prow in zip(gt, pred):
            for g, p in zip(grow, prow):
                if g == void:  # @line L3
                    continue
                if not (0 <= g < k and 0 <= p < k):
                    raise ValueError("label out of range")
                n[g][p] += 1  # @line L4
    return n


def class_iou(n):
    """Return the IoU of each class as a Fraction, or None for a class that is neither true nor predicted."""
    k = len(n)
    out = []
    for i in range(k):
        t = sum(n[i]) + sum(n[j][i] for j in range(k)) - n[i][i]
        out.append(Fraction(n[i][i], t) if t > 0 else None)
    return out


def mean_iou(n):
    """Mean of the class IoUs over the classes with a defined IoU, or None if there is none."""
    k = len(n)
    s, c = Fraction(0), 0  # @line L5
    for i in range(k):  # @line L6
        t = sum(n[i]) + sum(n[j][i] for j in range(k)) - n[i][i]  # @line L7
        if t > 0:  # @line L8
            s += Fraction(n[i][i], t)
            c += 1
    return s / c if c else None  # @line L9


def pixel_accuracy(n):
    total = sum(map(sum, n))
    return Fraction(sum(n[i][i] for i in range(len(n))), total) if total else None


def mean_accuracy(n):
    vals = [Fraction(n[i][i], sum(n[i])) for i in range(len(n)) if sum(n[i])]
    return sum(vals, Fraction(0)) / len(vals) if vals else None


def frequency_weighted_iou(n):
    total = sum(map(sum, n))
    ious = class_iou(n)
    return sum((Fraction(sum(n[i]), total) * ious[i] for i in range(len(n)) if sum(n[i])), Fraction(0))


def dice(n):
    """Per-class Dice (F1) score 2 n_ii / (|G_i| + |P_i|), or None."""
    k = len(n)
    out = []
    for i in range(k):
        s = sum(n[i]) + sum(n[j][i] for j in range(k))
        out.append(Fraction(2 * n[i][i], s) if s else None)
    return out


def per_image_mean_iou(pairs, k, void=VOID):
    """Average over images of the mIoU of each image: a different score, shown for contrast."""
    vals = [mean_iou(confusion_matrix([pair], k, void)) for pair in pairs]
    vals = [x for x in vals if x is not None]
    return sum(vals, Fraction(0)) / len(vals) if vals else None
test_mean_intersection_over_union.py 131 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mean-intersection-over-union/. The authors are listed in prov/7XWT5K.jsonl.

import random
from fractions import Fraction

from mean_intersection_over_union import (VOID, class_iou, confusion_matrix, dice, frequency_weighted_iou,
                                          mean_accuracy, mean_iou, per_image_mean_iou, pixel_accuracy)

GT = [[0, 0, 1, 1], [0, 0, 1, 1], [0, 0, 2, 2], [VOID, 0, 2, 2]]
PRED = [[0, 0, 0, 1], [0, 1, 1, 1], [0, 0, 2, 2], [2, 0, 0, 2]]


def random_pair(rng, k, w, h, void_rate=0.1):
    gt = [[VOID if rng.random() < void_rate else rng.randrange(k) for _ in range(w)] for _ in range(h)]
    pred = [[rng.randrange(k) for _ in range(w)] for _ in range(h)]
    return gt, pred


def jaccard_by_sets(pairs, k, i):
    """IoU of class i from pixel sets, keyed by (image, u, v)."""
    g, p = set(), set()
    for idx, (gt, pred) in enumerate(pairs):
        for v, row in enumerate(gt):
            for u, lab in enumerate(row):
                if lab == VOID:
                    continue
                if lab == i:
                    g.add((idx, u, v))
                if pred[v][u] == i:
                    p.add((idx, u, v))
    union = g | p
    return Fraction(len(g & p), len(union)) if union else None


def test_page_example():
    n = confusion_matrix([(GT, PRED)], 3)
    assert n == [[6, 1, 0], [1, 3, 0], [1, 0, 3]]
    assert class_iou(n) == [Fraction(2, 3), Fraction(3, 5), Fraction(3, 4)]
    assert mean_iou(n) == Fraction(121, 180)
    assert pixel_accuracy(n) == Fraction(4, 5)
    assert mean_accuracy(n) == Fraction(11, 14)
    assert frequency_weighted_iou(n) == Fraction(151, 225)


def test_matches_set_jaccard():
    rng = random.Random(31)
    for _ in range(20):
        k = rng.randrange(2, 6)
        pairs = [random_pair(rng, k, rng.randrange(1, 9), rng.randrange(1, 9)) for _ in range(rng.randrange(1, 4))]
        n = confusion_matrix(pairs, k)
        ious = class_iou(n)
        for i in range(k):
            assert ious[i] == jaccard_by_sets(pairs, k, i)
        defined = [x for x in ious if x is not None]
        assert mean_iou(n) == sum(defined, Fraction(0)) / len(defined)


def test_void_is_ignored_and_order_does_not_matter():
    rng = random.Random(32)
    pairs = [random_pair(rng, 4, 6, 5, void_rate=0.3) for _ in range(4)]
    n = confusion_matrix(pairs, 4)
    assert sum(map(sum, n)) == sum(1 for gt, _ in pairs for row in gt for x in row if x != VOID)
    changed = []
    for gt, pred in pairs:
        pred2 = [[(x + 1) % 4 if g == VOID else x for g, x in zip(gr, pr)] for gr, pr in zip(gt, pred)]
        changed.append((gt, pred2))
    assert confusion_matrix(changed, 4) == n
    assert confusion_matrix(list(reversed(pairs)), 4) == n


def test_range_and_perfect_prediction():
    rng = random.Random(33)
    for _ in range(20):
        gt, pred = random_pair(rng, 3, 5, 5)
        n = confusion_matrix([(gt, pred)], 3)
        m = mean_iou(n)
        assert 0 <= m <= 1
        perfect = [[x if x != VOID else 0 for x in row] for row in gt]
        assert mean_iou(confusion_matrix([(gt, perfect)], 3)) == 1
        assert (m == 1) == all(n[i][j] == 0 for i in range(3) for j in range(3) if i != j)


def test_absent_class_rules():
    gt, pred = [[0, 0]], [[0, 0]]
    n = confusion_matrix([(gt, pred)], 3)
    assert class_iou(n) == [1, None, None] and mean_iou(n) == 1
    n = confusion_matrix([(gt, [[0, 2]])], 3)
    assert class_iou(n) == [Fraction(1, 2), None, 0]  # predicted but absent: IoU 0, and it counts
    assert mean_iou(n) == Fraction(1, 4)


def test_dataset_score_differs_from_mean_of_images():
    a = ([[0, 0, 0, 1]], [[0, 0, 0, 0]])
    b = ([[1, 1, 1, 1]], [[1, 1, 1, 1]])
    assert mean_iou(confusion_matrix([a, b], 2)) == Fraction(31, 40)
    assert per_image_mean_iou([a, b], 2) == Fraction(11, 16)


def test_imbalance_accuracy_versus_miou():
    g = [[0] * 8 for _ in range(8)]
    g[0][0] = 1
    p = [[0] * 8 for _ in range(8)]
    n = confusion_matrix([(g, p)], 2)
    assert pixel_accuracy(n) == Fraction(63, 64)
    assert mean_iou(n) == Fraction(63, 128)


def test_dice_is_increasing_function_of_iou():
    rng = random.Random(34)
    gt, pred = random_pair(rng, 5, 8, 8)
    n = confusion_matrix([(gt, pred)], 5)
    for j, d in zip(class_iou(n), dice(n)):
        assert (j is None and d is None) or d == 2 * j / (1 + j)


def test_permuting_labels_keeps_the_score():
    rng = random.Random(35)
    gt, pred = random_pair(rng, 4, 7, 6)
    perm = [2, 0, 3, 1]
    gt2 = [[x if x == VOID else perm[x] for x in row] for row in gt]
    pred2 = [[perm[x] for x in row] for row in pred]
    assert mean_iou(confusion_matrix([(gt, pred)], 4)) == mean_iou(confusion_matrix([(gt2, pred2)], 4))


def test_bad_labels_raise():
    try:
        confusion_matrix([([[0]], [[3]])], 3)
    except ValueError:
        return
    raise AssertionError("expected ValueError")

References

  1. Jonathan Long, Evan Shelhamer and Trevor Darrell, Fully convolutional networks for semantic segmentation, IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2015, 3431-3440 (arXiv 1411.4038), Section 5, Metrics (pixel accuracy, mean accuracy, mean IU and frequency weighted IU, written with n_ij and t_i)
  2. Mark Everingham, Luc Van Gool, Christopher K. I. Williams, John Winn and Andrew Zisserman, The PASCAL Visual Object Classes (VOC) challenge, International Journal of Computer Vision 88(2), 2010, 303-338, Section 4.2.1, Segmentation accuracy, Eq. (4) (true positives over true positives, false positives and false negatives, void pixels excluded, the void border of 5 pixels)
  3. Richard Szeliski, Computer Vision, Algorithms and Applications, second edition, Springer, 2022, Section 6.4, Semantic segmentation (the evaluation of per-pixel labels)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH2 full proof
  • correctness: no review record reviews/7XWT5K/proof-correctness.yaml
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/7XWT5K/text.yaml