Skip to content

Comparing partitions: ARI, AMI and variation of information

Two clusterings of the same rows, or a clustering against known labels, compared without caring about label names. Chance-corrected scores, an information distance, and the choices (noise points, subsets) that change all three.

Advanced ~14 min10 steps

What runs in CodeSplash

You will be able to

  • Compute and read the adjusted Rand index and adjusted mutual information
  • Tell adjusted from normalized mutual information
  • Use variation of information and its two conditional entropies to tell splits from merges
  • Report noise handling and the row subset with every score

Read first

01

Labels are arbitrary

Read

Cluster "1" in one run and cluster "3" in another can be the same group. Agreement measures for partitions ignore the names: they look at the contingency table nijn_{ij} of how many rows fall in group ii of one partition and group jj of the other.

Use them to compare two clusterings of the same rows, a clustering with reference labels, or runs with different seeds. Both partitions must cover the same observations, and the reference labels must be the target you care about, not assumed to be the only legitimate structure.

02

Adjusted Rand index

Read

The adjusted Rand indexAdjusted Rand indexAgreement between two clusterings corrected for chance; 0 is random, 1 is identical. counts pairs of rows placed together in both partitions, minus what random partitions with the same group sizes would give:

ARI=∑ij(nij2)−AB/(n2)12(A+B)−AB/(n2),A=∑i(ai2),  B=∑j(bj2).\mathrm{ARI} = \frac{\sum_{ij}\binom{n_{ij}}{2} - AB/\binom{n}{2}}{\tfrac12(A + B) - AB/\binom{n}{2}}, \quad A = \sum_i \binom{a_i}{2},\; B = \sum_j \binom{b_j}{2}.

1 is identical, 0 is chance level, and it can go below 0. It is not a p-value. In the reference's six-row example it is 0.324.

Reference · EVA010 · Runs in CodeSplashAdjusted Rand indexMeasures pairwise partition agreement corrected for chance under the fixed-marginal random-partition model.
03

Adjusted mutual information

Read

Adjusted mutual informationAdjusted mutual informationShared information of two partitions corrected for chance: 0 = chance, 1 = identical; fair across group counts. measures shared information beyond chance:

AMI=I(U;V)−E I(U;V)M(H(U),H(V))−E I(U;V).\mathrm{AMI} = \frac{I(U;V) - \mathbb E\,I(U;V)}{M(H(U), H(V)) - \mathbb E\,I(U;V)} .

MM is a mean of the two entropies (arithmetic, geometric, min or max); say which. In the reference's example, with the arithmetic mean, it is 0.355.

Normalized mutual information drops the expected term. It rewards partitions with many small groups, which share some information with anything by chance. Prefer the adjusted version when cluster counts differ.

Reference · EVA011 · Runs in CodeSplashAdjusted mutual informationCompares the information shared by two partitions after correcting for expected chance agreement.
04

Variation of information

Read

Variation of informationVariation of informationH(A|B) + H(B|A): information lost going either way between two partitions; a true distance, 0 = identical. is a true distance between partitions, in nats or bits:

VI(U,V)=H(U∣V)+H(V∣U).\mathrm{VI}(U, V) = H(U \mid V) + H(V \mid U).

In the reference's example it is 0.693 nats, exactly ln⁡2\ln 2. Its two parts tell a story: H(V∣U)H(V \mid U) large means VV splits groups of UU; H(U∣V)H(U \mid V) large means VV merges them. VI isn't chance-corrected, and its maximum grows with the number of rows, so don't compare values across very different sample sizes.

Reference · EVA012 · Runs in CodeSplashVariation of informationMeasures information lost or gained when one partition is replaced by another.
05

Splits and merges

Explore
Compare two partitions (ARI, AMI, VI, purity)Recorded · Python and R agreeRecorded 2026-11-21 · 22 values compared
R

hc (4 groups) and km (3 groups) are in substantial agreement: ARI 0.61, AMI 0.70, VI 0.73 nats.

Adjusted Rand index
0.6106
Adjusted mutual information
0.6984
Variation of information (nats)
0.7269

Plots

Rows by hc and kmWhat do the values of a square or rectangular result matrix look like at a glance?

Each cell counts the rows in that pair of groups; a perfect match puts every row in one cell per row and column.

View data
kmCounthcRows
148h148
20h10
30h10
11h21
20h20
329h229
10h30
220h320
324h324
10h40
226h426
30h40
How the groups of hc map onto kmHow do the rows of one grouping spread over another, for example known classes over clusters?
View data
Rowshckm
48h11
1h21
29h23
20h32
24h33
26h42

Agreement indices

IndexValueReading
Adjusted Rand index0.61060 = chance, 1 = identical
Adjusted mutual information0.69840 = chance, 1 = identical
Normalized mutual information0.70350 to 1; not chance-corrected
Variation of information (nats)0.72690 = identical; a distance
Normalized variation of information0.45730 = identical, 1 = unrelated
Fowlkes–Mallows0.72900 to 1
Rand index0.83700 to 1; not chance-corrected
Pair Jaccard0.56730 to 1
Homogeneity0.63661 = each judged group holds one reference group
Completeness0.78631 = each reference group sits in one judged group
V-measure0.7035harmonic mean of the two above
Purity0.6959share of rows in the majority reference group of their judged group
Inverse purity0.8581the same with the roles swapped

Rows by hc (rows) and km (columns)

hc123Total
h1480048
h2102930
h30202444
h4026026
  • 2 of 150 rows were left out because a partition was missing.
The exact R script · R R version 4.5.1 (2025-06-13)
# Compare two partitions (ARI, AMI, VI, purity)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.compare_partitions 1.0.0 · spec a0de102c69a80186
# Dataset: clu4_partitions (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data
A <- "hc"
B <- "km"
NOISE_LABEL <- trimws("")
NOISE <- "cluster"
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/clu4_partitions.parquet", col_select = unique(c(A, B))))
n_input <- nrow(df)
cs_check_finite_columns(df, unique(c(A, B)))  # ±Inf stops with CS_E_NOT_FINITE in both engines
la <- cs_ml_label_text(df[[A]])
lb <- cs_ml_label_text(df[[B]])
ok <- !is.na(la) & !is.na(lb)
warnings <- list()
if (sum(ok) < n_input) warnings <- c(warnings, sprintf("%d of %d rows were left out because a partition was missing.", n_input - sum(ok), n_input))
cs_check_rows(sum(ok), 2, "Comparing two partitions")
nz <- cs_ml_partition_noise(la[ok], lb[ok], NOISE_LABEL, NOISE)
a <- nz$a
b <- nz$b
if (nz$n_noise > 0) {
  tail_msg <- switch(NOISE, cluster = "they count as one more group.", drop = "they were left out.", singletons = "each counts as a group of its own.")
  warnings <- c(warnings, sprintf("%d row(s) carry the noise label '%s'; %s", nz$n_noise, NOISE_LABEL, tail_msg))
}
cs_check_rows(length(a), 2, "Comparing two partitions")

