CDiscover · discover.compare_partitions
Compare two partitions (ARI, AMI, VI, purity)
How closely do two groupings of the same rows agree — a clustering and the known groups, or two clusterings?
Cross-tabulates two partitions of the same rows and reports every common agreement index: the adjusted Rand index and adjusted mutual information (0 = chance agreement, 1 = identical), normalized mutual information, variation of information (a distance: 0 = identical, in nats and bits), Fowlkes–Mallows, Rand and pair Jaccard, homogeneity, completeness and V-measure, and purity both ways. The first partition is the reference. A noise label (DBSCAN's −1) can be kept as a group, dropped or made singletons, so the convention behind a score is explicit.
A real result
Example “Iris species vs kmeans”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
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
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.
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.
Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.
Worked examples in the app
- Iris species vs kmeansclu4_partitions · a: species · b: km
- Iris species vs dbscan noise groupclu4_partitions · a: species · b: db
- Iris species vs dbscan noise droppedclu4_partitions · a: species · b: db
- Iris species vs dbscan noise singletonsclu4_partitions · a: species · b: db
- Iris ward vs kmeansclu4_partitions · a: hc · b: km
- Iris identicalclu4_partitions · a: species · b: species
- Degenerate constantclu4_partitions · a: species · b: km
- Degenerate unicode levelsclu4_partitions · a: species · b: km
In the guides
Where it sits in the decision guides
- Testing and comparing clusterings (SigClust, selective inference, ARI, CKA) · DS & ML Decision Guide · Discover — find structure without labels
- Discover: cluster quality (silhouette, ARI); coherence (topics); stability and interpretability · DS & ML Decision Guide · How to evaluate — common metrics by question type
What you need
- Reference partitioncategorical / numeric / boolean · 1 column
- Groups to compare against, such as the known classes or a first clustering (rows with a missing value are left out).
- Partition to judgecategorical / numeric / boolean · 1 column
- The grouping being scored against the reference, such as saved cluster labels.
Choices you make
model
- Noise labeldefault —
A value that marks unclustered rows in either partition (DBSCAN and HDBSCAN use -1). Leave blank when there is none.
- Noise rowsdefault cluster
How rows with the noise label count. The choice changes every score, so report it.
- One more group(default) — All noise rows form a group of their own (scikit-learn's default when -1 is a label).
- Leave them out — Scores only the rows both partitions clustered; says how many were dropped.
- Each its own group — Every noise row is a group of one, so noise never counts as agreement.
What it reports
- n
- Rows compared, groups in each partition, rows with the noise label and rows dropped by the noise rule.
- n_noise
- Rows compared, groups in each partition, rows with the noise label and rows dropped by the noise rule.
- n_dropped
- Rows compared, groups in each partition, rows with the noise label and rows dropped by the noise rule.
- k_a
- Rows compared, groups in each partition, rows with the noise label and rows dropped by the noise rule.
- k_b
- Rows compared, groups in each partition, rows with the noise label and rows dropped by the noise rule.
- ari
- Pair-counting agreement of two partitions, corrected so chance agreement is 0 and identical partitions 1.
- ami
- Shared information of two partitions corrected for chance: 0 = chance, 1 = identical; fair across group counts.
- nmi
- Mutual information divided by the mean of the two entropies; 0 to 1, but not corrected for chance.
- vi
- H(A|B) + H(B|A): information lost going either way between two partitions; a true distance, 0 = identical.
- vi_bits
- H(A|B) + H(B|A): information lost going either way between two partitions; a true distance, 0 = identical.
- nvi
- H(A|B) + H(B|A): information lost going either way between two partitions; a true distance, 0 = identical.
- mi
- Mutual information divided by the mean of the two entropies; 0 to 1, but not corrected for chance.
- h_a
- Entropy of a partition's group sizes in nats; 0 when everything is in one group.
- h_b
- Entropy of a partition's group sizes in nats; 0 when everything is in one group.
- rand
- Agreement on pairs of rows grouped together or apart: Rand (all pairs), Fowlkes–Mallows and Jaccard (pairs together).
- fmi
- Agreement on pairs of rows grouped together or apart: Rand (all pairs), Fowlkes–Mallows and Jaccard (pairs together).
- jaccard
- Agreement on pairs of rows grouped together or apart: Rand (all pairs), Fowlkes–Mallows and Jaccard (pairs together).
- homogeneity
- Homogeneity: each judged group holds one reference group. Completeness: each reference group stays in one judged group.
- completeness
- Homogeneity: each judged group holds one reference group. Completeness: each reference group stays in one judged group.
- v_measure
- Homogeneity: each judged group holds one reference group. Completeness: each reference group stays in one judged group.
- purity
- Share of rows that sit in the majority reference group of their judged group; inverse purity swaps the roles.
- inverse_purity
- Share of rows that sit in the majority reference group of their judged group; inverse purity swaps the roles.
Python and R
Python and R agree to 10 decimals (relative tolerance 1e-10). Python uses numpy, scipy; R uses codesplashr.
Default traps between the two languages
- Both engines compute every index from the same contingency table with written-out formulas (scikit-learn's definitions; AMI's expected mutual information from log-gamma terms), so they agree to rounding. R's aricode gives the same ARI and VI, but its AMI uses the max normalizer by default; the oracle check therefore uses scikit-learn.
The exact script CodeSplash ran for example “Iris species vs kmeans” · 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,
})
The exact script CodeSplash ran for example “Iris species vs kmeans” · 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
))
Sources
- Hubert L, Arabie P (1985). Comparing partitions. Journal of Classification 2:193–218.
- Vinh NX, Epps J, Bailey J (2010). Information theoretic measures for clusterings comparison. JMLR 11:2837–2854.
- Meilă M (2007). Comparing clusterings — an information based distance. Journal of Multivariate Analysis 98:873–895.
- Rosenberg A, Hirschberg J (2007). V-measure: a conditional entropy-based external cluster evaluation measure. EMNLP-CoNLL 2007, 410–420.
- Fowlkes EB, Mallows CL (1983). A method for comparing two hierarchical clusterings. JASA 78:553–569.
From the CodeSplash method registry · discover.compare_partitions v1.0.0.