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.
What runs in CodeSplash
- EVA010Adjusted Rand index Runs in CodeSplash
- EVA011Adjusted mutual information Runs in CodeSplash
- EVA012Variation of information Runs in CodeSplash
- Compare two partitions (ARI, AMI, VI, purity) Verified in Python and R
- Choose the number of clusters Verified in Python and R
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
Labels are arbitrary
ReadCluster "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 of how many rows fall in group of one partition and group 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.
Adjusted Rand index
ReadThe 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:
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.Adjusted mutual information
ReadAdjusted mutual informationAdjusted mutual informationShared information of two partitions corrected for chance: 0 = chance, 1 = identical; fair across group counts. measures shared information beyond chance:
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.Variation of information
ReadVariation 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:
In the reference's example it is 0.693 nats, exactly . Its two parts tell a story: large means splits groups of ; large means 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.Splits and merges
Explorehc (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
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
| km | Count | hc | Rows |
|---|---|---|---|
| 1 | 48 | h1 | 48 |
| 2 | 0 | h1 | 0 |
| 3 | 0 | h1 | 0 |
| 1 | 1 | h2 | 1 |
| 2 | 0 | h2 | 0 |
| 3 | 29 | h2 | 29 |
| 1 | 0 | h3 | 0 |
| 2 | 20 | h3 | 20 |
| 3 | 24 | h3 | 24 |
| 1 | 0 | h4 | 0 |
| 2 | 26 | h4 | 26 |
| 3 | 0 | h4 | 0 |
View data
| Rows | hc | km |
|---|---|---|
| 48 | h1 | 1 |
| 1 | h2 | 1 |
| 29 | h2 | 3 |
| 20 | h3 | 2 |
| 24 | h3 | 3 |
| 26 | h4 | 2 |
Agreement indices
| Index | Value | Reading |
|---|---|---|
| Adjusted Rand index | 0.6106 | 0 = chance, 1 = identical |
| Adjusted mutual information | 0.6984 | 0 = chance, 1 = identical |
| Normalized mutual information | 0.7035 | 0 to 1; not chance-corrected |
| Variation of information (nats) | 0.7269 | 0 = identical; a distance |
| Normalized variation of information | 0.4573 | 0 = identical, 1 = unrelated |
| Fowlkes–Mallows | 0.7290 | 0 to 1 |
| Rand index | 0.8370 | 0 to 1; not chance-corrected |
| Pair Jaccard | 0.5673 | 0 to 1 |
| Homogeneity | 0.6366 | 1 = each judged group holds one reference group |
| Completeness | 0.7863 | 1 = each reference group sits in one judged group |
| V-measure | 0.7035 | harmonic mean of the two above |
| Purity | 0.6959 | share of rows in the majority reference group of their judged group |
| Inverse purity | 0.8581 | the same with the roles swapped |
Rows by hc (rows) and km (columns)
| hc | 1 | 2 | 3 | Total |
|---|---|---|---|---|
| h1 | 48 | 0 | 0 | 48 |
| h2 | 1 | 0 | 29 | 30 |
| h3 | 0 | 20 | 24 | 44 |
| h4 | 0 | 26 | 0 | 26 |
- 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
))
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
| Index | Value | Reading |
|---|---|---|
| Adjusted Rand index | 0.6106 | 0 = chance, 1 = identical |
| Adjusted mutual information | 0.6984 | 0 = chance, 1 = identical |
| Normalized mutual information | 0.7035 | 0 to 1; not chance-corrected |
| Variation of information (nats) | 0.7269 | 0 = identical; a distance |
| Normalized variation of information | 0.4573 | 0 = identical, 1 = unrelated |
| Fowlkes–Mallows | 0.7290 | 0 to 1 |
| Rand index | 0.8370 | 0 to 1; not chance-corrected |
| Pair Jaccard | 0.5673 | 0 to 1 |
| Homogeneity | 0.6366 | 1 = each judged group holds one reference group |
| Completeness | 0.7863 | 1 = each reference group sits in one judged group |
| V-measure | 0.7035 | harmonic mean of the two above |
| Purity | 0.6959 | share of rows in the majority reference group of their judged group |
| Inverse purity | 0.8581 | the same with the roles swapped |
Rows by hc (rows) and km (columns)
| hc | 1 | 2 | 3 | Total |
|---|---|---|---|---|
| h1 | 48 | 0 | 0 | 48 |
| h2 | 1 | 0 | 29 | 30 |
| h3 | 0 | 20 | 24 | 44 |
| h4 | 0 | 26 | 0 | 26 |
- 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.
Noise points change the score
PredictPredict 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?
Reveal
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
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
| db | Count | species | Rows |
|---|---|---|---|
| -1 | 5 | setosa | 5 |
| 0 | 45 | setosa | 45 |
| 1 | 0 | setosa | 0 |
| -1 | 11 | versicolor | 11 |
| 0 | 0 | versicolor | 0 |
| 1 | 39 | versicolor | 39 |
| -1 | 18 | virginica | 18 |
| 0 | 0 | virginica | 0 |
| 1 | 32 | virginica | 32 |
View data
| Rows | species | db |
|---|---|---|
| 5 | setosa | -1 |
| 45 | setosa | 0 |
| 11 | versicolor | -1 |
| 39 | versicolor | 1 |
| 18 | virginica | -1 |
| 32 | virginica | 1 |
Agreement indices
| Index | Value | Reading |
|---|---|---|
| Adjusted Rand index | 0.4421 | 0 = chance, 1 = identical |
| Adjusted mutual information | 0.5052 | 0 = chance, 1 = identical |
| Normalized mutual information | 0.5114 | 0 to 1; not chance-corrected |
| Variation of information (nats) | 1.051 | 0 = identical; a distance |
| Normalized variation of information | 0.6564 | 0 = identical, 1 = unrelated |
| Fowlkes–Mallows | 0.6349 | 0 to 1 |
| Rand index | 0.7476 | 0 to 1; not chance-corrected |
| Pair Jaccard | 0.4643 | 0 to 1 |
| Homogeneity | 0.5005 | 1 = each judged group holds one reference group |
| Completeness | 0.5228 | 1 = each reference group sits in one judged group |
| V-measure | 0.5114 | harmonic mean of the two above |
| Purity | 0.6800 | share of rows in the majority reference group of their judged group |
| Inverse purity | 0.7733 | the same with the roles swapped |
Rows by species (rows) and db (columns)
| species | -1 | 0 | 1 | Total |
|---|---|---|---|---|
| setosa | 5 | 45 | 0 | 50 |
| versicolor | 11 | 0 | 39 | 50 |
| virginica | 18 | 0 | 32 | 50 |
- 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
))
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
| Index | Value | Reading |
|---|---|---|
| Adjusted Rand index | 0.4421 | 0 = chance, 1 = identical |
| Adjusted mutual information | 0.5052 | 0 = chance, 1 = identical |
| Normalized mutual information | 0.5114 | 0 to 1; not chance-corrected |
| Variation of information (nats) | 1.051 | 0 = identical; a distance |
| Normalized variation of information | 0.6564 | 0 = identical, 1 = unrelated |
| Fowlkes–Mallows | 0.6349 | 0 to 1 |
| Rand index | 0.7476 | 0 to 1; not chance-corrected |
| Pair Jaccard | 0.4643 | 0 to 1 |
| Homogeneity | 0.5005 | 1 = each judged group holds one reference group |
| Completeness | 0.5228 | 1 = each reference group sits in one judged group |
| V-measure | 0.5114 | harmonic mean of the two above |
| Purity | 0.6800 | share of rows in the majority reference group of their judged group |
| Inverse purity | 0.7733 | the same with the roles swapped |
Rows by species (rows) and db (columns)
| species | -1 | 0 | 1 | Total |
|---|---|---|---|---|
| setosa | 5 | 45 | 0 | 50 |
| versicolor | 11 | 0 | 39 | 50 |
| virginica | 18 | 0 | 32 | 50 |
- 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.
Agreement isn't usefulness
Readspecies (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
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
| km | Count | species | Rows |
|---|---|---|---|
| 1 | 49 | setosa | 49 |
| 2 | 0 | setosa | 0 |
| 3 | 0 | setosa | 0 |
| 1 | 0 | versicolor | 0 |
| 2 | 10 | versicolor | 10 |
| 3 | 39 | versicolor | 39 |
| 1 | 0 | virginica | 0 |
| 2 | 36 | virginica | 36 |
| 3 | 14 | virginica | 14 |
View data
| Rows | species | km |
|---|---|---|
| 49 | setosa | 1 |
| 10 | versicolor | 2 |
| 39 | versicolor | 3 |
| 36 | virginica | 2 |
| 14 | virginica | 3 |
Agreement indices
| Index | Value | Reading |
|---|---|---|
| Adjusted Rand index | 0.6254 | 0 = chance, 1 = identical |
| Adjusted mutual information | 0.6599 | 0 = chance, 1 = identical |
| Normalized mutual information | 0.6642 | 0 to 1; not chance-corrected |
| Variation of information (nats) | 0.7373 | 0 = identical; a distance |
| Normalized variation of information | 0.5028 | 0 = identical, 1 = unrelated |
| Fowlkes–Mallows | 0.7488 | 0 to 1 |
| Rand index | 0.8345 | 0 to 1; not chance-corrected |
| Pair Jaccard | 0.5985 | 0 to 1 |
| Homogeneity | 0.6637 | 1 = each judged group holds one reference group |
| Completeness | 0.6647 | 1 = each reference group sits in one judged group |
| V-measure | 0.6642 | harmonic mean of the two above |
| Purity | 0.8378 | share of rows in the majority reference group of their judged group |
| Inverse purity | 0.8378 | the same with the roles swapped |
Rows by species (rows) and km (columns)
| species | 1 | 2 | 3 | Total |
|---|---|---|---|---|
| setosa | 49 | 0 | 0 | 49 |
| versicolor | 0 | 10 | 39 | 49 |
| virginica | 0 | 36 | 14 | 50 |
- 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
))
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
| Index | Value | Reading |
|---|---|---|
| Adjusted Rand index | 0.6254 | 0 = chance, 1 = identical |
| Adjusted mutual information | 0.6599 | 0 = chance, 1 = identical |
| Normalized mutual information | 0.6642 | 0 to 1; not chance-corrected |
| Variation of information (nats) | 0.7373 | 0 = identical; a distance |
| Normalized variation of information | 0.5028 | 0 = identical, 1 = unrelated |
| Fowlkes–Mallows | 0.7488 | 0 to 1 |
| Rand index | 0.8345 | 0 to 1; not chance-corrected |
| Pair Jaccard | 0.5985 | 0 to 1 |
| Homogeneity | 0.6637 | 1 = each judged group holds one reference group |
| Completeness | 0.6647 | 1 = each reference group sits in one judged group |
| V-measure | 0.6642 | harmonic mean of the two above |
| Purity | 0.8378 | share of rows in the majority reference group of their judged group |
| Inverse purity | 0.8378 | the same with the roles swapped |
Rows by species (rows) and km (columns)
| species | 1 | 2 | 3 | Total |
|---|---|---|---|---|
| setosa | 49 | 0 | 0 | 49 |
| versicolor | 0 | 10 | 39 | 49 |
| virginica | 0 | 36 | 14 | 50 |
- 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)?
Data
Commit your prediction above to see the result
Make your prediction to see the result.
In CodeSplash
In the appIn 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.
Check: comparing partitions
CheckpointCheck 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.
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