# %% Agreement indices
r <- cs_ml_compare_partitions(a, b)
keys <- c("n", "k_a", "k_b", "ari", "ami", "nmi", "vi", "vi_bits", "nvi", "mi", "h_a", "h_b", "rand", "fmi", "jaccard",
          "homogeneity", "completeness", "v_measure", "purity", "inverse_purity")
values <- r[keys]
values$n_noise <- nz$n_noise
values$n_dropped <- nz$n_dropped
T <- r$table
la_lv <- r$levels_a
lb_lv <- r$levels_b
index_rows <- list(
  c("ari", "Adjusted Rand index", "0 = chance, 1 = identical"),
  c("ami", "Adjusted mutual information", "0 = chance, 1 = identical"),
  c("nmi", "Normalized mutual information", "0 to 1; not chance-corrected"),
  c("vi", "Variation of information (nats)", "0 = identical; a distance"),
  c("nvi", "Normalized variation of information", "0 = identical, 1 = unrelated"),
  c("fmi", "Fowlkes–Mallows", "0 to 1"),
  c("rand", "Rand index", "0 to 1; not chance-corrected"),
  c("jaccard", "Pair Jaccard", "0 to 1"),
  c("homogeneity", "Homogeneity", "1 = each judged group holds one reference group"),
  c("completeness", "Completeness", "1 = each reference group sits in one judged group"),
  c("v_measure", "V-measure", "harmonic mean of the two above"),
  c("purity", "Purity", "share of rows in the majority reference group of their judged group"),
  c("inverse_purity", "Inverse purity", "the same with the roles swapped")
)
cont_cols <- c(list(list(key = "level", label = A, type = "string")),
               lapply(seq_along(lb_lv), function(j) list(key = sprintf("b%d", j - 1L), label = lb_lv[j], type = "integer")),
               list(list(key = "total", label = "Total", type = "integer")))
cont_rows <- lapply(seq_along(la_lv), function(i) {
  row <- list(level = la_lv[i])
  for (j in seq_along(lb_lv)) row[[sprintf("b%d", j - 1L)]] <- as.integer(T[i, j])
  row$total <- as.integer(sum(T[i, ]))
  row
})
tables <- list(
  list(key = "indices", title = "Agreement indices",
       columns = list(list(key = "index", label = "Index", type = "string"), list(key = "value", label = "Value", type = "number"),
                      list(key = "reading", label = "Reading", type = "string")),
       rows = lapply(index_rows, function(x) list(index = x[2], value = values[[x[1]]], reading = x[3]))),
  list(key = "contingency", title = sprintf("Rows by %s (rows) and %s (columns)", A, B), columns = cont_cols, rows = cont_rows)
)

# %% Charts
charts <- list()
ci <- rep(seq_along(la_lv), each = length(lb_lv))
cj <- rep(seq_along(lb_lv), times = length(la_lv))
if (length(la_lv) <= 60 && length(lb_lv) <= 60) {
  charts[[length(charts) + 1L]] <- cs_chart("contingency", "matrix-heatmap", sprintf("Rows by %s and %s", A, B), list(
    row = cs_col(A, la_lv[ci], "categorical", levels = la_lv),
    col = cs_col(B, lb_lv[cj], "categorical", levels = lb_lv),
    value = cs_col("Rows", T[cbind(ci, cj)], "numeric"),
    label = cs_col("Count", as.character(as.integer(T[cbind(ci, cj)])), "categorical")
  ), note = "Each cell counts the rows in that pair of groups; a perfect match puts every row in one cell per row and column.")
}
if (length(la_lv) <= 30 && length(lb_lv) <= 30) {
  keep <- T[cbind(ci, cj)] > 0
  charts[[length(charts) + 1L]] <- cs_chart("flow", "partition-flow", sprintf("How the groups of %s map onto %s", A, B), list(
    from = cs_col(A, la_lv[ci[keep]], "categorical", levels = la_lv),
    to = cs_col(B, lb_lv[cj[keep]], "categorical", levels = lb_lv),
    count = cs_col("Rows", T[cbind(ci, cj)][keep], "numeric")
  ))
}

# %% Result
ari <- values$ari
verdict <- if (ari >= 0.9) "almost identical" else if (ari >= 0.5) "in substantial agreement" else if (ari >= 0.2) "in partial agreement" else "close to chance agreement"
cs_publish(list(
  title = "Compare two partitions (ARI, AMI, VI, purity)",
  engine = cs_engine_info("codesplashr", "nanoparquet"),
  n = values$n,
  summary = sprintf("%s (%d groups) and %s (%d groups) are %s: ARI %.2f, AMI %.2f, VI %.2f nats.", A, values$k_a, B, values$k_b, verdict, ari, values$ami, values$vi),
  statistics = list(list(key = "ari", label = "Adjusted Rand index", value = ari),
                    list(key = "ami", label = "Adjusted mutual information", value = values$ami),
                    list(key = "vi", label = "Variation of information (nats)", value = values$vi)),
  tables = tables,
  values = values,
  charts = charts,
  warnings = warnings
))
Python

hc (4 groups) and km (3 groups) are in substantial agreement: ARI 0.61, AMI 0.70, VI 0.73 nats.

Adjusted Rand index
0.6106
Adjusted mutual information
0.6984
Variation of information (nats)
0.7269

To keep this page light, the plots are shown once, under the R tab.

Agreement indices

IndexValueReading
Adjusted Rand index0.61060 = chance, 1 = identical
Adjusted mutual information0.69840 = chance, 1 = identical
Normalized mutual information0.70350 to 1; not chance-corrected
Variation of information (nats)0.72690 = identical; a distance
Normalized variation of information0.45730 = identical, 1 = unrelated
Fowlkes–Mallows0.72900 to 1
Rand index0.83700 to 1; not chance-corrected
Pair Jaccard0.56730 to 1
Homogeneity0.63661 = each judged group holds one reference group
Completeness0.78631 = each reference group sits in one judged group
V-measure0.7035harmonic mean of the two above
Purity0.6959share of rows in the majority reference group of their judged group
Inverse purity0.8581the same with the roles swapped

Rows by hc (rows) and km (columns)

hc123Total
h1480048
h2102930
h30202444
h4026026
  • 2 of 150 rows were left out because a partition was missing.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Compare two partitions (ARI, AMI, VI, purity)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.compare_partitions 1.0.0 · spec a0de102c69a80186
# Dataset: clu4_partitions (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd

import codesplash as cs
from codesplash.ml import cluster_compare as cc

# %% Data
A = "hc"
B = "km"
NOISE_LABEL = "".strip()
NOISE = "cluster"
df = pd.read_parquet("tests/parity/fixtures/clu4_partitions.parquet", columns=list(dict.fromkeys([A, B])))
n_input = len(df)
cs.check_finite_columns(df, [A, B])  # ±Inf stops with CS_E_NOT_FINITE in both engines
la = cc.label_text(df[A].tolist())
lb = cc.label_text(df[B].tolist())
ok = np.array([x is not None and y is not None for x, y in zip(la, lb)])
warnings = []
if int(ok.sum()) < n_input:
    warnings.append(f"{n_input - int(ok.sum())} of {n_input} rows were left out because a partition was missing.")
