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 classes and a data set of pairs of label images of the same size, where is the ground truth and the prediction. A true label is a class or the void label, which is 255 in PASCAL VOC. Let be the set of all non-void pixels of all images. The confusion matrix is
the number of pixels of true class predicted as class . With , the number of pixels of true class , the IoU of class is
and the mIoU is the mean of 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.
MEAN-IOU(pairs, K, void)- 1
n ← K × K matrix of zeros - 2
for each pair (g, p) and each pixel x of the image do - 3
if g(x) = void then skip x - 4
n[g(x)][p(x)] ← n[g(x)][p(x)] + 1 - 5
S ← 0 ; c ← 0 - 6
for i ← 0 to K - 1 do - 7
t ← Σ_j n[i][j] + Σ_j n[j][i] - n[i][i] ▷ TP + FN + FP - 8
if t > 0 then S ← S + n[i][i] / t ; c ← c + 1 - 9
return S / c
The proof file shows that in line L7 is the size of the union of the true and the predicted region of class , so that each term is an exact Jaccard index (a theorem). It also shows that the score is in and that it is 1 exactly when the prediction equals the truth on all non-void pixels. The cost is for pixels, and the matrix needs 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 . Line L8 leaves it out. A class that is predicted but not true counts with the value 0. Some codes average over all 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 , the mean accuracy , and the frequency weighted IU .
Examples and non-examples
- A small example. One image with three classes, read row by row:
=
0 0 1 1 / 0 0 1 1 / 0 0 2 2 / void 0 2 2and =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 , and . The class IoUs are , and , and the mIoU is . The pixel accuracy is , the mean accuracy is and the frequency weighted IU is . - Small classes count fully. In an image of 64 pixels with one pixel of class 1 and all predictions 0, the pixel accuracy is , but the mIoU is . 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 1and prediction0 0 0 0, with mIoU . Image B has truth and prediction1 1 1 1, with mIoU 1, since class 0 is absent. The mean of the two is . The summed matrix has rows and , which gives . 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, , equals for its IoU . 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 , and .
Related definitions
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 classes, a data set of image pairs , and a void index. Index the pixels of the data set by , where is the number of the image. Let be the set of pixels whose true label is not void. For a class let
The procedure MEAN-IOU builds the matrix in lines L1 to L4 and averages in lines L5 to L9.
Lemma 1 (the confusion matrix). After line L4, for all classes and .
Proof. Line L3 skips exactly the pixels outside . Each pixel of is visited once, in its image, and line L4 adds 1 to the entry and to no other entry. So counts the pixels of with and .
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 , the value of line L7 is , and if then .
Proof. The sets for partition , and so do the sets . So and . Line L7 gives , by inclusion and exclusion, and by Lemma 1.
So the score of class is the intersection over union of the true and the predicted region of class , both taken over the whole data set as one pixel set. Line L8 counts the class only if . A class with appears neither in the truth nor in the prediction, and its ratio would be . A class that is predicted but never true has and , so it counts with the value 0. Line L9 returns the mean of the counted values, and the procedure returns no value when .
Corollary 1 (range and the perfect score). If at least one class is counted, then , and if and only if for every .
Proof. Each counted value is in , since , so their mean is too. If on , then for all and every counted value is 1. Conversely, if the mean is 1, every counted value is 1. If some had , then , so and , and the value of class would be below 1.
Corollary 2 (relabeling). If a permutation of the classes is applied to both and , the mIoU does not change.
Proof. The new sets are and , so the new values are the old ones in another order. The mean of a set of numbers does not depend on the order.
Corollary 3 (Dice). For a class with , the Dice score equals , where is the class IoU. So is an increasing function of .
Proof. Write and . Then , and . The function has derivative .
The mean of the and the mean of the 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 and have the mean , while the summed matrix gives .
Proposition 5 (pixel accuracy and mIoU). Pixel accuracy, the trace of over the sum of , can be close to 1 while the mIoU is close to .
Proof. Let have pixels, all of class 0 but one of class 1, and let be 0 everywhere. The accuracy is . Class 0 has IoU , class 1 has IoU , so the mIoU is .
Cost. Lines L1 to L4 take time for pixels in total. Lines L5 to L9 take time as written, or with the row and column sums kept during the count. The extra space is 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.
# 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
- 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)
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H2 full proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 7XWT5K Edit this page History Report an error Markdown