Skip to content

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.

Advanced ~16 min5 steps

What runs in CodeSplash

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

Read first

01

Two clusters, or one cloud?

Read

k-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:

Is the split significant? (SigClust)Recorded · Python and R agreeRecorded 2026-11-21 · 13 values compared
R

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

Cluster index under one Gaussian cloudHow unusual is the observed statistic if the null hypothesis were true?

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 valueNull density (normal fit)Observed cluster indexCluster index
0.62995.642e-80.57920.4810
0.62998.078e-80.57920.4829
0.62991.153e-70.57920.4848
0.62991.639e-70.57920.4867
0.62992.323e-70.57920.4886
0.62993.281e-70.57920.4905
0.62994.618e-70.57920.4924
0.62996.479e-70.57920.4943
0.62999.059e-70.57920.4962
0.62991.262e-60.57920.4981
0.62991.753e-60.57920.5000
0.62992.426e-60.57920.5020
0.62993.347e-60.57920.5039
0.62994.601e-60.57920.5058
0.62996.303e-60.57920.5077
0.62998.606e-60.57920.5096
0.62991.171e-50.57920.5115
0.62991.588e-50.57920.5134
0.62992.147e-50.57920.5153
0.62992.892e-50.57920.5172
0.62993.882e-50.57920.5191
0.62995.194e-50.57920.5210
0.62996.925e-50.57920.5229
0.62999.203e-50.57920.5248
0.62990.00010.57920.5267
0.62990.00020.57920.5286
0.62990.00020.57920.5305
0.62990.00030.57920.5324
0.62990.00040.57920.5343
0.62990.00050.57920.5362
0.62990.00060.57920.5381
0.62990.00080.57920.5400
0.62990.00100.57920.5419
0.62990.00130.57920.5438
0.62990.00170.57920.5457
0.62990.00210.57920.5476
0.62990.00270.57920.5496
0.62990.00350.57920.5515
0.62990.00440.57920.5534
0.62990.00550.57920.5553
0.62990.00690.57920.5572
0.62990.00860.57920.5591
0.62990.01070.57920.5610
0.62990.01330.57920.5629
0.62990.01650.57920.5648
0.62990.02040.57920.5667
0.62990.02500.57920.5686
0.62990.03070.57920.5705
0.62990.03740.57920.5724
0.62990.04550.57920.5743
0.62990.05520.57920.5762
0.62990.06680.57920.5781
0.62990.08040.57920.5800
0.62990.09650.57920.5819
0.62990.11550.57920.5838
0.62990.13770.57920.5857
0.62990.16370.57920.5876
0.62990.19390.57920.5895
0.62990.22880.57920.5914
0.62990.26920.57920.5933

First 60 of 200 rows.

Covariance eigenvalues: data and null

ComponentDataNull (simulated)
14.2344.234
21.2031.203
30.81511.147
40.76251.147
50.64051.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
))
Python

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

ComponentDataNull (simulated)
14.2344.234
21.2031.203
30.81511.147
40.76251.147
50.64051.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,
})
Null distributionHow unusual is the observed statistic if the null hypothesis were true?
View data
tdensityobservedcritical lowcritical high
−40.00092.310−2.1012.101
−3.9500.00102.310−2.1012.101
−3.9000.00122.310−2.1012.101
−3.8500.00132.310−2.1012.101
−3.8000.00152.310−2.1012.101
−3.7500.00162.310−2.1012.101
−3.7000.00182.310−2.1012.101
−3.6500.00202.310−2.1012.101
−3.6000.00232.310−2.1012.101
−3.5500.00252.310−2.1012.101
−3.5000.00282.310−2.1012.101
−3.4500.00322.310−2.1012.101
−3.4000.00352.310−2.1012.101
−3.3500.00392.310−2.1012.101
−3.3000.00442.310−2.1012.101
−3.2500.00492.310−2.1012.101
−3.2000.00552.310−2.1012.101
−3.1500.00612.310−2.1012.101
−3.1000.00682.310−2.1012.101
−3.0500.00752.310−2.1012.101
−30.00842.310−2.1012.101
−2.9500.00932.310−2.1012.101
−2.9000.01032.310−2.1012.101
−2.8500.01142.310−2.1012.101
−2.8000.01272.310−2.1012.101
−2.7500.01412.310−2.1012.101
−2.7000.01562.310−2.1012.101
−2.6500.01722.310−2.1012.101
−2.6000.01902.310−2.1012.101
−2.5500.02102.310−2.1012.101
−2.5000.02322.310−2.1012.101
−2.4500.02562.310−2.1012.101
−2.4000.02812.310−2.1012.101
−2.3500.03102.310−2.1012.101
−2.3000.03402.310−2.1012.101
−2.2500.03742.310−2.1012.101
−2.2000.04102.310−2.1012.101
−2.1500.04492.310−2.1012.101
−2.1000.04912.310−2.1012.101
−2.0500.05362.310−2.1012.101
−20.05852.310−2.1012.101
−1.9500.06372.310−2.1012.101
−1.9000.06932.310−2.1012.101
−1.8500.07532.310−2.1012.101
−1.8000.08172.310−2.1012.101
−1.7500.08842.310−2.1012.101
−1.7000.09562.310−2.1012.101
−1.6500.10322.310−2.1012.101
−1.6000.11122.310−2.1012.101
−1.5500.11972.310−2.1012.101
−1.5000.12852.310−2.1012.101
−1.4500.13782.310−2.1012.101
−1.4000.14742.310−2.1012.101
−1.3500.15742.310−2.1012.101
−1.3000.16772.310−2.1012.101
−1.2500.17842.310−2.1012.101
−1.2000.18942.310−2.1012.101
−1.1500.20062.310−2.1012.101
−1.1000.21212.310−2.1012.101
−1.0500.22372.310−2.1012.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:

Is the split significant? (SigClust)Recorded · Python and R agreeRecorded 2026-11-21 · 13 values compared
R

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

Cluster index under one Gaussian cloudHow unusual is the observed statistic if the null hypothesis were true?

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 valueNull density (normal fit)Observed cluster indexCluster index
0.68381.710e-50.72150.5758
0.68382.273e-50.72150.5774
0.68383.010e-50.72150.5791
0.68383.976e-50.72150.5808
0.68385.235e-50.72150.5824
0.68386.872e-50.72150.5841
0.68388.994e-50.72150.5858
0.68380.00010.72150.5874
0.68380.00020.72150.5891
0.68380.00020.72150.5907
0.68380.00030.72150.5924
0.68380.00030.72150.5941
0.68380.00040.72150.5957
0.68380.00050.72150.5974
0.68380.00070.72150.5991
0.68380.00090.72150.6007
0.68380.00110.72150.6024
0.68380.00140.72150.6041
0.68380.00180.72150.6057
0.68380.00230.72150.6074
0.68380.00280.72150.6090
0.68380.00350.72150.6107
0.68380.00440.72150.6124
0.68380.00550.72150.6140
0.68380.00680.72150.6157
0.68380.00840.72150.6174
0.68380.01040.72150.6190
0.68380.01280.72150.6207
0.68380.01560.72150.6224
0.68380.01910.72150.6240
0.68380.02330.72150.6257
0.68380.02820.72150.6273
0.68380.03420.72150.6290
0.68380.04120.72150.6307
0.68380.04960.72150.6323
0.68380.05950.72150.6340
0.68380.07110.72150.6357
0.68380.08480.72150.6373
0.68380.10080.72150.6390
0.68380.11950.72150.6407
0.68380.14110.72150.6423
0.68380.16620.72150.6440
0.68380.19520.72150.6456
0.68380.22860.72150.6473
0.68380.26680.72150.6490
0.68380.31050.72150.6506
0.68380.36030.72150.6523
0.68380.41680.72150.6540
0.68380.48080.72150.6556
0.68380.55280.72150.6573
0.68380.63370.72150.6590
0.68380.72440.72150.6606
0.68380.82540.72150.6623
0.68380.93780.72150.6640
0.68381.0620.72150.6656
0.68381.2000.72150.6673
0.68381.3510.72150.6689
0.68381.5160.72150.6706
0.68381.6970.72150.6723
0.68381.8930.72150.6739

First 60 of 200 rows.

Covariance eigenvalues: data and null

ComponentDataNull (simulated)
13.4093.409
21.4871.487
31.1581.257
41.1021.257
50.74291.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
))
Python

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

ComponentDataNull (simulated)
13.4093.409
21.4871.487
31.1581.257
41.1021.257
50.74291.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,
})
02

Testing what you just found

Read

After 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:

Are these clusters really different? (selective inference)Recorded · Python and R agreeRecorded 2026-11-21 · 17 values compared
R

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

Naive and selective p-values by pairHow do categories compare on one value — and across up to three groups?

The naive p ignores that the clusters were found in the same data; the selective p accounts for it.