cs.check_rows(int(ok.sum()), 2, "Comparing two partitions")
a, b, n_noise, n_dropped = cc.apply_noise(la[ok], lb[ok], NOISE_LABEL, NOISE)
if n_noise:
    warnings.append(
        f"{n_noise} row(s) carry the noise label {NOISE_LABEL!r}; "
        + {"cluster": "they count as one more group.", "drop": "they were left out.", "singletons": "each counts as a group of its own."}[NOISE]
    )
cs.check_rows(len(a), 2, "Comparing two partitions")

# %% Agreement indices
r = cc.compare_partitions(a, b)
keys = ["n", "k_a", "k_b", "ari", "ami", "nmi", "vi", "vi_bits", "nvi", "mi", "h_a", "h_b", "rand", "fmi", "jaccard",
        "homogeneity", "completeness", "v_measure", "purity", "inverse_purity"]
values = {k: r[k] for k in keys}
values["n_noise"] = n_noise
values["n_dropped"] = n_dropped
T = r["table"]
la_lv, lb_lv = r["levels_a"], r["levels_b"]
index_rows = [
    ("ari", "Adjusted Rand index", "0 = chance, 1 = identical"),
    ("ami", "Adjusted mutual information", "0 = chance, 1 = identical"),
    ("nmi", "Normalized mutual information", "0 to 1; not chance-corrected"),
    ("vi", "Variation of information (nats)", "0 = identical; a distance"),
    ("nvi", "Normalized variation of information", "0 = identical, 1 = unrelated"),
    ("fmi", "Fowlkes–Mallows", "0 to 1"),
    ("rand", "Rand index", "0 to 1; not chance-corrected"),
    ("jaccard", "Pair Jaccard", "0 to 1"),
    ("homogeneity", "Homogeneity", "1 = each judged group holds one reference group"),
    ("completeness", "Completeness", "1 = each reference group sits in one judged group"),
    ("v_measure", "V-measure", "harmonic mean of the two above"),
    ("purity", "Purity", "share of rows in the majority reference group of their judged group"),
    ("inverse_purity", "Inverse purity", "the same with the roles swapped"),
]
tables = [
    {
        "key": "indices",
        "title": "Agreement indices",
        "columns": [{"key": "index", "label": "Index", "type": "string"}, {"key": "value", "label": "Value", "type": "number"},
                    {"key": "reading", "label": "Reading", "type": "string"}],
        "rows": [{"index": lab, "value": values[k], "reading": note} for k, lab, note in index_rows],
    },
    {
        "key": "contingency",
        "title": f"Rows by {A} (rows) and {B} (columns)",
        "columns": [{"key": "level", "label": A, "type": "string"}]
        + [{"key": f"b{j}", "label": str(lv), "type": "integer"} for j, lv in enumerate(lb_lv)]
        + [{"key": "total", "label": "Total", "type": "integer"}],
        "rows": [
            {"level": str(lv), **{f"b{j}": int(T[i, j]) for j in range(len(lb_lv))}, "total": int(T[i].sum())}
            for i, lv in enumerate(la_lv)
        ],
    },
]

# %% Charts
charts = []
cells = [(i, j) for i in range(len(la_lv)) for j in range(len(lb_lv))]
if len(la_lv) <= 60 and len(lb_lv) <= 60:
    charts.append(cs.chart(
        "contingency", "matrix-heatmap", f"Rows by {A} and {B}",
        {
            "row": cs.col(A, [str(la_lv[i]) for i, _ in cells], "categorical", levels=[str(x) for x in la_lv]),
            "col": cs.col(B, [str(lb_lv[j]) for _, j in cells], "categorical", levels=[str(x) for x in lb_lv]),
            "value": cs.col("Rows", [float(T[i, j]) for i, j in cells], "numeric"),
            "label": cs.col("Count", [str(int(T[i, j])) for i, j in cells], "categorical"),
        },
        note="Each cell counts the rows in that pair of groups; a perfect match puts every row in one cell per row and column.",
    ))
if len(la_lv) <= 30 and len(lb_lv) <= 30:
    nz = [(i, j) for i, j in cells if T[i, j] > 0]
    charts.append(cs.chart(
        "flow", "partition-flow", f"How the groups of {A} map onto {B}",
        {
            "from": cs.col(A, [str(la_lv[i]) for i, _ in nz], "categorical", levels=[str(x) for x in la_lv]),
            "to": cs.col(B, [str(lb_lv[j]) for _, j in nz], "categorical", levels=[str(x) for x in lb_lv]),
            "count": cs.col("Rows", [float(T[i, j]) for i, j in nz], "numeric"),
        },
    ))

# %% Result
ari = values["ari"]
verdict = "almost identical" if ari >= 0.9 else ("in substantial agreement" if ari >= 0.5 else ("in partial agreement" if ari >= 0.2 else "close to chance agreement"))
cs.publish({
    "title": "Compare two partitions (ARI, AMI, VI, purity)",
    "engine": cs.engine_info("numpy", "scipy", "pandas"),
    "n": values["n"],
    "summary": f"{A} ({values['k_a']} groups) and {B} ({values['k_b']} groups) are {verdict}: ARI {ari:.2f}, AMI {values['ami']:.2f}, VI {values['vi']:.2f} nats.",
    "statistics": [
        {"key": "ari", "label": "Adjusted Rand index", "value": ari},
        {"key": "ami", "label": "Adjusted mutual information", "value": values["ami"]},
        {"key": "vi", "label": "Variation of information (nats)", "value": values["vi"]},
    ],
    "tables": tables,
    "values": values,
    "charts": charts,
    "warnings": warnings,
})

A four-group hierarchical clustering against three k-means groups: ARI 0.61, AMI 0.70, VI 0.73 nats.

Completeness is 0.79 and homogeneity 0.64: each hierarchical group sits mostly inside one k-means group, but one k-means group is split in two. The disagreement is a split, not a scramble.

06

Noise points change the score

Predict

Predict first

DBSCAN left some iris flowers as noise. Does it matter whether noise counts as its own group or is left out before comparing with the species?

It hardly mattersIt changes the agreement a lot
Reveal
Compare two partitions (ARI, AMI, VI, purity)Recorded · Python and R agreeRecorded 2026-11-21 · 22 values compared
R

species (3 groups) and db (3 groups) are in partial agreement: ARI 0.44, AMI 0.51, VI 1.05 nats.

Adjusted Rand index
0.4421
Adjusted mutual information
0.5052
Variation of information (nats)
1.051

Plots

Rows by species and dbWhat do the values of a square or rectangular result matrix look like at a glance?

Each cell counts the rows in that pair of groups; a perfect match puts every row in one cell per row and column.

