Compare two clusterings with the adjusted Rand index

Why it matters ARI is the standard way to compare a clustering with ground truth labels or with another run, for example to check k-means stability.

The adjusted Rand index (ARI) measures how much two clusterings agree on which pairs of points belong together, corrected so random labelings score about 0.

Write adjusted_rand_index(a, b). a and b are equal-length label lists (label names do not matter). Build the contingency table n_ij of counts for each pair of labels. With comb2(x) = x (x - 1) / 2, index = sum_ij comb2(n_ij), sa = sum_i comb2(row sums), sb = sum_j comb2(column sums), expected = sa * sb / comb2(n) and max_index = (sa + sb) / 2. Return (index - expected) / (max_index - expected) as a float, or 1.0 when max_index equals expected.

Signaturedef adjusted_rand_index(a, b)

Example

a [0, 0, 1, 1, 2, 2], b [1, 1, 0, 0, 0, 2] gives 0.444444 (rounded).

Understand the idea

Two clusterings can use totally different label names and still agree. So ARI looks at pairs of points: for each pair, are they together in clustering A? In clustering B? Agreement on many pairs means similar clusterings.

Raw pair agreement is inflated by chance, especially with many small clusters, so ARI subtracts what random labelings with the same cluster sizes would score and rescales so a perfect match is 1.

Worked example: a = 0, 0, 1, 1 and b = 0, 1, 0, 1. Every cell of the contingency table is 1, so no pair is together in both: index = 0. Each clustering has 2 pairs together, so sa = sb = 2, there are 6 pairs in total, expected = 2 * 2 / 6 = 0.667 and max_index = 2. ARI = (0 - 0.667) / (2 - 0.667) = -0.5, worse than random.

Rule: ARI = (index - expected) / (max_index - expected), where index = sum comb2(n_ij), expected = sa sb / comb2(n), max_index = (sa + sb) / 2.

ARI is the usual score for clustering benchmarks and for checking whether repeated runs give stable clusters.

Shapes and data flow

labels (n,) -> contingency (|A|, |B|)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: exampleadjusted_rand_index([0, 0, 1, 1, 2, 2], [1, 1, 0, 0, 0, 2])
  • Sample 2: renamed labelsadjusted_rand_index(['x', 'x', 'y', 'y'], [5, 5, 3, 3])