View data
ClustersTestp-value
1 vs 2Naive9.480e-12
1 vs 2Selective0.6123
1 vs 3Naive0.0062
1 vs 3Selective0.2694
2 vs 3Naive1.301e-7
2 vs 3Selective0.0817

Difference in means for each pair of clusters

ClustersRows (first)Rows (second)Distance between meansNaive pSelective pDraws keptEffective draws
1 vs 27183.6479.480e-120.612315633.510
1 vs 37115.1000.00620.269420078.212
2 vs 3818.4621.301e-70.081721445.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
))
Python

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

ClustersRows (first)Rows (second)Distance between meansNaive pSelective pDraws keptEffective draws
1 vs 27183.6479.480e-120.612315633.510
1 vs 37115.1000.00620.269420078.212
2 vs 3818.4621.301e-70.081721445.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,
})
Cleveland dot plotHow do categories compare on one value — and across up to three groups?
View data
countrylife_expectancysex
Japan83.300Male
Japan85.300Female
Japan82.600Male
Japan89.100Female
Japan81.200Male
Japan89.100Female
Japan83.500Male
Japan85.700Female
Japan79.900Male
Japan87.400Female
Japan83.800Male
Japan89.500Female
Japan80.600Male
Japan86.500Female
Japan84.200Male
Japan87.600Female
Japan82.100Male
Japan87.600Female
Japan82.800Male
Japan88.500Female
Japan83.800Male
Japan87.400Female
Japan83.400Male
Japan86.300Female
Japan81.900Male
Japan86.700Female
Japan80.800Male
Japan87.100Female
Japan81.500Male
Japan86.700Female
Japan81.100Male
Japan86Female
Japan83.900Male
Japan87.900Female
Japan81.300Male
Japan87.200Female
Japan81.300Male
Japan85.200Female
Japan85.100Male
Japan85.500Female
Spain78Male
Spain86.200Female
Spain80.800Male
Spain86.400Female
Spain81.100Male
Spain85.200Female
Spain82Male
Spain85.500Female
Spain80.700Male
Spain86.700Female
Spain83Male
Spain86.700Female
Spain77.900Male
Spain85.800Female
Spain82.300Male
Spain85.700Female
Spain81.100Male
Spain89.200Female
Spain81.800Male
Spain87.400Female

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.

03

Do two clusterings agree?

Read

To 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:

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

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

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

Plots

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

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

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

Agreement indices

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

Rows by species (rows) and db (columns)

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

# %% Setup
library(codesplashr)

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

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

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

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

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

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

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

Agreement indices

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

Rows by species (rows) and db (columns)

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

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

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

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

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

# %% Result
ari = values["ari"]
verdict = "almost identical" if ari >= 0.9 else ("in substantial agreement" if ari >= 0.5 else ("in partial agreement" if ari >= 0.2 else "close to chance agreement"))
cs.publish({
    "title": "Compare two partitions (ARI, AMI, VI, purity)",
    "engine": cs.engine_info("numpy", "scipy", "pandas"),
    "n": values["n"],
    "summary": f"{A} ({values['k_a']} groups) and {B} ({values['k_b']} groups) are {verdict}: ARI {ari:.2f}, AMI {values['ami']:.2f}, VI {values['vi']:.2f} nats.",
    "statistics": [
        {"key": "ari", "label": "Adjusted Rand index", "value": ari},
        {"key": "ami", "label": "Adjusted mutual information", "value": values["ami"]},
        {"key": "vi", "label": "Variation of information (nats)", "value": values["vi"]},
    ],
    "tables": tables,
    "values": values,
    "charts": charts,
    "warnings": warnings,
})
Partition flowHow do the rows of one grouping spread over another, for example known classes over clusters?
View data
speciesclusterflowers
setosaCluster 150
versicolorCluster 241
versicolorCluster 36
versicolornoise3
virginicaCluster 336
virginicaCluster 212
virginicanoise2

Left out:

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

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

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

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

View data
dbCountspeciesRows
045setosa45
10setosa0
00versicolor0
139versicolor39
00virginica0
132virginica32
How the groups of species map onto dbHow do the rows of one grouping spread over another, for example known classes over clusters?
View data
Rowsspeciesdb
45setosa0
39versicolor1
32virginica1

Agreement indices