View data
dbCountspeciesRows
-15setosa5
045setosa45
10setosa0
-111versicolor11
00versicolor0
139versicolor39
-118virginica18
00virginica0
132virginica32
How the groups of species map onto dbHow do the rows of one grouping spread over another, for example known classes over clusters?
View data
Rowsspeciesdb
5setosa-1
45setosa0
11versicolor-1
39versicolor1
18virginica-1
32virginica1

Agreement indices

IndexValueReading
Adjusted Rand index0.44210 = chance, 1 = identical
Adjusted mutual information0.50520 = chance, 1 = identical
Normalized mutual information0.51140 to 1; not chance-corrected
Variation of information (nats)1.0510 = identical; a distance
Normalized variation of information0.65640 = identical, 1 = unrelated
Fowlkes–Mallows0.63490 to 1
Rand index0.74760 to 1; not chance-corrected
Pair Jaccard0.46430 to 1
Homogeneity0.50051 = each judged group holds one reference group
Completeness0.52281 = each reference group sits in one judged group
V-measure0.5114harmonic mean of the two above
Purity0.6800share of rows in the majority reference group of their judged group
Inverse purity0.7733the same with the roles swapped

Rows by species (rows) and db (columns)

species-101Total
setosa545050
versicolor1103950
virginica1803250
  • 34 row(s) carry the noise label '-1'; they count as one more group.
The exact R script · R R version 4.5.1 (2025-06-13)
# Compare two partitions (ARI, AMI, VI, purity)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.compare_partitions 1.0.0 · spec b207cc2d25debca7
# Dataset: clu4_partitions (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data
A <- "species"
B <- "db"
NOISE_LABEL <- trimws("-1")
NOISE <- "cluster"
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/clu4_partitions.parquet", col_select = unique(c(A, B))))
n_input <- nrow(df)
cs_check_finite_columns(df, unique(c(A, B)))  # ±Inf stops with CS_E_NOT_FINITE in both engines
la <- cs_ml_label_text(df[[A]])
lb <- cs_ml_label_text(df[[B]])
ok <- !is.na(la) & !is.na(lb)
warnings <- list()
if (sum(ok) < n_input) warnings <- c(warnings, sprintf("%d of %d rows were left out because a partition was missing.", n_input - sum(ok), n_input))
cs_check_rows(sum(ok), 2, "Comparing two partitions")
nz <- cs_ml_partition_noise(la[ok], lb[ok], NOISE_LABEL, NOISE)
a <- nz$a
b <- nz$b
if (nz$n_noise > 0) {
  tail_msg <- switch(NOISE, cluster = "they count as one more group.", drop = "they were left out.", singletons = "each counts as a group of its own.")
  warnings <- c(warnings, sprintf("%d row(s) carry the noise label '%s'; %s", nz$n_noise, NOISE_LABEL, tail_msg))
}
cs_check_rows(length(a), 2, "Comparing two partitions")

# %% Agreement indices
r <- cs_ml_compare_partitions(a, b)
keys <- c("n", "k_a", "k_b", "ari", "ami", "nmi", "vi", "vi_bits", "nvi", "mi", "h_a", "h_b", "rand", "fmi", "jaccard",
          "homogeneity", "completeness", "v_measure", "purity", "inverse_purity")
values <- r[keys]
values$n_noise <- nz$n_noise
values$n_dropped <- nz$n_dropped
T <- r$table
la_lv <- r$levels_a
lb_lv <- r$levels_b
index_rows <- list(
  c("ari", "Adjusted Rand index", "0 = chance, 1 = identical"),
  c("ami", "Adjusted mutual information", "0 = chance, 1 = identical"),
  c("nmi", "Normalized mutual information", "0 to 1; not chance-corrected"),
  c("vi", "Variation of information (nats)", "0 = identical; a distance"),
  c("nvi", "Normalized variation of information", "0 = identical, 1 = unrelated"),
  c("fmi", "Fowlkes–Mallows", "0 to 1"),
  c("rand", "Rand index", "0 to 1; not chance-corrected"),
  c("jaccard", "Pair Jaccard", "0 to 1"),
  c("homogeneity", "Homogeneity", "1 = each judged group holds one reference group"),
  c("completeness", "Completeness", "1 = each reference group sits in one judged group"),
  c("v_measure", "V-measure", "harmonic mean of the two above"),
  c("purity", "Purity", "share of rows in the majority reference group of their judged group"),
  c("inverse_purity", "Inverse purity", "the same with the roles swapped")
)
cont_cols <- c(list(list(key = "level", label = A, type = "string")),
               lapply(seq_along(lb_lv), function(j) list(key = sprintf("b%d", j - 1L), label = lb_lv[j], type = "integer")),
               list(list(key = "total", label = "Total", type = "integer")))
cont_rows <- lapply(seq_along(la_lv), function(i) {
  row <- list(level = la_lv[i])
  for (j in seq_along(lb_lv)) row[[sprintf("b%d", j - 1L)]] <- as.integer(T[i, j])
  row$total <- as.integer(sum(T[i, ]))
  row
})
tables <- list(
  list(key = "indices", title = "Agreement indices",
       columns = list(list(key = "index", label = "Index", type = "string"), list(key = "value", label = "Value", type = "number"),
                      list(key = "reading", label = "Reading", type = "string")),
       rows = lapply(index_rows, function(x) list(index = x[2], value = values[[x[1]]], reading = x[3]))),
  list(key = "contingency", title = sprintf("Rows by %s (rows) and %s (columns)", A, B), columns = cont_cols, rows = cont_rows)
)

# %% Charts
charts <- list()
ci <- rep(seq_along(la_lv), each = length(lb_lv))
cj <- rep(seq_along(lb_lv), times = length(la_lv))
if (length(la_lv) <= 60 && length(lb_lv) <= 60) {
  charts[[length(charts) + 1L]] <- cs_chart("contingency", "matrix-heatmap", sprintf("Rows by %s and %s", A, B), list(
    row = cs_col(A, la_lv[ci], "categorical", levels = la_lv),
    col = cs_col(B, lb_lv[cj], "categorical", levels = lb_lv),
    value = cs_col("Rows", T[cbind(ci, cj)], "numeric"),
    label = cs_col("Count", as.character(as.integer(T[cbind(ci, cj)])), "categorical")
  ), note = "Each cell counts the rows in that pair of groups; a perfect match puts every row in one cell per row and column.")
}
if (length(la_lv) <= 30 && length(lb_lv) <= 30) {
  keep <- T[cbind(ci, cj)] > 0
  charts[[length(charts) + 1L]] <- cs_chart("flow", "partition-flow", sprintf("How the groups of %s map onto %s", A, B), list(
    from = cs_col(A, la_lv[ci[keep]], "categorical", levels = la_lv),
    to = cs_col(B, lb_lv[cj[keep]], "categorical", levels = lb_lv),
    count = cs_col("Rows", T[cbind(ci, cj)][keep], "numeric")
  ))
}

