Is the split real? Testing and comparing clusterings
Test whether two clusters beat one Gaussian cloud (SigClust), test cluster means without double dipping (selective inference), and compare two clusterings or two maps of the same rows with the right index.
What runs in CodeSplash
- Is the split significant? (SigClust) Verified in Python and R
- Are these clusters really different? (selective inference) Experimental
- Compare two partitions (ARI, AMI, VI, purity) Verified in Python and R
- Compare two embeddings (CKA, Procrustes, kNN overlap) Verified in Python and R
You will be able to
- Read SigClust's cluster index and p-value
- Explain why testing clusters on the data that formed them needs a selective p-value
- Pick an agreement index for two partitions and state the noise convention
- Tell global from local agreement between two embeddings
Two clusters, or one cloud?
Readk-means always returns the groups you ask for, even from a single round cloud. SigClustSigClustTests whether the best two-group split beats what one Gaussian cloud with the data's shape would give. asks whether the best two-group split is stronger than one Gaussian cloud with the data's own shape would give. Its statistic is the cluster indexCluster indexWithin-cluster sum of squares of a two-group split divided by the total; smaller = a cleaner split.: the within-cluster sum of squares of the split divided by the total. The null comes from simulating Gaussian data with the data's covariance eigenvalues, small ones raised to a background noise levelBackground noise varianceNoise level estimated robustly from all values (MAD squared); small eigenvalues are raised to it in the null. estimated from all values.
Here are two well-separated clouds:
The best 2-means split has cluster index 0.579 (null mean 0.684); p = 0: the split is stronger than one Gaussian cloud would give.
- Cluster index
- 0.5792
- p (simulated)
- < .001
- p (Gaussian fit)
- < .001
Plots
Normal curve fitted to 100 simulated cluster indices; a split far to the left of it is stronger than one cloud would give.
View data
| 5% critical value | Null density (normal fit) | Observed cluster index | Cluster index |
|---|---|---|---|
| 0.6299 | 5.642e-8 | 0.5792 | 0.4810 |
| 0.6299 | 8.078e-8 | 0.5792 | 0.4829 |
| 0.6299 | 1.153e-7 | 0.5792 | 0.4848 |
| 0.6299 | 1.639e-7 | 0.5792 | 0.4867 |
| 0.6299 | 2.323e-7 | 0.5792 | 0.4886 |
| 0.6299 | 3.281e-7 | 0.5792 | 0.4905 |
| 0.6299 | 4.618e-7 | 0.5792 | 0.4924 |
| 0.6299 | 6.479e-7 | 0.5792 | 0.4943 |
| 0.6299 | 9.059e-7 | 0.5792 | 0.4962 |
| 0.6299 | 1.262e-6 | 0.5792 | 0.4981 |
| 0.6299 | 1.753e-6 | 0.5792 | 0.5000 |
| 0.6299 | 2.426e-6 | 0.5792 | 0.5020 |
| 0.6299 | 3.347e-6 | 0.5792 | 0.5039 |
| 0.6299 | 4.601e-6 | 0.5792 | 0.5058 |
| 0.6299 | 6.303e-6 | 0.5792 | 0.5077 |
| 0.6299 | 8.606e-6 | 0.5792 | 0.5096 |
| 0.6299 | 1.171e-5 | 0.5792 | 0.5115 |
| 0.6299 | 1.588e-5 | 0.5792 | 0.5134 |
| 0.6299 | 2.147e-5 | 0.5792 | 0.5153 |
| 0.6299 | 2.892e-5 | 0.5792 | 0.5172 |
| 0.6299 | 3.882e-5 | 0.5792 | 0.5191 |
| 0.6299 | 5.194e-5 | 0.5792 | 0.5210 |
| 0.6299 | 6.925e-5 | 0.5792 | 0.5229 |
| 0.6299 | 9.203e-5 | 0.5792 | 0.5248 |
| 0.6299 | 0.0001 | 0.5792 | 0.5267 |
| 0.6299 | 0.0002 | 0.5792 | 0.5286 |
| 0.6299 | 0.0002 | 0.5792 | 0.5305 |
| 0.6299 | 0.0003 | 0.5792 | 0.5324 |
| 0.6299 | 0.0004 | 0.5792 | 0.5343 |
| 0.6299 | 0.0005 | 0.5792 | 0.5362 |
| 0.6299 | 0.0006 | 0.5792 | 0.5381 |
| 0.6299 | 0.0008 | 0.5792 | 0.5400 |
| 0.6299 | 0.0010 | 0.5792 | 0.5419 |
| 0.6299 | 0.0013 | 0.5792 | 0.5438 |
| 0.6299 | 0.0017 | 0.5792 | 0.5457 |
| 0.6299 | 0.0021 | 0.5792 | 0.5476 |
| 0.6299 | 0.0027 | 0.5792 | 0.5496 |
| 0.6299 | 0.0035 | 0.5792 | 0.5515 |
| 0.6299 | 0.0044 | 0.5792 | 0.5534 |
| 0.6299 | 0.0055 | 0.5792 | 0.5553 |
| 0.6299 | 0.0069 | 0.5792 | 0.5572 |
| 0.6299 | 0.0086 | 0.5792 | 0.5591 |
| 0.6299 | 0.0107 | 0.5792 | 0.5610 |
| 0.6299 | 0.0133 | 0.5792 | 0.5629 |
| 0.6299 | 0.0165 | 0.5792 | 0.5648 |
| 0.6299 | 0.0204 | 0.5792 | 0.5667 |
| 0.6299 | 0.0250 | 0.5792 | 0.5686 |
| 0.6299 | 0.0307 | 0.5792 | 0.5705 |
| 0.6299 | 0.0374 | 0.5792 | 0.5724 |
| 0.6299 | 0.0455 | 0.5792 | 0.5743 |
| 0.6299 | 0.0552 | 0.5792 | 0.5762 |
| 0.6299 | 0.0668 | 0.5792 | 0.5781 |
| 0.6299 | 0.0804 | 0.5792 | 0.5800 |
| 0.6299 | 0.0965 | 0.5792 | 0.5819 |
| 0.6299 | 0.1155 | 0.5792 | 0.5838 |
| 0.6299 | 0.1377 | 0.5792 | 0.5857 |
| 0.6299 | 0.1637 | 0.5792 | 0.5876 |
| 0.6299 | 0.1939 | 0.5792 | 0.5895 |
| 0.6299 | 0.2288 | 0.5792 | 0.5914 |
| 0.6299 | 0.2692 | 0.5792 | 0.5933 |
First 60 of 200 rows.
Covariance eigenvalues: data and null
| Component | Data | Null (simulated) |
|---|---|---|
| 1 | 4.234 | 4.234 |
| 2 | 1.203 | 1.203 |
| 3 | 0.8151 | 1.147 |
| 4 | 0.7625 | 1.147 |
| 5 | 0.6405 | 1.147 |
The exact R script · R R version 4.5.1 (2025-06-13)
# Is the split significant? (SigClust)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.sigclust 1.0.0 · spec 8d6ef312e2dcb35b
# Dataset: clu4_sigclust (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
FEATURES <- c("c1", "c2", "c3", "c4", "c5")
SPLIT <- NULL # optional two-group column to test
SEED <- 42
SIMS <- 100
STARTS <- 3
METHOD <- "soft"
SCALE <- "none"
cols <- unique(c(FEATURES, if (!is.null(SPLIT)) SPLIT))
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/clu4_sigclust.parquet", col_select = cols))
n_input <- nrow(df)
cs_check_finite_columns(df, cols) # ±Inf stops with CS_E_NOT_FINITE in both engines
rows <- cs_ml_complete_rows(df, cols)
warnings <- list()
if (length(rows) < n_input) warnings <- c(warnings, sprintf("%d of %d rows were left out because a value was missing.", n_input - length(rows), n_input))
cs_check_rows(length(rows), 5, "SigClust")
X <- cs_ml_numeric_matrix(df, FEATURES, rows)
if (all(apply(X, 2, function(v) max(v) - min(v)) == 0)) cs_error("CS_E_CONSTANT", column = paste(FEATURES, collapse = ", "))
if (SCALE == "standardize") {
flat <- apply(X, 2, function(v) max(v) - min(v)) == 0
s <- apply(X, 2, stats::sd)
s[flat] <- 1
X <- sweep(sweep(X, 2, colMeans(X)), 2, s, "/")
X[, flat] <- 0 # constant columns exactly 0 in both engines
}
split <- NULL
if (!is.null(SPLIT)) {
lab <- cs_ml_label_text(df[[SPLIT]][rows + 1L])
cs_check_groups(lab, SPLIT, exactly = 2)
levels <- sort(unique(lab), method = "radix")
split <- match(lab, levels) - 1L
}
# %% SigClust
r <- cs_ml_sigclust(X, SIMS, STARTS, METHOD, cs_rng(SEED), split)
lab <- r$labels
sizes <- c(sort(as.integer(table(lab)), decreasing = TRUE), 0L, 0L)
values <- list(n = r$n, d = r$d, ci = r$ci, p_empirical = r$p_empirical, p_gaussian = r$p_gaussian,
sim_mean = r$sim_mean, sim_sd = r$sim_sd, sigma2_background = r$sigma2_background, tau = r$tau,
n_floored = r$n_floored, size_1 = sizes[1], size_2 = sizes[2], sims = SIMS)
if (is.nan(values$tau)) warnings <- c(warnings, "Every eigenvalue is below the background noise level, so the null uses the noise level for all of them.")
eig <- r$eigen
eig0 <- r$eigen_null
tables <- list(list(key = "eigenvalues", title = "Covariance eigenvalues: data and null",
columns = list(list(key = "component", label = "Component", type = "integer"),
list(key = "sample", label = "Data", type = "number"),
list(key = "null", label = "Null (simulated)", type = "number")),
rows = lapply(seq_len(min(length(eig), 50)), function(j) list(component = j, sample = eig[j], null = eig0[j]))))
# %% Null distribution chart (normal fitted to the simulated cluster indices)
sims <- r$sims
m <- values$sim_mean
s <- values$sim_sd
charts <- list()
if (is.finite(s) && s > 0) {
lo <- min(min(sims), values$ci) - 3 * s
hi <- max(max(sims), values$ci) + 3 * s
grid <- seq(lo, hi, length.out = 200)
charts[[1]] <- cs_chart("null", "null-distribution", "Cluster index under one Gaussian cloud", list(
x = cs_col("Cluster index", grid, "numeric"),
density = cs_col("Null density (normal fit)", stats::dnorm(grid, m, s), "numeric"),
observed = cs_col("Observed cluster index", rep(values$ci, length(grid)), "numeric"),
critical_low = cs_col("5% critical value", rep(stats::qnorm(0.05, m, s), length(grid)), "numeric")
), note = sprintf("Normal curve fitted to %d simulated cluster indices; a split far to the left of it is stronger than one cloud would give.", SIMS))
}
# %% Result
p <- values$p_empirical
verdict <- if (p < 0.05) "stronger than one Gaussian cloud would give" else "explained by one Gaussian cloud"
cs_publish(list(
title = "Is the split significant? (SigClust)",
engine = cs_engine_info("codesplashr", "nanoparquet"),
n = values$n,
summary = sprintf("%s has cluster index %.3f (null mean %.3f); p = %s: the split is %s.",
if (!is.null(SPLIT)) "The given split" else "The best 2-means split", values$ci, m, format(signif(p, 3)), verdict),
statistics = list(list(key = "ci", label = "Cluster index", value = values$ci),
list(key = "p_empirical", label = "p (simulated)", value = p, format = "p"),
list(key = "p_gaussian", label = "p (Gaussian fit)", value = values$p_gaussian, format = "p")),
tables = tables,
values = values,
charts = charts,
warnings = warnings
))
The best 2-means split has cluster index 0.579 (null mean 0.684); p = 0: the split is stronger than one Gaussian cloud would give.
- Cluster index
- 0.5792
- p (simulated)
- < .001
- p (Gaussian fit)
- < .001
To keep this page light, the plots are shown once, under the R tab.
Covariance eigenvalues: data and null
| Component | Data | Null (simulated) |
|---|---|---|
| 1 | 4.234 | 4.234 |
| 2 | 1.203 | 1.203 |
| 3 | 0.8151 | 1.147 |
| 4 | 0.7625 | 1.147 |
| 5 | 0.6405 | 1.147 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Is the split significant? (SigClust)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.sigclust 1.0.0 · spec 8d6ef312e2dcb35b
# Dataset: clu4_sigclust (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
from scipy.stats import norm
import codesplash as cs
from codesplash.errors import check_groups
from codesplash.ml import cluster_checks as ck
from codesplash.ml import cluster_compare as cc
from codesplash.ml import embed as csembed
from codesplash.stats.rng import Rng
# %% Data
FEATURES = ["c1", "c2", "c3", "c4", "c5"]
SPLIT = None # optional two-group column to test
SEED = 42
SIMS = 100
STARTS = 3
METHOD = "soft"
SCALE = "none"
cols = list(dict.fromkeys(FEATURES + ([SPLIT] if SPLIT else [])))
df = pd.read_parquet("tests/parity/fixtures/clu4_sigclust.parquet", columns=cols)
n_input = len(df)
cs.check_finite_columns(df, cols) # ±Inf stops with CS_E_NOT_FINITE in both engines
rows = csembed.complete_rows(df, cols)
warnings = []
if len(rows) < n_input:
warnings.append(f"{n_input - len(rows)} of {n_input} rows were left out because a value was missing.")
cs.check_rows(len(rows), 5, "SigClust")
X = csembed.numeric_matrix(df, FEATURES, rows)
if np.all(np.ptp(X, axis=0) == 0):
cs.cs_error("CS_E_CONSTANT", column=", ".join(FEATURES))
if SCALE == "standardize":
flat = np.ptp(X, axis=0) == 0
X = csembed.standardize(X, ddof=1)
X[:, flat] = 0.0 # constant columns exactly 0 in both engines
split = None
if SPLIT:
lab = cc.label_text(df[SPLIT].iloc[rows].tolist())
check_groups(pd.Series(lab, dtype=object), SPLIT, exactly=2)
levels = sorted(set(lab.tolist()))
split = np.array([levels.index(v) for v in lab], dtype=np.int64)
# %% SigClust
r = ck.sigclust(X, SIMS, STARTS, METHOD, Rng(SEED), split)
lab = np.asarray(r["labels"])
sizes = sorted([int(np.sum(lab == c)) for c in np.unique(lab)], reverse=True) + [0, 0]
values = {
"n": r["n"], "d": r["d"], "ci": r["ci"], "p_empirical": r["p_empirical"], "p_gaussian": r["p_gaussian"],
"sim_mean": r["sim_mean"], "sim_sd": r["sim_sd"], "sigma2_background": r["sigma2_background"], "tau": r["tau"],
"n_floored": r["n_floored"], "size_1": sizes[0], "size_2": sizes[1], "sims": SIMS,
}
if values["tau"] != values["tau"]:
warnings.append("Every eigenvalue is below the background noise level, so the null uses the noise level for all of them.")
eig = r["eigen"]
eig0 = r["eigen_null"]
tables = [{
"key": "eigenvalues",
"title": "Covariance eigenvalues: data and null",
"columns": [{"key": "component", "label": "Component", "type": "integer"},
{"key": "sample", "label": "Data", "type": "number"},
{"key": "null", "label": "Null (simulated)", "type": "number"}],
"rows": [{"component": j + 1, "sample": float(eig[j]), "null": float(eig0[j])} for j in range(min(len(eig), 50))],
}]
# %% Null distribution chart (normal fitted to the simulated cluster indices)
sims = r["sims"]
m, s = values["sim_mean"], values["sim_sd"]
charts = []
if s == s and s > 0:
lo = min(float(np.min(sims)), values["ci"]) - 3 * s
hi = max(float(np.max(sims)), values["ci"]) + 3 * s
grid = np.linspace(lo, hi, 200)
charts.append(cs.chart(
"null", "null-distribution", "Cluster index under one Gaussian cloud",
{
"x": cs.col("Cluster index", list(grid), "numeric"),
"density": cs.col("Null density (normal fit)", list(norm.pdf(grid, m, s)), "numeric"),
"observed": cs.col("Observed cluster index", [values["ci"]] * len(grid), "numeric"),
"critical_low": cs.col("5% critical value", [float(norm.ppf(0.05, m, s))] * len(grid), "numeric"),
},
note=f"Normal curve fitted to {SIMS} simulated cluster indices; a split far to the left of it is stronger than one cloud would give.",
))
# %% Result
p = values["p_empirical"]
verdict = "stronger than one Gaussian cloud would give" if p < 0.05 else "explained by one Gaussian cloud"
cs.publish({
"title": "Is the split significant? (SigClust)",
"engine": cs.engine_info("numpy", "scipy", "pandas"),
"n": values["n"],
"summary": f"{'The given split' if SPLIT else 'The best 2-means split'} has cluster index {values['ci']:.3f} (null mean {m:.3f}); p = {p:.3g}: the split is {verdict}.",
"statistics": [
{"key": "ci", "label": "Cluster index", "value": values["ci"]},
{"key": "p_empirical", "label": "p (simulated)", "value": p, "format": "p"},
{"key": "p_gaussian", "label": "p (Gaussian fit)", "value": values["p_gaussian"], "format": "p"},
],
"tables": tables,
"values": values,
"charts": charts,
"warnings": warnings,
})
View data
| t | density | observed | critical low | critical high |
|---|---|---|---|---|
| −4 | 0.0009 | 2.310 | −2.101 | 2.101 |
| −3.950 | 0.0010 | 2.310 | −2.101 | 2.101 |
| −3.900 | 0.0012 | 2.310 | −2.101 | 2.101 |
| −3.850 | 0.0013 | 2.310 | −2.101 | 2.101 |
| −3.800 | 0.0015 | 2.310 | −2.101 | 2.101 |
| −3.750 | 0.0016 | 2.310 | −2.101 | 2.101 |
| −3.700 | 0.0018 | 2.310 | −2.101 | 2.101 |
| −3.650 | 0.0020 | 2.310 | −2.101 | 2.101 |
| −3.600 | 0.0023 | 2.310 | −2.101 | 2.101 |
| −3.550 | 0.0025 | 2.310 | −2.101 | 2.101 |
| −3.500 | 0.0028 | 2.310 | −2.101 | 2.101 |
| −3.450 | 0.0032 | 2.310 | −2.101 | 2.101 |
| −3.400 | 0.0035 | 2.310 | −2.101 | 2.101 |
| −3.350 | 0.0039 | 2.310 | −2.101 | 2.101 |
| −3.300 | 0.0044 | 2.310 | −2.101 | 2.101 |
| −3.250 | 0.0049 | 2.310 | −2.101 | 2.101 |
| −3.200 | 0.0055 | 2.310 | −2.101 | 2.101 |
| −3.150 | 0.0061 | 2.310 | −2.101 | 2.101 |
| −3.100 | 0.0068 | 2.310 | −2.101 | 2.101 |
| −3.050 | 0.0075 | 2.310 | −2.101 | 2.101 |
| −3 | 0.0084 | 2.310 | −2.101 | 2.101 |
| −2.950 | 0.0093 | 2.310 | −2.101 | 2.101 |
| −2.900 | 0.0103 | 2.310 | −2.101 | 2.101 |
| −2.850 | 0.0114 | 2.310 | −2.101 | 2.101 |
| −2.800 | 0.0127 | 2.310 | −2.101 | 2.101 |
| −2.750 | 0.0141 | 2.310 | −2.101 | 2.101 |
| −2.700 | 0.0156 | 2.310 | −2.101 | 2.101 |
| −2.650 | 0.0172 | 2.310 | −2.101 | 2.101 |
| −2.600 | 0.0190 | 2.310 | −2.101 | 2.101 |
| −2.550 | 0.0210 | 2.310 | −2.101 | 2.101 |
| −2.500 | 0.0232 | 2.310 | −2.101 | 2.101 |
| −2.450 | 0.0256 | 2.310 | −2.101 | 2.101 |
| −2.400 | 0.0281 | 2.310 | −2.101 | 2.101 |
| −2.350 | 0.0310 | 2.310 | −2.101 | 2.101 |
| −2.300 | 0.0340 | 2.310 | −2.101 | 2.101 |
| −2.250 | 0.0374 | 2.310 | −2.101 | 2.101 |
| −2.200 | 0.0410 | 2.310 | −2.101 | 2.101 |
| −2.150 | 0.0449 | 2.310 | −2.101 | 2.101 |
| −2.100 | 0.0491 | 2.310 | −2.101 | 2.101 |
| −2.050 | 0.0536 | 2.310 | −2.101 | 2.101 |
| −2 | 0.0585 | 2.310 | −2.101 | 2.101 |
| −1.950 | 0.0637 | 2.310 | −2.101 | 2.101 |
| −1.900 | 0.0693 | 2.310 | −2.101 | 2.101 |
| −1.850 | 0.0753 | 2.310 | −2.101 | 2.101 |
| −1.800 | 0.0817 | 2.310 | −2.101 | 2.101 |
| −1.750 | 0.0884 | 2.310 | −2.101 | 2.101 |
| −1.700 | 0.0956 | 2.310 | −2.101 | 2.101 |
| −1.650 | 0.1032 | 2.310 | −2.101 | 2.101 |
| −1.600 | 0.1112 | 2.310 | −2.101 | 2.101 |
| −1.550 | 0.1197 | 2.310 | −2.101 | 2.101 |
| −1.500 | 0.1285 | 2.310 | −2.101 | 2.101 |
| −1.450 | 0.1378 | 2.310 | −2.101 | 2.101 |
| −1.400 | 0.1474 | 2.310 | −2.101 | 2.101 |
| −1.350 | 0.1574 | 2.310 | −2.101 | 2.101 |
| −1.300 | 0.1677 | 2.310 | −2.101 | 2.101 |
| −1.250 | 0.1784 | 2.310 | −2.101 | 2.101 |
| −1.200 | 0.1894 | 2.310 | −2.101 | 2.101 |
| −1.150 | 0.2006 | 2.310 | −2.101 | 2.101 |
| −1.100 | 0.2121 | 2.310 | −2.101 | 2.101 |
| −1.050 | 0.2237 | 2.310 | −2.101 | 2.101 |
First 60 of 161 rows.
And one stretched cloud. Its best split is still a split, but one Gaussian cloud of this shape gives splits that clean often:
The best 2-means split has cluster index 0.722 (null mean 0.734); p = 0.33: the split is explained by one Gaussian cloud.
- Cluster index
- 0.7215
- p (simulated)
- .330
- p (Gaussian fit)
- .345
Plots
Normal curve fitted to 100 simulated cluster indices; a split far to the left of it is stronger than one cloud would give.
View data
| 5% critical value | Null density (normal fit) | Observed cluster index | Cluster index |
|---|---|---|---|
| 0.6838 | 1.710e-5 | 0.7215 | 0.5758 |
| 0.6838 | 2.273e-5 | 0.7215 | 0.5774 |
| 0.6838 | 3.010e-5 | 0.7215 | 0.5791 |
| 0.6838 | 3.976e-5 | 0.7215 | 0.5808 |
| 0.6838 | 5.235e-5 | 0.7215 | 0.5824 |
| 0.6838 | 6.872e-5 | 0.7215 | 0.5841 |
| 0.6838 | 8.994e-5 | 0.7215 | 0.5858 |
| 0.6838 | 0.0001 | 0.7215 | 0.5874 |
| 0.6838 | 0.0002 | 0.7215 | 0.5891 |
| 0.6838 | 0.0002 | 0.7215 | 0.5907 |
| 0.6838 | 0.0003 | 0.7215 | 0.5924 |
| 0.6838 | 0.0003 | 0.7215 | 0.5941 |
| 0.6838 | 0.0004 | 0.7215 | 0.5957 |
| 0.6838 | 0.0005 | 0.7215 | 0.5974 |
| 0.6838 | 0.0007 | 0.7215 | 0.5991 |
| 0.6838 | 0.0009 | 0.7215 | 0.6007 |
| 0.6838 | 0.0011 | 0.7215 | 0.6024 |
| 0.6838 | 0.0014 | 0.7215 | 0.6041 |
| 0.6838 | 0.0018 | 0.7215 | 0.6057 |
| 0.6838 | 0.0023 | 0.7215 | 0.6074 |
| 0.6838 | 0.0028 | 0.7215 | 0.6090 |
| 0.6838 | 0.0035 | 0.7215 | 0.6107 |
| 0.6838 | 0.0044 | 0.7215 | 0.6124 |
| 0.6838 | 0.0055 | 0.7215 | 0.6140 |
| 0.6838 | 0.0068 | 0.7215 | 0.6157 |
| 0.6838 | 0.0084 | 0.7215 | 0.6174 |
| 0.6838 | 0.0104 | 0.7215 | 0.6190 |
| 0.6838 | 0.0128 | 0.7215 | 0.6207 |
| 0.6838 | 0.0156 | 0.7215 | 0.6224 |
| 0.6838 | 0.0191 | 0.7215 | 0.6240 |
| 0.6838 | 0.0233 | 0.7215 | 0.6257 |
| 0.6838 | 0.0282 | 0.7215 | 0.6273 |
| 0.6838 | 0.0342 | 0.7215 | 0.6290 |
| 0.6838 | 0.0412 | 0.7215 | 0.6307 |
| 0.6838 | 0.0496 | 0.7215 | 0.6323 |
| 0.6838 | 0.0595 | 0.7215 | 0.6340 |
| 0.6838 | 0.0711 | 0.7215 | 0.6357 |
| 0.6838 | 0.0848 | 0.7215 | 0.6373 |
| 0.6838 | 0.1008 | 0.7215 | 0.6390 |
| 0.6838 | 0.1195 | 0.7215 | 0.6407 |
| 0.6838 | 0.1411 | 0.7215 | 0.6423 |
| 0.6838 | 0.1662 | 0.7215 | 0.6440 |
| 0.6838 | 0.1952 | 0.7215 | 0.6456 |
| 0.6838 | 0.2286 | 0.7215 | 0.6473 |
| 0.6838 | 0.2668 | 0.7215 | 0.6490 |
| 0.6838 | 0.3105 | 0.7215 | 0.6506 |
| 0.6838 | 0.3603 | 0.7215 | 0.6523 |
| 0.6838 | 0.4168 | 0.7215 | 0.6540 |
| 0.6838 | 0.4808 | 0.7215 | 0.6556 |
| 0.6838 | 0.5528 | 0.7215 | 0.6573 |
| 0.6838 | 0.6337 | 0.7215 | 0.6590 |
| 0.6838 | 0.7244 | 0.7215 | 0.6606 |
| 0.6838 | 0.8254 | 0.7215 | 0.6623 |
| 0.6838 | 0.9378 | 0.7215 | 0.6640 |
| 0.6838 | 1.062 | 0.7215 | 0.6656 |
| 0.6838 | 1.200 | 0.7215 | 0.6673 |
| 0.6838 | 1.351 | 0.7215 | 0.6689 |
| 0.6838 | 1.516 | 0.7215 | 0.6706 |
| 0.6838 | 1.697 | 0.7215 | 0.6723 |
| 0.6838 | 1.893 | 0.7215 | 0.6739 |
First 60 of 200 rows.
Covariance eigenvalues: data and null
| Component | Data | Null (simulated) |
|---|---|---|
| 1 | 3.409 | 3.409 |
| 2 | 1.487 | 1.487 |
| 3 | 1.158 | 1.257 |
| 4 | 1.102 | 1.257 |
| 5 | 0.7429 | 1.257 |
The exact R script · R R version 4.5.1 (2025-06-13)
# Is the split significant? (SigClust)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.sigclust 1.0.0 · spec 998fdf91be44d712
# Dataset: clu4_sigclust (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
FEATURES <- c("g1", "g2", "g3", "g4", "g5")
SPLIT <- NULL # optional two-group column to test
SEED <- 42
SIMS <- 100
STARTS <- 3
METHOD <- "soft"
SCALE <- "none"
cols <- unique(c(FEATURES, if (!is.null(SPLIT)) SPLIT))
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/clu4_sigclust.parquet", col_select = cols))
n_input <- nrow(df)
cs_check_finite_columns(df, cols) # ±Inf stops with CS_E_NOT_FINITE in both engines
rows <- cs_ml_complete_rows(df, cols)
warnings <- list()
if (length(rows) < n_input) warnings <- c(warnings, sprintf("%d of %d rows were left out because a value was missing.", n_input - length(rows), n_input))
cs_check_rows(length(rows), 5, "SigClust")
X <- cs_ml_numeric_matrix(df, FEATURES, rows)
if (all(apply(X, 2, function(v) max(v) - min(v)) == 0)) cs_error("CS_E_CONSTANT", column = paste(FEATURES, collapse = ", "))
if (SCALE == "standardize") {
flat <- apply(X, 2, function(v) max(v) - min(v)) == 0
s <- apply(X, 2, stats::sd)
s[flat] <- 1
X <- sweep(sweep(X, 2, colMeans(X)), 2, s, "/")
X[, flat] <- 0 # constant columns exactly 0 in both engines
}
split <- NULL
if (!is.null(SPLIT)) {
lab <- cs_ml_label_text(df[[SPLIT]][rows + 1L])
cs_check_groups(lab, SPLIT, exactly = 2)
levels <- sort(unique(lab), method = "radix")
split <- match(lab, levels) - 1L
}
# %% SigClust
r <- cs_ml_sigclust(X, SIMS, STARTS, METHOD, cs_rng(SEED), split)
lab <- r$labels
sizes <- c(sort(as.integer(table(lab)), decreasing = TRUE), 0L, 0L)
values <- list(n = r$n, d = r$d, ci = r$ci, p_empirical = r$p_empirical, p_gaussian = r$p_gaussian,
sim_mean = r$sim_mean, sim_sd = r$sim_sd, sigma2_background = r$sigma2_background, tau = r$tau,
n_floored = r$n_floored, size_1 = sizes[1], size_2 = sizes[2], sims = SIMS)
if (is.nan(values$tau)) warnings <- c(warnings, "Every eigenvalue is below the background noise level, so the null uses the noise level for all of them.")
eig <- r$eigen
eig0 <- r$eigen_null
tables <- list(list(key = "eigenvalues", title = "Covariance eigenvalues: data and null",
columns = list(list(key = "component", label = "Component", type = "integer"),
list(key = "sample", label = "Data", type = "number"),
list(key = "null", label = "Null (simulated)", type = "number")),
rows = lapply(seq_len(min(length(eig), 50)), function(j) list(component = j, sample = eig[j], null = eig0[j]))))
# %% Null distribution chart (normal fitted to the simulated cluster indices)
sims <- r$sims
m <- values$sim_mean
s <- values$sim_sd
charts <- list()
if (is.finite(s) && s > 0) {
lo <- min(min(sims), values$ci) - 3 * s
hi <- max(max(sims), values$ci) + 3 * s
grid <- seq(lo, hi, length.out = 200)
charts[[1]] <- cs_chart("null", "null-distribution", "Cluster index under one Gaussian cloud", list(
x = cs_col("Cluster index", grid, "numeric"),
density = cs_col("Null density (normal fit)", stats::dnorm(grid, m, s), "numeric"),
observed = cs_col("Observed cluster index", rep(values$ci, length(grid)), "numeric"),
critical_low = cs_col("5% critical value", rep(stats::qnorm(0.05, m, s), length(grid)), "numeric")
), note = sprintf("Normal curve fitted to %d simulated cluster indices; a split far to the left of it is stronger than one cloud would give.", SIMS))
}
# %% Result
p <- values$p_empirical
verdict <- if (p < 0.05) "stronger than one Gaussian cloud would give" else "explained by one Gaussian cloud"
cs_publish(list(
title = "Is the split significant? (SigClust)",
engine = cs_engine_info("codesplashr", "nanoparquet"),
n = values$n,
summary = sprintf("%s has cluster index %.3f (null mean %.3f); p = %s: the split is %s.",
if (!is.null(SPLIT)) "The given split" else "The best 2-means split", values$ci, m, format(signif(p, 3)), verdict),
statistics = list(list(key = "ci", label = "Cluster index", value = values$ci),
list(key = "p_empirical", label = "p (simulated)", value = p, format = "p"),
list(key = "p_gaussian", label = "p (Gaussian fit)", value = values$p_gaussian, format = "p")),
tables = tables,
values = values,
charts = charts,
warnings = warnings
))
The best 2-means split has cluster index 0.722 (null mean 0.734); p = 0.33: the split is explained by one Gaussian cloud.
- Cluster index
- 0.7215
- p (simulated)
- .330
- p (Gaussian fit)
- .345
To keep this page light, the plots are shown once, under the R tab.
Covariance eigenvalues: data and null
| Component | Data | Null (simulated) |
|---|---|---|
| 1 | 3.409 | 3.409 |
| 2 | 1.487 | 1.487 |
| 3 | 1.158 | 1.257 |
| 4 | 1.102 | 1.257 |
| 5 | 0.7429 | 1.257 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Is the split significant? (SigClust)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.sigclust 1.0.0 · spec 998fdf91be44d712
# Dataset: clu4_sigclust (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
from scipy.stats import norm
import codesplash as cs
from codesplash.errors import check_groups
from codesplash.ml import cluster_checks as ck
from codesplash.ml import cluster_compare as cc
from codesplash.ml import embed as csembed
from codesplash.stats.rng import Rng
# %% Data
FEATURES = ["g1", "g2", "g3", "g4", "g5"]
SPLIT = None # optional two-group column to test
SEED = 42
SIMS = 100
STARTS = 3
METHOD = "soft"
SCALE = "none"
cols = list(dict.fromkeys(FEATURES + ([SPLIT] if SPLIT else [])))
df = pd.read_parquet("tests/parity/fixtures/clu4_sigclust.parquet", columns=cols)
n_input = len(df)
cs.check_finite_columns(df, cols) # ±Inf stops with CS_E_NOT_FINITE in both engines
rows = csembed.complete_rows(df, cols)
warnings = []
if len(rows) < n_input:
warnings.append(f"{n_input - len(rows)} of {n_input} rows were left out because a value was missing.")
cs.check_rows(len(rows), 5, "SigClust")
X = csembed.numeric_matrix(df, FEATURES, rows)
if np.all(np.ptp(X, axis=0) == 0):
cs.cs_error("CS_E_CONSTANT", column=", ".join(FEATURES))
if SCALE == "standardize":
flat = np.ptp(X, axis=0) == 0
X = csembed.standardize(X, ddof=1)
X[:, flat] = 0.0 # constant columns exactly 0 in both engines
split = None
if SPLIT:
lab = cc.label_text(df[SPLIT].iloc[rows].tolist())
check_groups(pd.Series(lab, dtype=object), SPLIT, exactly=2)
levels = sorted(set(lab.tolist()))
split = np.array([levels.index(v) for v in lab], dtype=np.int64)
# %% SigClust
r = ck.sigclust(X, SIMS, STARTS, METHOD, Rng(SEED), split)
lab = np.asarray(r["labels"])
sizes = sorted([int(np.sum(lab == c)) for c in np.unique(lab)], reverse=True) + [0, 0]
values = {
"n": r["n"], "d": r["d"], "ci": r["ci"], "p_empirical": r["p_empirical"], "p_gaussian": r["p_gaussian"],
"sim_mean": r["sim_mean"], "sim_sd": r["sim_sd"], "sigma2_background": r["sigma2_background"], "tau": r["tau"],
"n_floored": r["n_floored"], "size_1": sizes[0], "size_2": sizes[1], "sims": SIMS,
}
if values["tau"] != values["tau"]:
warnings.append("Every eigenvalue is below the background noise level, so the null uses the noise level for all of them.")
eig = r["eigen"]
eig0 = r["eigen_null"]
tables = [{
"key": "eigenvalues",
"title": "Covariance eigenvalues: data and null",
"columns": [{"key": "component", "label": "Component", "type": "integer"},
{"key": "sample", "label": "Data", "type": "number"},
{"key": "null", "label": "Null (simulated)", "type": "number"}],
"rows": [{"component": j + 1, "sample": float(eig[j]), "null": float(eig0[j])} for j in range(min(len(eig), 50))],
}]
# %% Null distribution chart (normal fitted to the simulated cluster indices)
sims = r["sims"]
m, s = values["sim_mean"], values["sim_sd"]
charts = []
if s == s and s > 0:
lo = min(float(np.min(sims)), values["ci"]) - 3 * s
hi = max(float(np.max(sims)), values["ci"]) + 3 * s
grid = np.linspace(lo, hi, 200)
charts.append(cs.chart(
"null", "null-distribution", "Cluster index under one Gaussian cloud",
{
"x": cs.col("Cluster index", list(grid), "numeric"),
"density": cs.col("Null density (normal fit)", list(norm.pdf(grid, m, s)), "numeric"),
"observed": cs.col("Observed cluster index", [values["ci"]] * len(grid), "numeric"),
"critical_low": cs.col("5% critical value", [float(norm.ppf(0.05, m, s))] * len(grid), "numeric"),
},
note=f"Normal curve fitted to {SIMS} simulated cluster indices; a split far to the left of it is stronger than one cloud would give.",
))
# %% Result
p = values["p_empirical"]
verdict = "stronger than one Gaussian cloud would give" if p < 0.05 else "explained by one Gaussian cloud"
cs.publish({
"title": "Is the split significant? (SigClust)",
"engine": cs.engine_info("numpy", "scipy", "pandas"),
"n": values["n"],
"summary": f"{'The given split' if SPLIT else 'The best 2-means split'} has cluster index {values['ci']:.3f} (null mean {m:.3f}); p = {p:.3g}: the split is {verdict}.",
"statistics": [
{"key": "ci", "label": "Cluster index", "value": values["ci"]},
{"key": "p_empirical", "label": "p (simulated)", "value": p, "format": "p"},
{"key": "p_gaussian", "label": "p (Gaussian fit)", "value": values["p_gaussian"], "format": "p"},
],
"tables": tables,
"values": values,
"charts": charts,
"warnings": warnings,
})
Testing what you just found
ReadAfter clustering, it is tempting to run a t-test or χ² test on the clusters. That is double dippingDouble dippingTesting differences between groups that were created from the same rows; the tests come out optimistic.: the clusters were chosen to look different, so the test rejects even on pure noise.
The selective p-valueSelective p-valueA p-value that conditions on how the clusters were chosen, so it stays valid when the same data formed them. of Gao, Bien and Witten asks a narrower question: among data sets that would have produced these same two clusters, how unusual is the distance between their means? CodeSplash estimates it by moving the two clusters apart or together and re-running the clustering for each draw.
The same single cloud, cut into three clusters by average linkage:
3 pair(s) of 3 clusters (average linkage) tested; clusters 1 and 2: selective p = 0.612 (naive p = 9.48e-12).
- Selective p (1 vs 2)
- .612
- Naive p (1 vs 2)
- < .001
Plots
The naive p ignores that the clusters were found in the same data; the selective p accounts for it.
View data
| Clusters | Test | p-value |
|---|---|---|
| 1 vs 2 | Naive | 9.480e-12 |
| 1 vs 2 | Selective | 0.6123 |
| 1 vs 3 | Naive | 0.0062 |
| 1 vs 3 | Selective | 0.2694 |
| 2 vs 3 | Naive | 1.301e-7 |
| 2 vs 3 | Selective | 0.0817 |
Difference in means for each pair of clusters
| Clusters | Rows (first) | Rows (second) | Distance between means | Naive p | Selective p | Draws kept | Effective draws |
|---|---|---|---|---|---|---|---|
| 1 vs 2 | 71 | 8 | 3.647 | 9.480e-12 | 0.6123 | 156 | 33.510 |
| 1 vs 3 | 71 | 1 | 5.100 | 0.0062 | 0.2694 | 200 | 78.212 |
| 2 vs 3 | 8 | 1 | 8.462 | 1.301e-7 | 0.0817 | 214 | 45.340 |
The exact R script · R R version 4.5.1 (2025-06-13)
# Are these clusters really different? (selective inference)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.cluster_inference 1.0.0 · spec 12586d9a59e1c47d
# Dataset: clu4_sigclust (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
FEATURES <- c("g1", "g2", "g3", "g4", "g5")
SEED <- 42
LINKAGE <- "average"
K <- 3
DRAWS <- 300
SCALE <- "none"
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/clu4_sigclust.parquet", col_select = FEATURES))
n_input <- nrow(df)
cs_check_finite_columns(df, FEATURES) # ±Inf stops with CS_E_NOT_FINITE in both engines
rows <- cs_ml_complete_rows(df, FEATURES)
warnings <- list()
if (length(rows) < n_input) warnings <- c(warnings, sprintf("%d of %d rows were left out because a value was missing.", n_input - length(rows), n_input))
cs_check_rows(length(rows), K + 2, "Selective inference after clustering")
X <- cs_ml_numeric_matrix(df, FEATURES, rows)
if (all(apply(X, 2, function(v) max(v) - min(v)) == 0)) cs_error("CS_E_CONSTANT", column = paste(FEATURES, collapse = ", "))
if (SCALE == "standardize") {
flat <- apply(X, 2, function(v) max(v) - min(v)) == 0
s <- apply(X, 2, stats::sd)
s[flat] <- 1
X <- sweep(sweep(X, 2, colMeans(X)), 2, s, "/")
X[, flat] <- 0 # constant columns exactly 0 in both engines
}
# %% Clusters and the noise SD
labels <- cs_ml_canonical(cs_ml_hclust_cut(X, LINKAGE, K))
k_found <- max(labels)
if (k_found < 2) cs_error("CS_E_UNDEFINED", what = "Selective inference", reason = "the tree has fewer than two clusters at this cut")
sigma <- cs_ml_pooled_sigma(X)
# %% Selective p-value for every pair (shared stream, pair by pair)
rng <- cs_rng(SEED)
pairs <- list()
values <- list(n = length(rows), q = ncol(X), k = k_found, sigma = sigma)
for (a in seq_len(k_found)) {
for (b in seq_len(k_found)) {
if (b <= a) next
res <- cs_ml_selective_pair(X, labels == a, labels == b, LINKAGE, K, sigma, DRAWS, rng)
pairs[[length(pairs) + 1L]] <- list(a = a, b = b, r = res)
values[[sprintf("p_selective[%d-%d]", a, b)]] <- res$p_selective
values[[sprintf("p_naive[%d-%d]", a, b)]] <- res$p_naive
}
}
first <- pairs[[1]]$r
psel <- vapply(pairs, function(x) x$r$p_selective, numeric(1))
values$n_pairs <- length(pairs)
values$p_selective <- first$p_selective
values$p_naive <- first$p_naive
values$distance <- first$stat
values$kept <- first$kept
values$ess <- first$ess
values["min_p_selective"] <- list(if (any(!is.nan(psel))) min(psel[!is.nan(psel)]) else NULL)
pair_name <- function(x, sep = "–") sprintf("%d%s%d", x$a, sep, x$b)
low_ess <- vapply(Filter(function(x) x$r$kept > 0 && x$r$ess < 20, pairs), pair_name, character(1))
if (length(low_ess)) warnings <- c(warnings, paste0("Few effective draws for pair(s) ", paste(low_ess, collapse = ", "), "; raise the number of draws for a steadier p-value."))
none_kept <- vapply(Filter(function(x) x$r$kept == 0, pairs), pair_name, character(1))
if (length(none_kept)) warnings <- c(warnings, paste0("No draw reproduced pair(s) ", paste(none_kept, collapse = ", "), "; their selective p-value is undefined at this number of draws."))
tables <- list(list(
key = "pairs", title = "Difference in means for each pair of clusters",
columns = list(
list(key = "pair", label = "Clusters", type = "string"),
list(key = "n_a", label = "Rows (first)", type = "integer"),
list(key = "n_b", label = "Rows (second)", type = "integer"),
list(key = "distance", label = "Distance between means", type = "number"),
list(key = "p_naive", label = "Naive p", type = "p"),
list(key = "p_selective", label = "Selective p", type = "p"),
list(key = "kept", label = "Draws kept", type = "integer"),
list(key = "ess", label = "Effective draws", type = "number")
),
rows = lapply(pairs, function(x) list(pair = sprintf("%d vs %d", x$a, x$b), n_a = x$r$n1, n_b = x$r$n2, distance = x$r$stat,
p_naive = x$r$p_naive, p_selective = x$r$p_selective, kept = x$r$kept, ess = x$r$ess))
))
# %% Chart: naive vs selective p-values
cats <- character(0)
vals <- numeric(0)
grp <- character(0)
for (x in pairs) {
for (g in list(c("Naive", "p_naive"), c("Selective", "p_selective"))) {
v <- x$r[[g[2]]]
if (!is.nan(v)) {
cats <- c(cats, sprintf("%d vs %d", x$a, x$b))
vals <- c(vals, v)
grp <- c(grp, g[1])
}
}
}
charts <- list(cs_chart("pvalues", "cleveland-dot", "Naive and selective p-values by pair", list(
category = cs_col("Clusters", cats, "categorical", levels = vapply(pairs, function(x) sprintf("%d vs %d", x$a, x$b), character(1))),
value = cs_col("p-value", vals, "numeric"),
group = cs_col("Test", grp, "categorical", levels = c("Naive", "Selective"))
), note = "The naive p ignores that the clusters were found in the same data; the selective p accounts for it."))
# %% Result
ps <- first$p_selective
cs_publish(list(
title = "Are these clusters really different? (selective inference)",
engine = cs_engine_info("codesplashr", "nanoparquet"),
n = length(rows),
summary = sprintf("%d pair(s) of %d clusters (%s linkage) tested; clusters 1 and 2: selective p = %s (naive p = %s).",
length(pairs), k_found, LINKAGE, if (is.nan(ps)) "undefined" else format(signif(ps, 3)), format(signif(first$p_naive, 3))),
statistics = list(list(key = "p_selective", label = "Selective p (1 vs 2)", value = ps, format = "p"),
list(key = "p_naive", label = "Naive p (1 vs 2)", value = first$p_naive, format = "p")),
tables = tables,
values = values,
charts = charts,
warnings = warnings
))
3 pair(s) of 3 clusters (average linkage) tested; clusters 1 and 2: selective p = 0.612 (naive p = 9.48e-12).
- Selective p (1 vs 2)
- .612
- Naive p (1 vs 2)
- < .001
To keep this page light, the plots are shown once, under the R tab.
Difference in means for each pair of clusters
| Clusters | Rows (first) | Rows (second) | Distance between means | Naive p | Selective p | Draws kept | Effective draws |
|---|---|---|---|---|---|---|---|
| 1 vs 2 | 71 | 8 | 3.647 | 9.480e-12 | 0.6123 | 156 | 33.510 |
| 1 vs 3 | 71 | 1 | 5.100 | 0.0062 | 0.2694 | 200 | 78.212 |
| 2 vs 3 | 8 | 1 | 8.462 | 1.301e-7 | 0.0817 | 214 | 45.340 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Are these clusters really different? (selective inference)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.cluster_inference 1.0.0 · spec 12586d9a59e1c47d
# Dataset: clu4_sigclust (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 as csc
from codesplash.ml import cluster_checks as ck
from codesplash.ml import embed as csembed
from codesplash.stats.rng import Rng
# %% Data
FEATURES = ["g1", "g2", "g3", "g4", "g5"]
SEED = 42
LINKAGE = "average"
K = 3
DRAWS = 300
SCALE = "none"
df = pd.read_parquet("tests/parity/fixtures/clu4_sigclust.parquet", columns=FEATURES)
n_input = len(df)
cs.check_finite_columns(df, FEATURES) # ±Inf stops with CS_E_NOT_FINITE in both engines
rows = csembed.complete_rows(df, FEATURES)
warnings = []
if len(rows) < n_input:
warnings.append(f"{n_input - len(rows)} of {n_input} rows were left out because a value was missing.")
cs.check_rows(len(rows), K + 2, "Selective inference after clustering")
X = csembed.numeric_matrix(df, FEATURES, rows)
if np.all(np.ptp(X, axis=0) == 0):
cs.cs_error("CS_E_CONSTANT", column=", ".join(FEATURES))
if SCALE == "standardize":
flat = np.ptp(X, axis=0) == 0
X = csembed.standardize(X, ddof=1)
X[:, flat] = 0.0 # constant columns exactly 0 in both engines
# %% Clusters and the noise SD
labels = csc.canonical(ck.hclust_cut(X, LINKAGE, K))
k_found = int(labels.max())
if k_found < 2:
cs.cs_error("CS_E_UNDEFINED", what="Selective inference", reason="the tree has fewer than two clusters at this cut")
sigma = ck.pooled_sigma(X)
# %% Selective p-value for every pair (shared stream, pair by pair)
rng = Rng(SEED)
pairs = []
values = {"n": len(rows), "q": X.shape[1], "k": k_found, "sigma": sigma}
for a in range(1, k_found + 1):
for b in range(a + 1, k_found + 1):
res = ck.selective_pair(X, labels == a, labels == b, LINKAGE, K, sigma, DRAWS, rng)
pairs.append((a, b, res))
values[f"p_selective[{a}-{b}]"] = res["p_selective"]
values[f"p_naive[{a}-{b}]"] = res["p_naive"]
first = pairs[0][2]
values.update({
"n_pairs": len(pairs), "p_selective": first["p_selective"], "p_naive": first["p_naive"], "distance": first["stat"],
"kept": first["kept"], "ess": first["ess"],
"min_p_selective": min((r["p_selective"] for _, _, r in pairs if r["p_selective"] == r["p_selective"]), default=None),
})
low_ess = [f"{a}–{b}" for a, b, r in pairs if r["kept"] > 0 and r["ess"] < 20]
if low_ess:
warnings.append("Few effective draws for pair(s) " + ", ".join(low_ess) + "; raise the number of draws for a steadier p-value.")
none_kept = [f"{a}–{b}" for a, b, r in pairs if r["kept"] == 0]
if none_kept:
warnings.append("No draw reproduced pair(s) " + ", ".join(none_kept) + "; their selective p-value is undefined at this number of draws.")
tables = [{
"key": "pairs",
"title": "Difference in means for each pair of clusters",
"columns": [
{"key": "pair", "label": "Clusters", "type": "string"},
{"key": "n_a", "label": "Rows (first)", "type": "integer"},
{"key": "n_b", "label": "Rows (second)", "type": "integer"},
{"key": "distance", "label": "Distance between means", "type": "number"},
{"key": "p_naive", "label": "Naive p", "type": "p"},
{"key": "p_selective", "label": "Selective p", "type": "p"},
{"key": "kept", "label": "Draws kept", "type": "integer"},
{"key": "ess", "label": "Effective draws", "type": "number"},
],
"rows": [
{"pair": f"{a} vs {b}", "n_a": r["n1"], "n_b": r["n2"], "distance": r["stat"], "p_naive": r["p_naive"],
"p_selective": r["p_selective"], "kept": r["kept"], "ess": r["ess"]}
for a, b, r in pairs
],
}]
# %% Chart: naive vs selective p-values
cats, vals, grp = [], [], []
for a, b, r in pairs:
for label, key in (("Naive", "p_naive"), ("Selective", "p_selective")):
if r[key] == r[key]:
cats.append(f"{a} vs {b}")
vals.append(r[key])
grp.append(label)
charts = [cs.chart(
"pvalues", "cleveland-dot", "Naive and selective p-values by pair",
{
"category": cs.col("Clusters", cats, "categorical", levels=[f"{a} vs {b}" for a, b, _ in pairs]),
"value": cs.col("p-value", vals, "numeric"),
"group": cs.col("Test", grp, "categorical", levels=["Naive", "Selective"]),
},
note="The naive p ignores that the clusters were found in the same data; the selective p accounts for it.",
)]
# %% Result
ps = first["p_selective"]
cs.publish({
"title": "Are these clusters really different? (selective inference)",
"engine": cs.engine_info("scipy", "numpy", "pandas"),
"n": len(rows),
"summary": (
f"{len(pairs)} pair(s) of {k_found} clusters ({LINKAGE} linkage) tested; clusters 1 and 2: selective p = "
+ (f"{ps:.3g}" if ps == ps else "undefined") + f" (naive p = {first['p_naive']:.3g})."
),
"statistics": [
{"key": "p_selective", "label": "Selective p (1 vs 2)", "value": ps, "format": "p"},
{"key": "p_naive", "label": "Naive p (1 vs 2)", "value": first["p_naive"], "format": "p"},
],
"tables": tables,
"values": values,
"charts": charts,
"warnings": warnings,
})
View data
| country | life_expectancy | sex |
|---|---|---|
| Japan | 83.300 | Male |
| Japan | 85.300 | Female |
| Japan | 82.600 | Male |
| Japan | 89.100 | Female |
| Japan | 81.200 | Male |
| Japan | 89.100 | Female |
| Japan | 83.500 | Male |
| Japan | 85.700 | Female |
| Japan | 79.900 | Male |
| Japan | 87.400 | Female |
| Japan | 83.800 | Male |
| Japan | 89.500 | Female |
| Japan | 80.600 | Male |
| Japan | 86.500 | Female |
| Japan | 84.200 | Male |
| Japan | 87.600 | Female |
| Japan | 82.100 | Male |
| Japan | 87.600 | Female |
| Japan | 82.800 | Male |
| Japan | 88.500 | Female |
| Japan | 83.800 | Male |
| Japan | 87.400 | Female |
| Japan | 83.400 | Male |
| Japan | 86.300 | Female |
| Japan | 81.900 | Male |
| Japan | 86.700 | Female |
| Japan | 80.800 | Male |
| Japan | 87.100 | Female |
| Japan | 81.500 | Male |
| Japan | 86.700 | Female |
| Japan | 81.100 | Male |
| Japan | 86 | Female |
| Japan | 83.900 | Male |
| Japan | 87.900 | Female |
| Japan | 81.300 | Male |
| Japan | 87.200 | Female |
| Japan | 81.300 | Male |
| Japan | 85.200 | Female |
| Japan | 85.100 | Male |
| Japan | 85.500 | Female |
| Spain | 78 | Male |
| Spain | 86.200 | Female |
| Spain | 80.800 | Male |
| Spain | 86.400 | Female |
| Spain | 81.100 | Male |
| Spain | 85.200 | Female |
| Spain | 82 | Male |
| Spain | 85.500 | Female |
| Spain | 80.700 | Male |
| Spain | 86.700 | Female |
| Spain | 83 | Male |
| Spain | 86.700 | Female |
| Spain | 77.900 | Male |
| Spain | 85.800 | Female |
| Spain | 82.300 | Male |
| Spain | 85.700 | Female |
| Spain | 81.100 | Male |
| Spain | 89.200 | Female |
| Spain | 81.800 | Male |
| Spain | 87.400 | Female |
First 60 of 480 rows.
Every naive pNaive p-value (after clustering)The χ² test of a difference in cluster means that ignores that the clusters were found in the same data; far too small. is essentially zero, as if the clusters were real. The selective p-values are not small: one cloud explains these clusters.
Do two clusterings agree?
ReadTo compare a clustering with known groups, or two clusterings, use adjusted Rand indexAdjusted Rand index (partitions)Pair-counting agreement of two partitions, corrected so chance agreement is 0 and identical partitions 1. or adjusted mutual informationAdjusted mutual informationShared information of two partitions corrected for chance: 0 = chance, 1 = identical; fair across group counts.: both are 0 for chance agreement and 1 for identical partitions. 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 (0 = identical). PurityPurityShare of rows that sit in the majority reference group of their judged group; inverse purity swaps the roles. is easy to read but rewards many tiny groups.
DBSCAN marks unclustered rows as noise (−1). How those rows count changes every score, so say which convention you used. Kept as one more group:
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,
})
View data
| species | cluster | flowers |
|---|---|---|
| setosa | Cluster 1 | 50 |
| versicolor | Cluster 2 | 41 |
| versicolor | Cluster 3 | 6 |
| versicolor | noise | 3 |
| virginica | Cluster 3 | 36 |
| virginica | Cluster 2 | 12 |
| virginica | noise | 2 |
Left out:
species (3 groups) and db (2 groups) are in substantial agreement: ARI 0.63, AMI 0.76, VI 0.42 nats.
- Adjusted Rand index
- 0.6309
- Adjusted mutual information
- 0.7578
- Variation of information (nats)
- 0.4213
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 |
|---|---|---|---|
| 0 | 45 | setosa | 45 |
| 1 | 0 | setosa | 0 |
| 0 | 0 | versicolor | 0 |
| 1 | 39 | versicolor | 39 |
| 0 | 0 | virginica | 0 |
| 1 | 32 | virginica | 32 |
View data
| Rows | species | db |
|---|---|---|
| 45 | setosa | 0 |
| 39 | versicolor | 1 |
| 32 | virginica | 1 |
Agreement indices
| Index | Value | Reading |
|---|---|---|
| Adjusted Rand index | 0.6309 | 0 = chance, 1 = identical |
| Adjusted mutual information | 0.7578 | 0 = chance, 1 = identical |
| Normalized mutual information | 0.7602 | 0 to 1; not chance-corrected |
| Variation of information (nats) | 0.4213 | 0 = identical; a distance |
| Normalized variation of information | 0.3868 | 0 = identical, 1 = unrelated |
| Fowlkes–Mallows | 0.8005 | 0 to 1 |
| Rand index | 0.8129 | 0 to 1; not chance-corrected |
| Pair Jaccard | 0.6409 | 0 to 1 |
| Homogeneity | 0.6132 | 1 = each judged group holds one reference group |
| Completeness | 1 | 1 = each reference group sits in one judged group |
| V-measure | 0.7602 | harmonic mean of the two above |
| Purity | 0.7241 | share of rows in the majority reference group of their judged group |
| Inverse purity | 1 | the same with the roles swapped |
Rows by species (rows) and db (columns)
| species | 0 | 1 | Total |
|---|---|---|---|
| setosa | 45 | 0 | 45 |
| versicolor | 0 | 39 | 39 |
| virginica | 0 | 32 | 32 |
- 34 row(s) carry the noise label '-1'; they were left out.
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 9d87c01f62dff28f
# 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 <- "drop"
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 (2 groups) are in substantial agreement: ARI 0.63, AMI 0.76, VI 0.42 nats.
- Adjusted Rand index
- 0.6309
- Adjusted mutual information
- 0.7578
- Variation of information (nats)
- 0.4213
To keep this page light, the plots are shown once, under the R tab.
Agreement indices
| Index | Value | Reading |
|---|---|---|
| Adjusted Rand index | 0.6309 | 0 = chance, 1 = identical |
| Adjusted mutual information | 0.7578 | 0 = chance, 1 = identical |
| Normalized mutual information | 0.7602 | 0 to 1; not chance-corrected |
| Variation of information (nats) | 0.4213 | 0 = identical; a distance |
| Normalized variation of information | 0.3868 | 0 = identical, 1 = unrelated |
| Fowlkes–Mallows | 0.8005 | 0 to 1 |
| Rand index | 0.8129 | 0 to 1; not chance-corrected |
| Pair Jaccard | 0.6409 | 0 to 1 |
| Homogeneity | 0.6132 | 1 = each judged group holds one reference group |
| Completeness | 1 | 1 = each reference group sits in one judged group |
| V-measure | 0.7602 | harmonic mean of the two above |
| Purity | 0.7241 | share of rows in the majority reference group of their judged group |
| Inverse purity | 1 | the same with the roles swapped |
Rows by species (rows) and db (columns)
| species | 0 | 1 | Total |
|---|---|---|---|
| setosa | 45 | 0 | 45 |
| versicolor | 0 | 39 | 39 |
| virginica | 0 | 32 | 32 |
- 34 row(s) carry the noise label '-1'; they were left out.
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 9d87c01f62dff28f
# 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 = "drop"
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,
})
Dropping the noise rows scores only the rows DBSCAN was confident about, so the agreement looks better. Neither is wrong; they answer different questions.
Do two maps agree?
ReadTwo embeddings of the same rows (PCA and UMAP, or two seeds) can agree globally and still disagree locally. Centered kernel alignmentCentered kernel alignmentSimilarity of two embeddings of the same rows: 1 = same up to rotation and overall scale, near 0 = unrelated. and ProcrustesProcrustes disparitySquared mismatch left after shifting, rotating, reflecting and rescaling one embedding onto the other; 0 = identical. judge the overall layout; kNN overlapkNN overlapAverage share of each row's k nearest neighbors that both embeddings agree on: local agreement. asks whether each row keeps its nearest neighbors.
A PCA map against the same map with noise added:
Linear CKA 0.96, RBF CKA 0.94, Procrustes r 0.98; 32% of each row's 5 nearest neighbors agree.
- Linear CKA
- 0.9628
- Procrustes r
- 0.9766
- kNN overlap
- 31.5%
Agreement between the embeddings
| Index | Value | Reading |
|---|---|---|
| Linear CKA (RV coefficient) | 0.9628 | 1 = same up to rotation and scale |
| Debiased linear CKA | 0.9627 | corrects the upward bias with few rows or many columns |
| RBF CKA | 0.9371 | more weight on local structure |
| Procrustes disparity | 0.0463 | 0 = same up to shift, rotation and scale |
| Procrustes r | 0.9766 | √(1 − disparity) |
| kNN overlap (k = 5) | 0.3154 | share of shared nearest neighbors |
| Distance rank correlation | 0.9514 | Spearman ρ of pairwise distances |
| Permutation p (linear CKA, 99 shuffles) | 0.0100 | small = more alike than unrelated rows |
- 1 of 150 rows were left out because a coordinate was missing.
The exact R script · R R version 4.5.1 (2025-06-13)
# Compare two embeddings (CKA, Procrustes, kNN overlap)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.compare_embeddings 1.0.0 · spec 8b4783d33b87c351
# Dataset: clu4_embeddings (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
COLS_A <- c("pc1", "pc2")
COLS_B <- c("nz1", "nz2")
SEED <- 42
K <- 5
WIDTH <- as.numeric(0.5)
SCALE <- "none"
PERMS <- 99
CAP <- 2000
cols <- unique(c(COLS_A, COLS_B))
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/clu4_embeddings.parquet", col_select = cols))
n_input <- nrow(df)
cs_check_finite_columns(df, cols) # ±Inf stops with CS_E_NOT_FINITE in both engines
rows <- cs_ml_complete_rows(df, cols)
warnings <- list()
if (length(rows) < n_input) warnings <- c(warnings, sprintf("%d of %d rows were left out because a coordinate was missing.", n_input - length(rows), n_input))
cs_check_rows(length(rows), 4, "Comparing two embeddings")
A <- cs_ml_numeric_matrix(df, COLS_A, rows)
B <- cs_ml_numeric_matrix(df, COLS_B, rows)
if (all(apply(A, 2, function(v) max(v) - min(v)) == 0)) cs_error("CS_E_CONSTANT", column = paste(COLS_A, collapse = ", "))
if (all(apply(B, 2, function(v) max(v) - min(v)) == 0)) cs_error("CS_E_CONSTANT", column = paste(COLS_B, collapse = ", "))
standardize <- function(X) {
flat <- apply(X, 2, function(v) max(v) - min(v)) == 0
s <- apply(X, 2, stats::sd)
s[flat] <- 1
X <- sweep(sweep(X, 2, colMeans(X)), 2, s, "/")
X[, flat] <- 0 # constant columns exactly 0 in both engines
X
}
if (SCALE == "standardize") {
A <- standardize(A)
B <- standardize(B)
}
# %% Agreement indices
r <- cs_ml_compare_embeddings(A, B, K, WIDTH, CAP)
p_perm <- if (PERMS > 0) cs_ml_cka_permutation_p(A, B, r$linear_cka, PERMS, cs_rng(SEED)) else NULL
keys <- c("n", "n_sub", "dims_a", "dims_b", "linear_cka", "debiased_cka", "rbf_cka", "sigma_a", "sigma_b",
"procrustes_disparity", "procrustes_r", "knn_overlap", "k_used", "distance_spearman")
values <- r[keys]
values["p_permutation"] <- list(p_perm)
if (r$n_sub < r$n) warnings <- c(warnings, sprintf("RBF and debiased CKA, kNN overlap and the distance correlation use %s evenly spaced rows of %s.",
format(r$n_sub, big.mark = ","), format(r$n, big.mark = ",")))
idx_rows <- list(
list(index = "Linear CKA (RV coefficient)", value = values$linear_cka, reading = "1 = same up to rotation and scale"),
list(index = "Debiased linear CKA", value = values$debiased_cka, reading = "corrects the upward bias with few rows or many columns"),
list(index = "RBF CKA", value = values$rbf_cka, reading = "more weight on local structure"),
list(index = "Procrustes disparity", value = values$procrustes_disparity, reading = "0 = same up to shift, rotation and scale"),
list(index = "Procrustes r", value = values$procrustes_r, reading = "√(1 − disparity)"),
list(index = sprintf("kNN overlap (k = %d)", values$k_used), value = values$knn_overlap, reading = "share of shared nearest neighbors"),
list(index = "Distance rank correlation", value = values$distance_spearman, reading = "Spearman ρ of pairwise distances")
)
if (!is.null(p_perm)) idx_rows[[length(idx_rows) + 1L]] <- list(index = sprintf("Permutation p (linear CKA, %d shuffles)", PERMS), value = p_perm, reading = "small = more alike than unrelated rows")
tables <- list(list(key = "indices", title = "Agreement between the embeddings",
columns = list(list(key = "index", label = "Index", type = "string"), list(key = "value", label = "Value", type = "number"),
list(key = "reading", label = "Reading", type = "string")),
rows = idx_rows))
# %% Charts
da <- r$dist_a
db <- r$dist_b
pick <- cs_ml_even_sample(length(da), 3000) + 1L
note1 <- paste0(if (length(pick) == length(da)) "" else sprintf("%s of %s row pairs shown. ", format(length(pick), big.mark = ","), format(length(da), big.mark = ",")),
"Points on a rising curve mean the two maps keep the same global layout.")
charts <- list(
cs_chart("distances", "scatter", "Pairwise distances in A and B",
list(x = cs_col("Distance in A", da[pick], "numeric"), y = cs_col("Distance in B", db[pick], "numeric")), note = note1),
cs_chart("overlap", "histogram", sprintf("Share of each row's %d nearest neighbors shared", values$k_used),
list(x = cs_col("kNN overlap", r$knn_rows, "numeric")), controls = list(kde = FALSE),
note = "Rows near 0 sit in different neighborhoods in the two maps.")
)
# %% Result
cs_publish(list(
title = "Compare two embeddings (CKA, Procrustes, kNN overlap)",
engine = cs_engine_info("codesplashr", "nanoparquet"),
n = values$n,
summary = sprintf("Linear CKA %.2f, RBF CKA %.2f, Procrustes r %.2f; %.0f%% of each row's %d nearest neighbors agree.",
values$linear_cka, values$rbf_cka, values$procrustes_r, values$knn_overlap * 100, values$k_used),
statistics = list(list(key = "linear_cka", label = "Linear CKA", value = values$linear_cka),
list(key = "procrustes_r", label = "Procrustes r", value = values$procrustes_r),
list(key = "knn_overlap", label = "kNN overlap", value = values$knn_overlap, format = "percent")),
tables = tables,
values = values,
charts = charts,
warnings = warnings
))
Linear CKA 0.96, RBF CKA 0.94, Procrustes r 0.98; 32% of each row's 5 nearest neighbors agree.
- Linear CKA
- 0.9628
- Procrustes r
- 0.9766
- kNN overlap
- 31.5%
Agreement between the embeddings
| Index | Value | Reading |
|---|---|---|
| Linear CKA (RV coefficient) | 0.9628 | 1 = same up to rotation and scale |
| Debiased linear CKA | 0.9627 | corrects the upward bias with few rows or many columns |
| RBF CKA | 0.9371 | more weight on local structure |
| Procrustes disparity | 0.0463 | 0 = same up to shift, rotation and scale |
| Procrustes r | 0.9766 | √(1 − disparity) |
| kNN overlap (k = 5) | 0.3154 | share of shared nearest neighbors |
| Distance rank correlation | 0.9514 | Spearman ρ of pairwise distances |
| Permutation p (linear CKA, 99 shuffles) | 0.0100 | small = more alike than unrelated rows |
- 1 of 150 rows were left out because a coordinate was missing.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Compare two embeddings (CKA, Procrustes, kNN overlap)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.compare_embeddings 1.0.0 · spec 8b4783d33b87c351
# Dataset: clu4_embeddings (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 as csc
from codesplash.ml import cluster_compare as cc
from codesplash.ml import embed as csembed
from codesplash.stats.rng import Rng
# %% Data
COLS_A = ["pc1", "pc2"]
COLS_B = ["nz1", "nz2"]
SEED = 42
K = 5
WIDTH = float(0.5)
SCALE = "none"
PERMS = 99
CAP = 2000
cols = list(dict.fromkeys(COLS_A + COLS_B))
df = pd.read_parquet("tests/parity/fixtures/clu4_embeddings.parquet", columns=cols)
n_input = len(df)
cs.check_finite_columns(df, cols) # ±Inf stops with CS_E_NOT_FINITE in both engines
rows = csembed.complete_rows(df, cols)
warnings = []
if len(rows) < n_input:
warnings.append(f"{n_input - len(rows)} of {n_input} rows were left out because a coordinate was missing.")
cs.check_rows(len(rows), 4, "Comparing two embeddings")
A = csembed.numeric_matrix(df, COLS_A, rows)
B = csembed.numeric_matrix(df, COLS_B, rows)
if np.all(np.ptp(A, axis=0) == 0):
cs.cs_error("CS_E_CONSTANT", column=", ".join(COLS_A))
if np.all(np.ptp(B, axis=0) == 0):
cs.cs_error("CS_E_CONSTANT", column=", ".join(COLS_B))
if SCALE == "standardize":
fa, fb = np.ptp(A, axis=0) == 0, np.ptp(B, axis=0) == 0
A = csembed.standardize(A, ddof=1)
B = csembed.standardize(B, ddof=1)
A[:, fa] = 0.0 # constant columns exactly 0 in both engines
B[:, fb] = 0.0
# %% Agreement indices
r = cc.compare_embeddings(A, B, K, WIDTH, CAP)
p_perm = cc.permutation_p(A, B, r["linear_cka"], PERMS, Rng(SEED)) if PERMS > 0 else None
keys = ["n", "n_sub", "dims_a", "dims_b", "linear_cka", "debiased_cka", "rbf_cka", "sigma_a", "sigma_b",
"procrustes_disparity", "procrustes_r", "knn_overlap", "k_used", "distance_spearman"]
values = {k: r[k] for k in keys}
values["p_permutation"] = p_perm
if r["n_sub"] < r["n"]:
warnings.append(f"RBF and debiased CKA, kNN overlap and the distance correlation use {r['n_sub']:,} evenly spaced rows of {r['n']:,}.")
tables = [{
"key": "indices",
"title": "Agreement between the embeddings",
"columns": [{"key": "index", "label": "Index", "type": "string"}, {"key": "value", "label": "Value", "type": "number"},
{"key": "reading", "label": "Reading", "type": "string"}],
"rows": [
{"index": "Linear CKA (RV coefficient)", "value": values["linear_cka"], "reading": "1 = same up to rotation and scale"},
{"index": "Debiased linear CKA", "value": values["debiased_cka"], "reading": "corrects the upward bias with few rows or many columns"},
{"index": "RBF CKA", "value": values["rbf_cka"], "reading": "more weight on local structure"},
{"index": "Procrustes disparity", "value": values["procrustes_disparity"], "reading": "0 = same up to shift, rotation and scale"},
{"index": "Procrustes r", "value": values["procrustes_r"], "reading": "√(1 − disparity)"},
{"index": f"kNN overlap (k = {values['k_used']})", "value": values["knn_overlap"], "reading": "share of shared nearest neighbors"},
{"index": "Distance rank correlation", "value": values["distance_spearman"], "reading": "Spearman ρ of pairwise distances"},
] + ([{"index": f"Permutation p (linear CKA, {PERMS} shuffles)", "value": p_perm, "reading": "small = more alike than unrelated rows"}] if p_perm is not None else []),
}]
# %% Charts
da, db = r["dist_a"], r["dist_b"]
pick = csc.even_sample(len(da), 3000)
charts = [
cs.chart(
"distances", "scatter", "Pairwise distances in A and B",
{"x": cs.col("Distance in A", list(da[pick]), "numeric"), "y": cs.col("Distance in B", list(db[pick]), "numeric")},
note=("" if len(pick) == len(da) else f"{len(pick):,} of {len(da):,} row pairs shown. ") + "Points on a rising curve mean the two maps keep the same global layout.",
),
cs.chart(
"overlap", "histogram", f"Share of each row's {values['k_used']} nearest neighbors shared",
{"x": cs.col("kNN overlap", list(r["knn_rows"]), "numeric")},
controls={"kde": False},
note="Rows near 0 sit in different neighborhoods in the two maps.",
),
]
# %% Result
cs.publish({
"title": "Compare two embeddings (CKA, Procrustes, kNN overlap)",
"engine": cs.engine_info("numpy", "pandas"),
"n": values["n"],
"summary": (
f"Linear CKA {values['linear_cka']:.2f}, RBF CKA {values['rbf_cka']:.2f}, Procrustes r {values['procrustes_r']:.2f}; "
f"{values['knn_overlap'] * 100:.0f}% of each row's {values['k_used']} nearest neighbors agree."
),
"statistics": [
{"key": "linear_cka", "label": "Linear CKA", "value": values["linear_cka"]},
{"key": "procrustes_r", "label": "Procrustes r", "value": values["procrustes_r"]},
{"key": "knn_overlap", "label": "kNN overlap", "value": values["knn_overlap"], "format": "percent"},
],
"tables": tables,
"values": values,
"charts": charts,
"warnings": warnings,
})
Shortened for the Academy: 2 chart(s) dropped to stay under 100 KB; 2 chart(s) dropped to stay under 100 KB.
View data
| spend_k | revenue_k | segment |
|---|---|---|
| 47.700 | 100.30 | SMB |
| 56.900 | 129.10 | Enterprise |
| 47.600 | 105.20 | SMB |
| 37.800 | 83.900 | Consumer |
| 16.900 | 8.100 | Consumer |
| 1.100 | 5.200 | Consumer |
| 40.100 | 68.600 | SMB |
| 70.800 | 145.90 | Enterprise |
| 28.200 | 79.900 | Consumer |
| 34.200 | 67.400 | SMB |
| 55.600 | 119.30 | Enterprise |
| 74.600 | 169.50 | Enterprise |
| 55.800 | 147.90 | SMB |
| 34.700 | 78 | Consumer |
| 18.600 | 32.700 | Consumer |
| 29.900 | 59 | SMB |
| 66.800 | 162.80 | Enterprise |
| 33.700 | 83.300 | SMB |
| 1.200 | 10.400 | Consumer |
| 68.100 | 149.40 | Enterprise |
| 57.400 | 124.90 | Enterprise |
| 15 | 42.400 | Consumer |
| 76.400 | 163.30 | Enterprise |
| 36.700 | 73.200 | Consumer |
| 43.400 | 88.200 | SMB |
| 66.400 | 155.60 | SMB |
| 33.600 | 64.600 | SMB |
| 10.600 | 47.400 | Consumer |
| 85.900 | 181 | Enterprise |
| 6.100 | 36.100 | Consumer |
| 61.800 | 160.80 | Enterprise |
| 26 | 68.200 | Consumer |
| 39.700 | 85 | Consumer |
| 20.600 | 45.300 | Consumer |
| 57.300 | 118.90 | SMB |
| 61.900 | 132.20 | SMB |
| 69.900 | 149.50 | Enterprise |
| 30.400 | 68.700 | SMB |
| 57.200 | 124.40 | SMB |
| 78.700 | 170.20 | Enterprise |
| 46.500 | 113.30 | SMB |
| 49.900 | 106.20 | Enterprise |
| 18.500 | 29.100 | Consumer |
| 44 | 112.80 | Enterprise |
| 42.900 | 97.900 | SMB |
| 80.600 | 170.80 | Enterprise |
| 20.200 | 40.100 | Consumer |
| 12.100 | 30.400 | Consumer |
| 6.100 | 32.900 | Consumer |
| 58.200 | 119 | SMB |
| 24 | 50.900 | Consumer |
| 26.600 | 44.200 | Consumer |
| 58.100 | 102 | SMB |
| 33.100 | 91.700 | SMB |
| 17.700 | 68.200 | Consumer |
| 11.800 | 18.100 | Consumer |
| 16.200 | 30.200 | Consumer |
| 32.400 | 32 | Consumer |
| 44.700 | 86.800 | SMB |
| 24.600 | 54 | Consumer |
First 60 of 300 rows.
CKA and Procrustes r are close to 1: the layout survives. The kNN overlap is much lower: the noise reshuffles who sits next to whom. Report both when you claim two maps "show the same thing".
Check your understanding
CheckpointCheck yourself
SigClust gives a cluster index of 0.58 against simulated values around 0.73, with p near 0. What does that say?
Show the answer
Answer: a
A smaller cluster index means a cleaner split. The index is the within-cluster share of the variance, so the between-cluster share is 42%.
Check yourself
Your variables are income in dollars and age in years. What should you do before SigClust?
Show the answer
Answer: b
The background noise comes from the median absolute deviation of every value in the table, which only makes sense when the variables share units.
Check yourself
You clustered survey answers into three groups and a t-test says groups 1 and 2 differ, p < 0.001. Why is that p-value not evidence?
Show the answer
Answer: b
This is double dipping. The selective p-value conditions on the clustering that produced the groups, which keeps its false-alarm rate at the nominal level.
Check yourself
For one pair of clusters, the naive p is 0.0001 and the selective p is 0.4. What do you conclude?
Show the answer
Answer: b
The naive p ignores how the clusters were chosen. The selective p is the valid one; 0.4 is no evidence of a real difference.
Check yourself
Two papers compare DBSCAN with known classes on the same data and report ARIs of 0.44 and 0.63. What is the likeliest reason?
Show the answer
Answer: b
The noise convention changes every agreement index. State it whenever you report a score for a clustering with noise.
Check yourself
Why is purity alone a poor way to judge a clustering?
Show the answer
Answer: a
Every singleton group is perfectly pure. Chance-corrected indices such as ARI and AMI don't reward that.
Check yourself
Two maps have linear CKA 0.96 but kNN overlap 0.31. How do you describe them?
Show the answer
Answer: b
CKA weighs the global structure. kNN overlap looks at each row's neighborhood. Both views matter when you read clusters off a map.
Check yourself
One map is the other rotated by 90° and doubled in size. What is the Procrustes disparity?
Show the answer
Answer: a
Procrustes removes shifts, rotations, reflections and overall scale before comparing, so a rotated, rescaled copy matches exactly.
Concepts in this lesson