IndexValueReading
Adjusted Rand index0.63090 = chance, 1 = identical
Adjusted mutual information0.75780 = chance, 1 = identical
Normalized mutual information0.76020 to 1; not chance-corrected
Variation of information (nats)0.42130 = identical; a distance
Normalized variation of information0.38680 = identical, 1 = unrelated
Fowlkes–Mallows0.80050 to 1
Rand index0.81290 to 1; not chance-corrected
Pair Jaccard0.64090 to 1
Homogeneity0.61321 = each judged group holds one reference group
Completeness11 = each reference group sits in one judged group
V-measure0.7602harmonic mean of the two above
Purity0.7241share of rows in the majority reference group of their judged group
Inverse purity1the same with the roles swapped

Rows by species (rows) and db (columns)

species01Total
setosa45045
versicolor03939
virginica03232
  • 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
))
Python

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

IndexValueReading
Adjusted Rand index0.63090 = chance, 1 = identical
Adjusted mutual information0.75780 = chance, 1 = identical
Normalized mutual information0.76020 to 1; not chance-corrected
Variation of information (nats)0.42130 = identical; a distance
Normalized variation of information0.38680 = identical, 1 = unrelated
Fowlkes–Mallows0.80050 to 1
Rand index0.81290 to 1; not chance-corrected
Pair Jaccard0.64090 to 1
Homogeneity0.61321 = each judged group holds one reference group
Completeness11 = each reference group sits in one judged group
V-measure0.7602harmonic mean of the two above
Purity0.7241share of rows in the majority reference group of their judged group
Inverse purity1the same with the roles swapped

Rows by species (rows) and db (columns)

species01Total
setosa45045
versicolor03939
virginica03232
  • 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.

04

Do two maps agree?

Read

Two 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:

Compare two embeddings (CKA, Procrustes, kNN overlap)Recorded · Python and R agreeRecorded 2026-11-21 · 15 values compared
R

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

IndexValueReading
Linear CKA (RV coefficient)0.96281 = same up to rotation and scale
Debiased linear CKA0.9627corrects the upward bias with few rows or many columns
RBF CKA0.9371more weight on local structure
Procrustes disparity0.04630 = same up to shift, rotation and scale
Procrustes r0.9766√(1 − disparity)
kNN overlap (k = 5)0.3154share of shared nearest neighbors
Distance rank correlation0.9514Spearman ρ of pairwise distances
Permutation p (linear CKA, 99 shuffles)0.0100small = 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
))
Python

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

IndexValueReading
Linear CKA (RV coefficient)0.96281 = same up to rotation and scale
Debiased linear CKA0.9627corrects the upward bias with few rows or many columns
RBF CKA0.9371more weight on local structure
Procrustes disparity0.04630 = same up to shift, rotation and scale
Procrustes r0.9766√(1 − disparity)
kNN overlap (k = 5)0.3154share of shared nearest neighbors
Distance rank correlation0.9514Spearman ρ of pairwise distances
Permutation p (linear CKA, 99 shuffles)0.0100small = 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.

Scatter plotHow do two numeric variables move together?
View data
spend_krevenue_ksegment
47.700100.30SMB
56.900129.10Enterprise
47.600105.20SMB
37.80083.900Consumer
16.9008.100Consumer
1.1005.200Consumer
40.10068.600SMB
70.800145.90Enterprise
28.20079.900Consumer
34.20067.400SMB
55.600119.30Enterprise
74.600169.50Enterprise
55.800147.90SMB
34.70078Consumer
18.60032.700Consumer
29.90059SMB
66.800162.80Enterprise
33.70083.300SMB
1.20010.400Consumer
68.100149.40Enterprise
57.400124.90Enterprise
1542.400Consumer
76.400163.30Enterprise
36.70073.200Consumer
43.40088.200SMB
66.400155.60SMB
33.60064.600SMB
10.60047.400Consumer
85.900181Enterprise
6.10036.100Consumer
61.800160.80Enterprise
2668.200Consumer
39.70085Consumer
20.60045.300Consumer
57.300118.90SMB
61.900132.20SMB
69.900149.50Enterprise
30.40068.700SMB
57.200124.40SMB
78.700170.20Enterprise
46.500113.30SMB
49.900106.20Enterprise
18.50029.100Consumer
44112.80Enterprise
42.90097.900SMB
80.600170.80Enterprise
20.20040.100Consumer
12.10030.400Consumer
6.10032.900Consumer
58.200119SMB
2450.900Consumer
26.60044.200Consumer
58.100102SMB
33.10091.700SMB
17.70068.200Consumer
11.80018.100Consumer
16.20030.200Consumer
32.40032Consumer
44.70086.800SMB
24.60054Consumer

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".

05

Check your understanding

Checkpoint

Check 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