# %% Result
ari <- values$ari
verdict <- if (ari >= 0.9) "almost identical" else if (ari >= 0.5) "in substantial agreement" else if (ari >= 0.2) "in partial agreement" else "close to chance agreement"
cs_publish(list(
  title = "Compare two partitions (ARI, AMI, VI, purity)",
  engine = cs_engine_info("codesplashr", "nanoparquet"),
  n = values$n,
  summary = sprintf("%s (%d groups) and %s (%d groups) are %s: ARI %.2f, AMI %.2f, VI %.2f nats.", A, values$k_a, B, values$k_b, verdict, ari, values$ami, values$vi),
  statistics = list(list(key = "ari", label = "Adjusted Rand index", value = ari),
                    list(key = "ami", label = "Adjusted mutual information", value = values$ami),
                    list(key = "vi", label = "Variation of information (nats)", value = values$vi)),
  tables = tables,
  values = values,
  charts = charts,
  warnings = warnings
))
Python

species (3 groups) and db (3 groups) are in partial agreement: ARI 0.44, AMI 0.51, VI 1.05 nats.

Adjusted Rand index
0.4421
Adjusted mutual information
0.5052
Variation of information (nats)
1.051

To keep this page light, the plots are shown once, under the R tab.

Agreement indices

IndexValueReading
Adjusted Rand index0.44210 = chance, 1 = identical
Adjusted mutual information0.50520 = chance, 1 = identical
Normalized mutual information0.51140 to 1; not chance-corrected
Variation of information (nats)1.0510 = identical; a distance
Normalized variation of information0.65640 = identical, 1 = unrelated
Fowlkes–Mallows0.63490 to 1
Rand index0.74760 to 1; not chance-corrected
Pair Jaccard0.46430 to 1
Homogeneity0.50051 = each judged group holds one reference group
Completeness0.52281 = each reference group sits in one judged group
V-measure0.5114harmonic mean of the two above
Purity0.6800share of rows in the majority reference group of their judged group
Inverse purity0.7733the same with the roles swapped

Rows by species (rows) and db (columns)

species-101Total
setosa545050
versicolor1103950
virginica1803250
  • 34 row(s) carry the noise label '-1'; they count as one more group.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Compare two partitions (ARI, AMI, VI, purity)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.compare_partitions 1.0.0 · spec b207cc2d25debca7
# Dataset: clu4_partitions (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd

import codesplash as cs
from codesplash.ml import cluster_compare as cc

# %% Data
A = "species"
B = "db"
NOISE_LABEL = "-1".strip()
NOISE = "cluster"
df = pd.read_parquet("tests/parity/fixtures/clu4_partitions.parquet", columns=list(dict.fromkeys([A, B])))
n_input = len(df)
cs.check_finite_columns(df, [A, B])  # ±Inf stops with CS_E_NOT_FINITE in both engines
la = cc.label_text(df[A].tolist())
lb = cc.label_text(df[B].tolist())
ok = np.array([x is not None and y is not None for x, y in zip(la, lb)])
warnings = []
if int(ok.sum()) < n_input:
    warnings.append(f"{n_input - int(ok.sum())} of {n_input} rows were left out because a partition was missing.")
cs.check_rows(int(ok.sum()), 2, "Comparing two partitions")
a, b, n_noise, n_dropped = cc.apply_noise(la[ok], lb[ok], NOISE_LABEL, NOISE)
if n_noise:
    warnings.append(
        f"{n_noise} row(s) carry the noise label {NOISE_LABEL!r}; "
        + {"cluster": "they count as one more group.", "drop": "they were left out.", "singletons": "each counts as a group of its own."}[NOISE]
    )
cs.check_rows(len(a), 2, "Comparing two partitions")

# %% Agreement indices
r = cc.compare_partitions(a, b)
keys = ["n", "k_a", "k_b", "ari", "ami", "nmi", "vi", "vi_bits", "nvi", "mi", "h_a", "h_b", "rand", "fmi", "jaccard",
        "homogeneity", "completeness", "v_measure", "purity", "inverse_purity"]
values = {k: r[k] for k in keys}
values["n_noise"] = n_noise
values["n_dropped"] = n_dropped
T = r["table"]
la_lv, lb_lv = r["levels_a"], r["levels_b"]
index_rows = [
    ("ari", "Adjusted Rand index", "0 = chance, 1 = identical"),
    ("ami", "Adjusted mutual information", "0 = chance, 1 = identical"),
    ("nmi", "Normalized mutual information", "0 to 1; not chance-corrected"),
    ("vi", "Variation of information (nats)", "0 = identical; a distance"),
    ("nvi", "Normalized variation of information", "0 = identical, 1 = unrelated"),
    ("fmi", "Fowlkes–Mallows", "0 to 1"),
    ("rand", "Rand index", "0 to 1; not chance-corrected"),
    ("jaccard", "Pair Jaccard", "0 to 1"),
    ("homogeneity", "Homogeneity", "1 = each judged group holds one reference group"),
    ("completeness", "Completeness", "1 = each reference group sits in one judged group"),
    ("v_measure", "V-measure", "harmonic mean of the two above"),
    ("purity", "Purity", "share of rows in the majority reference group of their judged group"),
    ("inverse_purity", "Inverse purity", "the same with the roles swapped"),
]
tables = [
    {
        "key": "indices",
        "title": "Agreement indices",
        "columns": [{"key": "index", "label": "Index", "type": "string"}, {"key": "value", "label": "Value", "type": "number"},
                    {"key": "reading", "label": "Reading", "type": "string"}],
        "rows": [{"index": lab, "value": values[k], "reading": note} for k, lab, note in index_rows],
    },
    {
        "key": "contingency",
        "title": f"Rows by {A} (rows) and {B} (columns)",
        "columns": [{"key": "level", "label": A, "type": "string"}]
        + [{"key": f"b{j}", "label": str(lv), "type": "integer"} for j, lv in enumerate(lb_lv)]
        + [{"key": "total", "label": "Total", "type": "integer"}],
        "rows": [
            {"level": str(lv), **{f"b{j}": int(T[i, j]) for j in range(len(lb_lv))}, "total": int(T[i].sum())}
            for i, lv in enumerate(la_lv)
        ],
    },
]

# %% Charts
charts = []
cells = [(i, j) for i in range(len(la_lv)) for j in range(len(lb_lv))]
if len(la_lv) <= 60 and len(lb_lv) <= 60:
    charts.append(cs.chart(
        "contingency", "matrix-heatmap", f"Rows by {A} and {B}",
        {
            "row": cs.col(A, [str(la_lv[i]) for i, _ in cells], "categorical", levels=[str(x) for x in la_lv]),
            "col": cs.col(B, [str(lb_lv[j]) for _, j in cells], "categorical", levels=[str(x) for x in lb_lv]),
            "value": cs.col("Rows", [float(T[i, j]) for i, j in cells], "numeric"),
            "label": cs.col("Count", [str(int(T[i, j])) for i, j in cells], "categorical"),
        },
        note="Each cell counts the rows in that pair of groups; a perfect match puts every row in one cell per row and column.",
    ))
if len(la_lv) <= 30 and len(lb_lv) <= 30:
    nz = [(i, j) for i, j in cells if T[i, j] > 0]
    charts.append(cs.chart(
        "flow", "partition-flow", f"How the groups of {A} map onto {B}",
        {
            "from": cs.col(A, [str(la_lv[i]) for i, _ in nz], "categorical", levels=[str(x) for x in la_lv]),
            "to": cs.col(B, [str(lb_lv[j]) for _, j in nz], "categorical", levels=[str(x) for x in lb_lv]),
            "count": cs.col("Rows", [float(T[i, j]) for i, j in nz], "numeric"),
        },
    ))

# %% Result
ari = values["ari"]
verdict = "almost identical" if ari >= 0.9 else ("in substantial agreement" if ari >= 0.5 else ("in partial agreement" if ari >= 0.2 else "close to chance agreement"))
cs.publish({
    "title": "Compare two partitions (ARI, AMI, VI, purity)",
    "engine": cs.engine_info("numpy", "scipy", "pandas"),
    "n": values["n"],
    "summary": f"{A} ({values['k_a']} groups) and {B} ({values['k_b']} groups) are {verdict}: ARI {ari:.2f}, AMI {values['ami']:.2f}, VI {values['vi']:.2f} nats.",
    "statistics": [
        {"key": "ari", "label": "Adjusted Rand index", "value": ari},
        {"key": "ami", "label": "Adjusted mutual information", "value": values["ami"]},
        {"key": "vi", "label": "Variation of information (nats)", "value": values["vi"]},
    ],
    "tables": tables,
    "values": values,
    "charts": charts,
    "warnings": warnings,
})

A lot. With noise as a group, ARI is 0.44 on 150 rows. Dropping the 34 noise points gives 0.63 on 116 rows. Report the noise rule and the rows used.

07

Agreement isn't usefulness

Read
Compare two partitions (ARI, AMI, VI, purity)Recorded · Python and R agreeRecorded 2026-11-21 · 22 values compared
R

species (3 groups) and km (3 groups) are in substantial agreement: ARI 0.63, AMI 0.66, VI 0.74 nats.

Adjusted Rand index
0.6254
Adjusted mutual information
0.6599
Variation of information (nats)
0.7373

Plots

Rows by species and kmWhat do the values of a square or rectangular result matrix look like at a glance?

Each cell counts the rows in that pair of groups; a perfect match puts every row in one cell per row and column.

View data
kmCountspeciesRows
149setosa49
20setosa0
30setosa0
10versicolor0
210versicolor10
339versicolor39
10virginica0
236virginica36
314virginica14
How the groups of species map onto kmHow do the rows of one grouping spread over another, for example known classes over clusters?
View data
Rowsspecieskm
49setosa1
10versicolor2
39versicolor3
36virginica2
14virginica3

Agreement indices

IndexValueReading
Adjusted Rand index0.62540 = chance, 1 = identical
Adjusted mutual information0.65990 = chance, 1 = identical
Normalized mutual information0.66420 to 1; not chance-corrected
Variation of information (nats)0.73730 = identical; a distance
Normalized variation of information0.50280 = identical, 1 = unrelated
Fowlkes–Mallows0.74880 to 1
Rand index0.83450 to 1; not chance-corrected
Pair Jaccard0.59850 to 1
Homogeneity0.66371 = each judged group holds one reference group
Completeness0.66471 = each reference group sits in one judged group
V-measure0.6642harmonic mean of the two above
Purity0.8378share of rows in the majority reference group of their judged group
Inverse purity0.8378the same with the roles swapped

Rows by species (rows) and km (columns)

species123Total
setosa490049
versicolor0103949
virginica0361450
  • 2 of 150 rows were left out because a partition was missing.
The exact R script · R R version 4.5.1 (2025-06-13)
# Compare two partitions (ARI, AMI, VI, purity)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.compare_partitions 1.0.0 · spec 1365e5875bdb00ce
# Dataset: clu4_partitions (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data
A <- "species"
B <- "km"
NOISE_LABEL <- trimws("")
NOISE <- "cluster"
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/clu4_partitions.parquet", col_select = unique(c(A, B))))
n_input <- nrow(df)
cs_check_finite_columns(df, unique(c(A, B)))  # ±Inf stops with CS_E_NOT_FINITE in both engines
la <- cs_ml_label_text(df[[A]])
lb <- cs_ml_label_text(df[[B]])
ok <- !is.na(la) & !is.na(lb)
warnings <- list()
if (sum(ok) < n_input) warnings <- c(warnings, sprintf("%d of %d rows were left out because a partition was missing.", n_input - sum(ok), n_input))
cs_check_rows(sum(ok), 2, "Comparing two partitions")
nz <- cs_ml_partition_noise(la[ok], lb[ok], NOISE_LABEL, NOISE)
a <- nz$a
b <- nz$b
if (nz$n_noise > 0) {
  tail_msg <- switch(NOISE, cluster = "they count as one more group.", drop = "they were left out.", singletons = "each counts as a group of its own.")
  warnings <- c(warnings, sprintf("%d row(s) carry the noise label '%s'; %s", nz$n_noise, NOISE_LABEL, tail_msg))
}
cs_check_rows(length(a), 2, "Comparing two partitions")

# %% Agreement indices
r <- cs_ml_compare_partitions(a, b)
keys <- c("n", "k_a", "k_b", "ari", "ami", "nmi", "vi", "vi_bits", "nvi", "mi", "h_a", "h_b", "rand", "fmi", "jaccard",
          "homogeneity", "completeness", "v_measure", "purity", "inverse_purity")
values <- r[keys]
values$n_noise <- nz$n_noise
values$n_dropped <- nz$n_dropped
T <- r$table
la_lv <- r$levels_a
lb_lv <- r$levels_b
index_rows <- list(
  c("ari", "Adjusted Rand index", "0 = chance, 1 = identical"),
  c("ami", "Adjusted mutual information", "0 = chance, 1 = identical"),
  c("nmi", "Normalized mutual information", "0 to 1; not chance-corrected"),
  c("vi", "Variation of information (nats)", "0 = identical; a distance"),
  c("nvi", "Normalized variation of information", "0 = identical, 1 = unrelated"),
  c("fmi", "Fowlkes–Mallows", "0 to 1"),
  c("rand", "Rand index", "0 to 1; not chance-corrected"),
  c("jaccard", "Pair Jaccard", "0 to 1"),
  c("homogeneity", "Homogeneity", "1 = each judged group holds one reference group"),
  c("completeness", "Completeness", "1 = each reference group sits in one judged group"),
  c("v_measure", "V-measure", "harmonic mean of the two above"),
  c("purity", "Purity", "share of rows in the majority reference group of their judged group"),
  c("inverse_purity", "Inverse purity", "the same with the roles swapped")
)
cont_cols <- c(list(list(key = "level", label = A, type = "string")),
               lapply(seq_along(lb_lv), function(j) list(key = sprintf("b%d", j - 1L), label = lb_lv[j], type = "integer")),
               list(list(key = "total", label = "Total", type = "integer")))
cont_rows <- lapply(seq_along(la_lv), function(i) {
  row <- list(level = la_lv[i])
  for (j in seq_along(lb_lv)) row[[sprintf("b%d", j - 1L)]] <- as.integer(T[i, j])
  row$total <- as.integer(sum(T[i, ]))
  row
})
tables <- list(
  list(key = "indices", title = "Agreement indices",
       columns = list(list(key = "index", label = "Index", type = "string"), list(key = "value", label = "Value", type = "number"),
                      list(key = "reading", label = "Reading", type = "string")),
       rows = lapply(index_rows, function(x) list(index = x[2], value = values[[x[1]]], reading = x[3]))),
  list(key = "contingency", title = sprintf("Rows by %s (rows) and %s (columns)", A, B), columns = cont_cols, rows = cont_rows)
)

# %% Charts
charts <- list()
ci <- rep(seq_along(la_lv), each = length(lb_lv))
cj <- rep(seq_along(lb_lv), times = length(la_lv))
if (length(la_lv) <= 60 && length(lb_lv) <= 60) {
  charts[[length(charts) + 1L]] <- cs_chart("contingency", "matrix-heatmap", sprintf("Rows by %s and %s", A, B), list(
    row = cs_col(A, la_lv[ci], "categorical", levels = la_lv),
    col = cs_col(B, lb_lv[cj], "categorical", levels = lb_lv),
    value = cs_col("Rows", T[cbind(ci, cj)], "numeric"),
    label = cs_col("Count", as.character(as.integer(T[cbind(ci, cj)])), "categorical")
  ), note = "Each cell counts the rows in that pair of groups; a perfect match puts every row in one cell per row and column.")
}
if (length(la_lv) <= 30 && length(lb_lv) <= 30) {
  keep <- T[cbind(ci, cj)] > 0
  charts[[length(charts) + 1L]] <- cs_chart("flow", "partition-flow", sprintf("How the groups of %s map onto %s", A, B), list(
    from = cs_col(A, la_lv[ci[keep]], "categorical", levels = la_lv),
    to = cs_col(B, lb_lv[cj[keep]], "categorical", levels = lb_lv),
    count = cs_col("Rows", T[cbind(ci, cj)][keep], "numeric")
  ))
}

# %% Result
ari <- values$ari
verdict <- if (ari >= 0.9) "almost identical" else if (ari >= 0.5) "in substantial agreement" else if (ari >= 0.2) "in partial agreement" else "close to chance agreement"
cs_publish(list(
  title = "Compare two partitions (ARI, AMI, VI, purity)",
  engine = cs_engine_info("codesplashr", "nanoparquet"),
  n = values$n,
  summary = sprintf("%s (%d groups) and %s (%d groups) are %s: ARI %.2f, AMI %.2f, VI %.2f nats.", A, values$k_a, B, values$k_b, verdict, ari, values$ami, values$vi),
  statistics = list(list(key = "ari", label = "Adjusted Rand index", value = ari),
                    list(key = "ami", label = "Adjusted mutual information", value = values$ami),
                    list(key = "vi", label = "Variation of information (nats)", value = values$vi)),
  tables = tables,
  values = values,
  charts = charts,
  warnings = warnings
))
Python

species (3 groups) and km (3 groups) are in substantial agreement: ARI 0.63, AMI 0.66, VI 0.74 nats.

Adjusted Rand index
0.6254
Adjusted mutual information
0.6599
Variation of information (nats)
0.7373

To keep this page light, the plots are shown once, under the R tab.

Agreement indices

IndexValueReading
Adjusted Rand index0.62540 = chance, 1 = identical
Adjusted mutual information0.65990 = chance, 1 = identical
Normalized mutual information0.66420 to 1; not chance-corrected
Variation of information (nats)0.73730 = identical; a distance
Normalized variation of information0.50280 = identical, 1 = unrelated
Fowlkes–Mallows0.74880 to 1
Rand index0.83450 to 1; not chance-corrected
Pair Jaccard0.59850 to 1
Homogeneity0.66371 = each judged group holds one reference group
Completeness0.66471 = each reference group sits in one judged group
V-measure0.6642harmonic mean of the two above
Purity0.8378share of rows in the majority reference group of their judged group
Inverse purity0.8378the same with the roles swapped

Rows by species (rows) and km (columns)

species123Total
setosa490049
versicolor0103949
virginica0361450
  • 2 of 150 rows were left out because a partition was missing.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Compare two partitions (ARI, AMI, VI, purity)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.compare_partitions 1.0.0 · spec 1365e5875bdb00ce
# Dataset: clu4_partitions (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd

import codesplash as cs
from codesplash.ml import cluster_compare as cc

# %% Data
A = "species"
B = "km"
NOISE_LABEL = "".strip()
NOISE = "cluster"
df = pd.read_parquet("tests/parity/fixtures/clu4_partitions.parquet", columns=list(dict.fromkeys([A, B])))
n_input = len(df)
cs.check_finite_columns(df, [A, B])  # ±Inf stops with CS_E_NOT_FINITE in both engines
la = cc.label_text(df[A].tolist())
lb = cc.label_text(df[B].tolist())
ok = np.array([x is not None and y is not None for x, y in zip(la, lb)])
warnings = []
if int(ok.sum()) < n_input:
    warnings.append(f"{n_input - int(ok.sum())} of {n_input} rows were left out because a partition was missing.")
cs.check_rows(int(ok.sum()), 2, "Comparing two partitions")
a, b, n_noise, n_dropped = cc.apply_noise(la[ok], lb[ok], NOISE_LABEL, NOISE)
if n_noise:
    warnings.append(
        f"{n_noise} row(s) carry the noise label {NOISE_LABEL!r}; "
        + {"cluster": "they count as one more group.", "drop": "they were left out.", "singletons": "each counts as a group of its own."}[NOISE]
    )
cs.check_rows(len(a), 2, "Comparing two partitions")

# %% Agreement indices
r = cc.compare_partitions(a, b)
keys = ["n", "k_a", "k_b", "ari", "ami", "nmi", "vi", "vi_bits", "nvi", "mi", "h_a", "h_b", "rand", "fmi", "jaccard",
        "homogeneity", "completeness", "v_measure", "purity", "inverse_purity"]
values = {k: r[k] for k in keys}
values["n_noise"] = n_noise
values["n_dropped"] = n_dropped
T = r["table"]
la_lv, lb_lv = r["levels_a"], r["levels_b"]
index_rows = [
    ("ari", "Adjusted Rand index", "0 = chance, 1 = identical"),
    ("ami", "Adjusted mutual information", "0 = chance, 1 = identical"),
    ("nmi", "Normalized mutual information", "0 to 1; not chance-corrected"),
    ("vi", "Variation of information (nats)", "0 = identical; a distance"),
    ("nvi", "Normalized variation of information", "0 = identical, 1 = unrelated"),
    ("fmi", "Fowlkes–Mallows", "0 to 1"),
    ("rand", "Rand index", "0 to 1; not chance-corrected"),
    ("jaccard", "Pair Jaccard", "0 to 1"),
    ("homogeneity", "Homogeneity", "1 = each judged group holds one reference group"),
    ("completeness", "Completeness", "1 = each reference group sits in one judged group"),
    ("v_measure", "V-measure", "harmonic mean of the two above"),
    ("purity", "Purity", "share of rows in the majority reference group of their judged group"),
    ("inverse_purity", "Inverse purity", "the same with the roles swapped"),
]
tables = [
    {
        "key": "indices",
        "title": "Agreement indices",
        "columns": [{"key": "index", "label": "Index", "type": "string"}, {"key": "value", "label": "Value", "type": "number"},
                    {"key": "reading", "label": "Reading", "type": "string"}],
        "rows": [{"index": lab, "value": values[k], "reading": note} for k, lab, note in index_rows],
    },
    {
        "key": "contingency",
        "title": f"Rows by {A} (rows) and {B} (columns)",
        "columns": [{"key": "level", "label": A, "type": "string"}]
        + [{"key": f"b{j}", "label": str(lv), "type": "integer"} for j, lv in enumerate(lb_lv)]
        + [{"key": "total", "label": "Total", "type": "integer"}],
        "rows": [
            {"level": str(lv), **{f"b{j}": int(T[i, j]) for j in range(len(lb_lv))}, "total": int(T[i].sum())}
            for i, lv in enumerate(la_lv)
        ],
    },
]

# %% Charts
charts = []
cells = [(i, j) for i in range(len(la_lv)) for j in range(len(lb_lv))]
if len(la_lv) <= 60 and len(lb_lv) <= 60:
    charts.append(cs.chart(
        "contingency", "matrix-heatmap", f"Rows by {A} and {B}",
        {
            "row": cs.col(A, [str(la_lv[i]) for i, _ in cells], "categorical", levels=[str(x) for x in la_lv]),
            "col": cs.col(B, [str(lb_lv[j]) for _, j in cells], "categorical", levels=[str(x) for x in lb_lv]),
            "value": cs.col("Rows", [float(T[i, j]) for i, j in cells], "numeric"),
            "label": cs.col("Count", [str(int(T[i, j])) for i, j in cells], "categorical"),
        },
        note="Each cell counts the rows in that pair of groups; a perfect match puts every row in one cell per row and column.",
    ))
if len(la_lv) <= 30 and len(lb_lv) <= 30:
    nz = [(i, j) for i, j in cells if T[i, j] > 0]
    charts.append(cs.chart(
        "flow", "partition-flow", f"How the groups of {A} map onto {B}",
        {
            "from": cs.col(A, [str(la_lv[i]) for i, _ in nz], "categorical", levels=[str(x) for x in la_lv]),
            "to": cs.col(B, [str(lb_lv[j]) for _, j in nz], "categorical", levels=[str(x) for x in lb_lv]),
            "count": cs.col("Rows", [float(T[i, j]) for i, j in nz], "numeric"),
        },
    ))

# %% Result
ari = values["ari"]
verdict = "almost identical" if ari >= 0.9 else ("in substantial agreement" if ari >= 0.5 else ("in partial agreement" if ari >= 0.2 else "close to chance agreement"))
cs.publish({
    "title": "Compare two partitions (ARI, AMI, VI, purity)",
    "engine": cs.engine_info("numpy", "scipy", "pandas"),
    "n": values["n"],
    "summary": f"{A} ({values['k_a']} groups) and {B} ({values['k_b']} groups) are {verdict}: ARI {ari:.2f}, AMI {values['ami']:.2f}, VI {values['vi']:.2f} nats.",
    "statistics": [
        {"key": "ari", "label": "Adjusted Rand index", "value": ari},
        {"key": "ami", "label": "Adjusted mutual information", "value": values["ami"]},
        {"key": "vi", "label": "Variation of information (nats)", "value": values["vi"]},
    ],
    "tables": tables,
    "values": values,
    "charts": charts,
    "warnings": warnings,
})

K-means against species: ARI 0.63, AMI 0.66. Moderate agreement with one labeling can penalize another valid structure, and high agreement says nothing about whether the groups help the task in the contract. If you tuned the clustering against the labels, an external score on those labels is optimistic; keep some labels for the final check, and show the contingency table and group sizes.

AExplorable · Do the clusters survive resampling?

Would the same clusters come back from a slightly different sample?

k-means always returns k clusters. Will its least stable cluster here come back in resamples (mean Jaccard above 0.75)?

How sure?

Data

3
120
Simulating…

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

08

In CodeSplash

In the app

In Discover, Compare two partitions takes two label columns of the same rows (for example two saved clusterings, or a clustering and known groups) and reports ARI, AMI, NMI, VI with both conditional entropies, purity, homogeneity and completeness, with a choice of how to treat noise labels. Choose the number of clusters, the Gaussian mixture and k-means report ARI and AMI against a Known groups column when you set one.

09

Check: comparing partitions

Checkpoint

Check yourself

An ARI of −0.05. What does it mean?

Show the answer

Answer: b

ARI is chance-corrected: 0 is chance level and small negative values happen. It isn't a test.

Check yourself

One run labels clusters 1, 2, 3 and another labels the same groups 3, 1, 2. What is their ARI?

Show the answer

Answer: a

ARI uses only which rows are grouped together, never the names, so a relabeling is perfect agreement.

Check yourself

You compare a 3-group labeling with clusterings of 3, 10 and 40 groups. Why prefer AMI to NMI?

Show the answer

Answer: b

Without the expected-information correction, finer partitions look better than they are.

Check yourself

Two papers report AMI for the same partitions and get slightly different values. A likely reason?

Show the answer

Answer: b

AMI's denominator uses a chosen mean. Report it.

Check yourself

Comparing an old partition U with a refined one V, H(V | U) is large and H(U | V) near zero. What happened?

Show the answer

Answer: a

Knowing U leaves uncertainty about V (splits); knowing V pins down U (no merges).

Check yourself

Study A reports VI = 1.2 nats on 100 rows; study B reports VI = 1.8 nats on 100,000 rows. Can you say A's partitions agree better?

Show the answer

Answer: b

Compare VI within one set of rows. Across studies, a chance-corrected score is fairer.

Check yourself

You chose the number of clusters by maximizing ARI against the labels, then reported that ARI. What's the problem?

Show the answer

Answer: b

Selecting on a score and reporting the same score on the same labels inflates it, exactly as with test-set tuning.

10

Recap

Recap
  • Partition scores ignore label names and use the contingency table.
  • ARI and AMI are chance-corrected (0 = chance, negatives possible); prefer AMI over NMI when group counts differ, and name AMI's mean.
  • VI is a distance; its two conditional entropies separate splits from merges.
  • Report the noise rule, the rows used and whether the labels were used for tuning.

Concepts in this lesson