Skip to content

Is the structure real? SigClust, selective inference, prediction strength and stability

A clustering algorithm always returns clusters. Four checks ask whether they mean anything: a test against one Gaussian, a p-value that allows for choosing the clusters, agreement on new rows, and survival under resampling.

Advanced ~15 min10 steps

What runs in CodeSplash

You will be able to

  • Explain why a t-test between clusters found on the same data is invalid, and what selective inference conditions on
  • State SigClust's null hypothesis and what rejecting it does and doesn't show
  • Compute prediction strength's idea from train and validation fits
  • Read bootstrap Jaccard stability, and say why stable isn't the same as correct

Read first

01

Clusters always come back

Read

Ask k-means for three clusters in a single round cloud and you get three clusters. They will differ in their means, often "significantly", because the algorithm drew the boundaries exactly where the means differ most. Finding clusters and then testing them on the same rows is double dippingDouble dippingTesting differences between groups that were created from the same rows; the tests come out optimistic..

This lesson's four checks each ask a sharper question:

CheckQuestion
SigClustIs the data more than one Gaussian cloud?
Selective inferenceDo two found clusters differ, given that they were found?
Prediction strengthDo new rows reproduce the clusters?
Bootstrap stabilityDo the clusters survive resampling?
02

One cloud, a tiny p-value

Predict

Predict first

You simulate one round Gaussian cloud, cut it into clusters with hierarchical clustering, and run an ordinary test for a difference in means between two of them. What p-value do you expect?

A large p-value: there's only one cloudA tiny p-value
Reveal

A tiny one. The naive p-value was p < .001, though there is no real structure. The selective p-value, which accounts for how the clusters were chosen, was p = .612.

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,
})
03

Selective inference

Read

A 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. conditions on the selection event S\mathcal S, here "hierarchical clustering produced these two clusters": psel=Pr⁡H0(T≥Tobs∣S)p_{\text{sel}}=\Pr_{H_0}(T\ge T_{\text{obs}}\mid\mathcal S). Under the null of equal means it is uniform even though the clusters were picked to look different.

Its validity is tied to the exact pipeline: the model (Gaussian with a known or estimated variance), the linkage, the cut and the variance treatment. Clustering an embedding and then running a t-test inherits none of it. Sample splitting helps only when the held-out rows' cluster labels don't reuse the features you test.

Compare the naive and the selective p-value on one cloud below, then move the clouds apart.

BExplorable · Selective inference after hierarchical clustering

You clustered the data, then tested whether two clusters differ. Why is the ordinary test's p-value too small?

Data

Simulated data follow the settings below. The lesson's example is the data the engines ran, as recorded; the settings don't change it.

50
4
0.0

0 gives one Gaussian cloud; larger values move half the rows along variable 1.

Linkage

How hierarchical clustering measures the distance between clusters.

3

Where the tree is cut; clusters 1 and 2 (the two largest) are tested.

200

Importance-sampling draws; each re-runs the clustering on moved data.

0.050

Your data

Simulated with a known number of clouds

The first two of 4 variables, marked by the 3 clusters of the tree; clusters 1 and 2 are tested. Crosses mark the means.

If H₀ were true

‖x̄₁ − x̄₂‖ = 3.29
  1. The reference: how ‖x̄₁ − x̄₂‖ varies across samples when H₀ is true, s·χ4 restricted to the 92 of 200 draws that reproduce the clusters (importance sampling: 92 of 200 moved data sets gave clusters 1 and 2 again (effective draws 34.5, seed 42); the naive p ignoring the selection is 0.000093).
  2. Your statistic, from the data above.
  3. The p-value: the area at least as extreme as yours (p = .764).
  4. The hatched rejection region at α = .050: statistics landing here reject H₀.

The formula

pselective=Pr⁡H0(∥XˉG1−XˉG2∥≥∥xˉG1−xˉG2∥  ∣  the clustering chose G1,G2)p_{\text{selective}} = \Pr_{H_0}\Bigl(\|\bar X_{G_1}-\bar X_{G_2}\| \ge \|\bar x_{G_1}-\bar x_{G_2}\| \;\Big|\; \text{the clustering chose } G_1, G_2\Bigr)

With your numbers

∥xˉG1−xˉG2∥=3.29,pnaive=0.000093, pselective=0.76, draws kept=92\|\bar x_{G_1}-\bar x_{G_2}\| = 3.29,\qquad p_{\text{naive}} = 0.000093,\ p_{\text{selective}} = 0.76,\ \text{draws kept} = 92
G1, G2G_1,\ G_2
the two largest clusters the algorithm chose from these same data
pnaivep_{\text{naive}}
the usual χ test, which ignores that the groups were chosen to be far apart
draws kept\text{draws kept}
moved data sets on which the clustering found G₁ and G₂ again: they make up the truncated null

The verdict

‖x̄₁ − x̄₂‖ = 3.29, p = .764

p > α = .050: compatible with H₀

Clustering picks groups that differ, so testing their difference on the same data double-dips: on one cloud the naive p is tiny, while the selective p, which conditions on the clustering's choice (Gao, Bien & Witten 2022), is not. Its price is power: because it conditions on the whole clustering, it can stay large even when the clouds are far apart. It is a Monte Carlo estimate, so check the effective draws. The lesson's example gives the recorded result.

Statistic
3.286
p-value
0.7641
Selective inference after hierarchical clustering on 50 rows on 4 variables: ‖x̄1 − x̄2‖ = 3.29, p = .764. The p-value is above α = .050, so the data are compatible with H0.

Selective inference after hierarchical clustering on 50 rows on 4 variables: ‖x̄₁ − x̄₂‖ = 3.29, p = .764. The p-value is above α = .050, so the data are compatible with H₀.

04

SigClust: more than one Gaussian?

Read

SigClustSigClustTests whether the best two-group split beats what one Gaussian cloud with the data's shape would give. tests whether a 2-means split is stronger than a single Gaussian would give. Its statistic is the cluster index CICI: within-cluster sum of squares over total sum of squares. It fits a Gaussian null with a carefully estimated covariance, simulates datasets from it, reruns 2-means on each and asks how often their CICI is as small.

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,
})

On one simulated cloud the p-value was 0.330; on two clouds, 0 in 100 simulations. Rejecting "one Gaussian" isn't proof of subtypes: skew, heavy tails, batch effects or preprocessing can reject it too. In high dimensions the covariance estimate decides the answer.

Raise the separation below until the 2-means split beats what one Gaussian cloud gives.

BExplorable · SigClust: is a two-cluster split significant?

k-means always finds two groups. Is this split stronger than splitting a single Gaussian cloud would give?

Data

Simulated data follow the settings below. The lesson's example is the data the engines ran, as recorded; the settings don't change it.

50
4
0.0

0 gives one Gaussian cloud; larger values move half the rows along variable 1.

100

Gaussian data sets simulated under the null; more gives a steadier p-value.

Null eigenvalues

How the null Gaussian's variances come from the data's eigenvalues and the background noise.

3

k-means++ starts per split; the best is kept for the data and for every simulation.

0.050

Your data

Simulated with a known number of clouds

The first two of 4 variables, marked by the best 2-means split. Crosses mark the means.

If H₀ were true

CI = 0.78
  1. The reference: how CI varies across samples when H₀ is true, normal fitted to 100 simulated cluster indices (mean 0.748, SD 0.027) (Gaussian p from 100 2-means fits to one simulated Gaussian cloud with the data's eigenvalues (seed 42); the share of simulated indices at or below yours is 0.880).
  2. Your statistic, from the data above.
  3. The p-value: the area at least as extreme as yours (p = .888).
  4. The hatched rejection region at α = .050: statistics landing here reject H₀.

The formula

CI=∑k=12∑i∈Ck∥xi−xˉk∥2∑i∥xi−xˉ∥2,p=Φ ⁣(CI−CIˉ∗sd(CI∗))\mathrm{CI} = \dfrac{\sum_{k=1}^{2}\sum_{i\in C_k}\|x_i-\bar x_k\|^2}{\sum_i \|x_i - \bar x\|^2},\qquad p = \Phi\!\left(\dfrac{\mathrm{CI} - \bar{\mathrm{CI}}^{*}}{\mathrm{sd}(\mathrm{CI}^{*})}\right)

With your numbers

CI=0.78,CIˉ∗=0.75, sd(CI∗)=0.03, simulations=100\mathrm{CI} = 0.78,\qquad \bar{\mathrm{CI}}^{*} = 0.75,\ \mathrm{sd}(\mathrm{CI}^{*}) = 0.03,\ \text{simulations} = 100
CI\mathrm{CI}
cluster index: within-cluster over total sum of squares of the best 2-means split; small means a strong split
CI∗\mathrm{CI}^{*}
the same index on data simulated from one Gaussian with the data's eigenvalues (background noise floored)

The verdict

CI = 0.78, p = .888

p > α = .050: compatible with H₀

A cluster index no smaller than what one Gaussian cloud gives means the split is what noise looks like. The null is simulated because the clustering is part of the statistic. Raise the separation until the split beats the null. The lesson's example is one cloud: the live numbers match the recorded run.

Statistic
0.780
p-value
0.8884
SigClust: is a two-cluster split significant? on 50 rows on 4 variables: CI = 0.78, p = .888. The p-value is above α = .050, so the data are compatible with H0.

SigClust: is a two-cluster split significant? on 50 rows on 4 variables: CI = 0.78, p = .888. The p-value is above α = .050, so the data are compatible with H₀.

05

Prediction strength: do new rows agree?

Read

Prediction strengthPrediction strengthShare of pairs in each test cluster that centers fitted on the other half also keep together; the weakest cluster counts. splits the rows. Cluster the training half; cluster the validation half on its own; then assign validation rows to the training clusters. For each validation cluster CjC_j, count the pairs of its rows that the training clusters also put together:

PS(k)=min⁡j#{i≠i′∈Cj: c^i=c^i′}∣Cj∣(∣Cj∣−1).PS(k)=\min_j\frac{\#\{i\ne i'\in C_j:\ \hat c_i=\hat c_{i'}\}}{|C_j|(|C_j|-1)}.

Choose the number of clustersRecorded · Python and R agreeRecorded 2026-11-25 · 63 values compared
R

Comparing k = 2–5 with k-means, the prediction strength (largest k at or above 0.8) recommends k = 2 (4 of 5 criteria agree).

Clusters
2
Mean silhouette
0.5818

Plots

ClustersWhich rows group together, and how well separated are the groups?
View data
CenterClusterPC1 (73%)PC2 (23%)
false2−2.2650.4800
false2−2.081−0.6741
false2−2.364−0.3419
false2−2.299−0.5974
false2−2.3900.6468
false2−2.0761.489
false2−2.4440.0476
false2−2.2330.2231
false2−2.335−1.115
false2−2.184−0.4690
false2−2.1661.044
false2−2.3260.1331
false2−2.218−0.7287
false2−2.633−0.9615
false2−2.1991.860
false2−2.2622.686
false2−2.2081.484
false2−2.1900.4888
false2−1.8991.405
false2−2.3431.128
false2−1.9140.4089
false2−2.2070.9241
false2−2.7740.4583
false2−1.8190.0856
false2−2.2270.1373
false2−1.952−0.6256
false2−2.0510.2422
false2−2.1690.5271
false2−2.1400.3132
false2−2.265−0.3377
false2−2.140−0.5045
false2−1.8320.4237
false2−2.6151.794
false2−2.4462.151
false2−2.110−0.4602
false2−2.208−0.2061
false2−2.0450.6616
false2−2.5270.5923
false2−2.430−0.9042
false2−2.1700.2689
false2−2.2860.4417
false2−1.858−2.337
false2−2.554−0.4791
false2−1.9640.4723
false2−2.1371.142
false2−2.070−0.7111
false2−2.3851.120
false2−2.394−0.3862
false2−2.2290.9980
false2−2.2040.0092
false11.1020.8630
false10.73130.5946
false11.2410.6163
false10.4075−1.754
false11.075−0.2084
false10.3887−0.5933
false10.74650.7730
false1−0.4873−1.852
false10.92790.0322
false10.0114−1.034

First 60 of 152 rows.

Criteria by number of clustersHow many clusters does the data support?

Recommended k = 2 by the prediction strength (largest k at or above 0.8).

View data
RecommendedCriterionClusters (k)Score
falseWithin-cluster SS2222.36
trueWithin-cluster SS3140.90
falseWithin-cluster SS4114.35
falseWithin-cluster SS5105.31
trueMean silhouette20.5818
falseMean silhouette30.4565
falseMean silhouette40.3819
falseMean silhouette50.3907
trueCalinski–Harabasz2251.35
falseCalinski–Harabasz3239.48
falseCalinski–Harabasz4206.68
falseCalinski–Harabasz5170.28
trueDavies–Bouldin20.5933
falseDavies–Bouldin30.8275
falseDavies–Bouldin40.8796
falseDavies–Bouldin51.003
truePrediction strength20.9953
falsePrediction strength30.6537
falsePrediction strength40.5761
falsePrediction strength50.4497
Silhouette widthsHow well does each row fit its cluster compared with the next-nearest cluster?
View data
ClusterSilhouette width
10.6662
10.6658
10.6646
10.6605
10.6604
10.6595
10.6580
10.6576
10.6502
10.6491
10.6487
10.6438
10.6386
10.6385
10.6347
10.6337
10.6326
10.6292
10.6289
10.6248
10.6245
10.6202
10.6189
10.6189
10.6176
10.6131
10.6118
10.6114
10.6107
10.6094
10.6084
10.6047
10.6017
10.6016
10.6013
10.6013
10.5981
10.5980
10.5948
10.5897
10.5879
10.5878
10.5870
10.5852
10.5796
10.5772
10.5766
10.5765
10.5729
10.5699
10.5681
10.5665
10.5637
10.5605
10.5578
10.5561
10.5556
10.5504
10.5448
10.5360

First 60 of 150 rows.

Clusters

ClusterSizeSharesepal_lengthsepal_widthpetal_lengthpetal_width
110066.7%6.2622.8724.9061.676
25033.3%5.0063.4281.4620.2460

Criteria by k

kWithin-cluster SSMean silhouetteCalinski–HarabaszDavies–BouldinPrediction strengthPrediction strength SD
2222.360.5818251.350.59330.99530.0133
3140.900.4565239.480.82750.65370.1215
4114.350.3819206.680.87960.57610.0907
5105.310.3907170.281.0030.44970.0579
The exact R script · R R version 4.5.1 (2025-06-13)
# Choose the number of clusters
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.choose_k 1.1.0 · spec 6455065068179c84
# Dataset: ml_iris (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("sepal_length", "sepal_width", "petal_length", "petal_width")
LABEL <- "species"  # known groups (external validation only)
ROW_ID <- NULL  # row labels for charts
SEED <- 42
KINDS <- list(
  sepal_length = "numeric",
  sepal_width = "numeric",
  petal_length = "numeric",
  petal_width = "numeric"
)
LEVELS <- list(
)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_iris.parquet", col_select = unique(c(FEATURES, LABEL, ROW_ID))))
n_input <- nrow(df)
prep <- cs_ml_cluster_prepare(df, FEATURES, KINDS, LEVELS, missing = "drop", scale = "standard")
X <- prep$X; rows <- prep$rows; names_ <- prep$names; frame <- prep$frame
warnings <- list()
if (length(rows) < n_input) {
  warnings <- c(warnings, sprintf("%d of %d rows were left out because a feature was missing.", n_input - length(rows), n_input))
}
if (length(rows) < 3) stop("Clustering needs at least three rows with every feature present.")
truth <- if (!is.null(LABEL)) as.character(frame[[LABEL]]) else NULL
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.choose_k/iris_prediction_strength/out-r")
values <- list(n_used = length(rows))
centers <- NULL
center_ids <- NULL
D <- NULL
extra <- list()
tables <- list()
charts <- list()
summary <- NULL

# %% Clustering
ALGORITHM <- "kmeans"
CRITERION <- "prediction_strength"
N_INIT <- 3
if (ALGORITHM != "kmeans" && CRITERION == "gap") stop("The gap statistic is computed for k-means; choose k-means or another criterion.")
if (ALGORITHM != "gmm" && CRITERION == "bic") stop("BIC needs the Gaussian mixture; choose that method or another criterion.")
if (ALGORITHM == "gmm") stop("Prediction strength is computed for k-means and PAM; choose one of them or another criterion.")
ks <- seq.int(2, min(5, length(rows) - 1))
if (length(ks) < 2) cs_error("CS_E_TOO_FEW_ROWS", what = "Comparing k = 2 to 5", min = 2 + 2L, n = length(rows))
values$k_min <- ks[1]; values$k_max <- ks[length(ks)]
D_choose <- NULL
if (ALGORITHM == "pam") {
  dist_ <- "auto"
  if (dist_ == "auto") dist_ <- if (any(unlist(KINDS[FEATURES]) != "numeric")) "gower" else "euclidean"
  D_choose <- if (dist_ == "gower") cs_ml_gower(frame, FEATURES, KINDS) else as.matrix(stats::dist(X))
  dimnames(D_choose) <- NULL
}
rng <- cs_rng(SEED)  # shared stream: the same starts in Python and R
fits <- list()
crit <- list(within = numeric(0), silhouette = numeric(0), calinski_harabasz = numeric(0), davies_bouldin = numeric(0))
if (ALGORITHM == "gmm") crit$bic <- numeric(0)
for (kk in ks) {
  if (ALGORITHM == "kmeans") {
    f <- cs_ml_kmeans_fit(X, kk, rng, N_INIT)
    raw_k <- f$labels; centers_k <- f$centers
  } else if (ALGORITHM == "pam") {
    res <- cluster::pam(stats::as.dist(D_choose), kk, diss = TRUE, pamonce = 0)
    raw_k <- res$clustering - 1L; centers_k <- X[res$id.med, , drop = FALSE]
  } else {
    f <- cs_ml_gmm_fit(X, kk, "full", rng, N_INIT)
    raw_k <- f$labels; centers_k <- f$means
    crit$bic <- c(crit$bic, f$bic)
  }
  fits[[as.character(kk)]] <- list(raw = raw_k, centers = centers_k)
  lab <- cs_ml_canonical(raw_k)
  crit$within <- c(crit$within, cs_ml_within_ss(X, lab))
  crit$silhouette <- c(crit$silhouette, cs_ml_silhouette(lab, X = if (is.null(D_choose)) X else NULL, D = D_choose, seed = SEED)$mean)
  crit$calinski_harabasz <- c(crit$calinski_harabasz, cs_ml_calinski_harabasz(X, lab))
  crit$davies_bouldin <- c(crit$davies_bouldin, cs_ml_davies_bouldin(X, lab))
}
best <- list(
  elbow = ks[cs_ml_kneedle(ks, crit$within) + 1L],
  silhouette = ks[which.max(crit$silhouette)],
  calinski_harabasz = ks[which.max(crit$calinski_harabasz)],
  davies_bouldin = ks[which.min(crit$davies_bouldin)]
)
if (ALGORITHM == "gmm") best$bic <- ks[which.min(crit$bic)]
if (CRITERION == "gap") {
  rng_gap <- cs_rng(SEED + 1)  # a second shared stream for the reference sets and their starts
  refs <- lapply(seq_len(10), function(b) cs_ml_reference_set(X, rng_gap))
  gap <- numeric(0); se <- numeric(0)
  for (i in seq_along(ks)) {
    logw <- vapply(refs, function(ref) log(max(cs_ml_kmeans_fit(ref, ks[i], rng_gap, 1)$inertia, 1e-300)), numeric(1))
    gap <- c(gap, mean(logw) - log(max(crit$within[i], 1e-300)))
    se <- c(se, stats::sd(logw) * sqrt(1 + 1 / length(refs)))
  }
  crit$gap <- gap; crit$gap_se <- se
  best$gap <- cs_ml_gap_choice(ks, gap, se)
}
# Prediction strength (Tibshirani & Walther 2005): cluster random halves separately and check how often the training
# centers keep each test cluster's pairs together (twin: prediction_strength)
rng_ps <- cs_rng(SEED + 2)  # a third shared stream for the splits and their fits
if (ALGORITHM == "kmeans") {
  ps_fit <- function(idx, kk) {
    fp <- cs_ml_kmeans_fit(X[idx + 1L, , drop = FALSE], kk, rng_ps, N_INIT)
    list(labels = fp$labels, centers = fp$centers)
  }
  ps_assign <- function(idx, cen) cs_cp_assign_nearest(X[idx + 1L, , drop = FALSE], cen)
} else {
  ps_fit <- function(idx, kk) {
    rp <- cluster::pam(stats::as.dist(D_choose[idx + 1L, idx + 1L]), kk, diss = TRUE, pamonce = 0)
    list(labels = rp$clustering - 1L, centers = idx[rp$id.med])
  }
  ps_assign <- function(idx, med) {
    sub <- D_choose[idx + 1L, med + 1L, drop = FALSE]
    max.col(-sub, ties.method = "first") - 1L
  }
}
psr <- cs_cp_prediction_strength(length(rows), ks, rng_ps, 8, ps_fit, ps_assign)
crit$prediction_strength <- psr$mean
crit$prediction_strength_sd <- psr$sd
chosen_ps <- cs_cp_ps_choice(ks, psr$mean, 0.8)
if (is.null(chosen_ps)) {
  chosen_ps <- ks[1]
  warnings <- c(warnings, sprintf("No k reached a prediction strength of %s; the smallest k tried is shown. The data may hold no stable clusters.", 0.8))
}
best$prediction_strength <- chosen_ps
for (nm in names(crit)) for (i in seq_along(ks)) values[[sprintf("score[%s,%d]", nm, ks[i])]] <- crit[[nm]][i]
for (nm in names(best)) values[[sprintf("best_k[%s]", nm)]] <- best[[nm]]
K_BEST <- best[[CRITERION]]
values$recommended_k <- K_BEST
values$agree <- sum(unlist(best) == K_BEST)
values$n_criteria <- length(best)
LABELS <- c(elbow = "elbow (kneedle)", silhouette = "mean silhouette", gap = "gap statistic (first-SE rule)",
            calinski_harabasz = "Calinski–Harabasz index", davies_bouldin = "Davies–Bouldin index", bic = "BIC")
LABELS[["prediction_strength"]] <- "prediction strength (largest k at or above 0.8)"
values$criterion_label <- LABELS[[CRITERION]]
values$algorithm_label <- switch(ALGORITHM, kmeans = "k-means", pam = "PAM", gmm = "a Gaussian mixture")
raw <- fits[[as.character(K_BEST)]]$raw
centers <- fits[[as.character(K_BEST)]]$centers
D <- D_choose
NAMES <- c(within = "Within-cluster SS", silhouette = "Mean silhouette", calinski_harabasz = "Calinski–Harabasz",
           davies_bouldin = "Davies–Bouldin", gap = "Gap", bic = "BIC", gap_se = "Gap SE")
NAMES[["prediction_strength"]] <- "Prediction strength"
NAMES[["prediction_strength_sd"]] <- "Prediction strength SD"
pk <- numeric(0); ps <- numeric(0); pc <- character(0); pch <- logical(0)
for (nm in intersect(c("within", "silhouette", "gap", "calinski_harabasz", "davies_bouldin", "bic", "prediction_strength"), names(crit))) {
  chosen_k <- best[[if (nm == "within") "elbow" else nm]]
  pk <- c(pk, ks); ps <- c(ps, crit[[nm]]); pc <- c(pc, rep(NAMES[[nm]], length(ks))); pch <- c(pch, ks == chosen_k)
}
charts[[length(charts) + 1L]] <- cs_chart(
  "choose_k", "elbow-plot", "Criteria by number of clusters",
  list(k = cs_col("Clusters (k)", pk, "numeric"), score = cs_col("Score", ps, "numeric"),
       criterion = cs_col("Criterion", pc, "categorical"), chosen = cs_col("Recommended", pch, "boolean")),
  note = sprintf("Recommended k = %d by the %s.", K_BEST, LABELS[[CRITERION]])
)
tables[[length(tables) + 1L]] <- list(
  key = "choose_k", title = "Criteria by k",
  columns = c(list(list(key = "k", label = "k", type = "integer")),
              lapply(names(crit), function(nm) list(key = nm, label = NAMES[[nm]], type = "number"))),
  rows = lapply(seq_along(ks), function(i) c(list(k = ks[i]), lapply(crit, function(v) v[i])))
)
summary <- sprintf("Comparing k = %d–%d with %s, the %s recommends k = %d (%d of %d criteria agree).",
                   ks[1], ks[length(ks)], values$algorithm_label, LABELS[[CRITERION]], K_BEST, values$agree, values$n_criteria)

# %% Canonical labels and validation
labels <- cs_ml_canonical(raw)
ids <- sort(unique(labels[labels != -1]))
k <- length(ids)
values$k <- k
values$n_noise <- sum(labels == -1)
if (!is.null(centers)) {
  cid <- if (is.null(center_ids)) seq_len(nrow(centers)) - 1L else center_ids
  raw_of <- vapply(ids, function(c) raw[which(labels == c)[1]], numeric(1))
  centers <- centers[match(raw_of, cid), , drop = FALSE]
  for (i in seq_along(ids)) for (j in seq_along(names_)) {
    values[[sprintf("center[%d,%s]", ids[i], names_[j])]] <- centers[i, j]
  }
}
sz <- cs_ml_cluster_sizes(labels)
for (c in names(sz)) values[[sprintf("size[%s]", c)]] <- sz[[c]]
check <- cs_ml_cluster_validation(X, labels, truth, D = D, cap = 3000, seed = SEED)
widths <- check$.widths
check$.widths <- NULL
values <- c(values, check)
profile_rows <- list()
for (c in ids) {
  member <- labels == c
  row <- list(cluster = c, size = sum(member), share = mean(member))
  for (f in FEATURES) {
    if (identical(KINDS[[f]], "numeric")) {
      m <- mean(suppressWarnings(as.numeric(frame[[f]]))[member], na.rm = TRUE)
      row[[f]] <- m
      values[[sprintf("mean[%d,%s]", c, f)]] <- m
    } else {
      v <- as.character(frame[[f]])[member]
      v <- v[!is.na(v)]
      top <- if (length(v)) sort(table(v), decreasing = TRUE) else NULL
      row[[f]] <- if (length(top)) sprintf("%s (%.0f%%)", names(top)[1], 100 * top[[1]] / sum(member)) else ""
    }
  }
  profile_rows[[length(profile_rows) + 1L]] <- row
}
tables <- c(list(list(
  key = "clusters", title = "Clusters",
  columns = c(list(list(key = "cluster", label = "Cluster", type = "integer"),
                   list(key = "size", label = "Size", type = "integer"),
                   list(key = "share", label = "Share", type = "percent")),
              lapply(FEATURES, function(f) list(key = f, label = f, type = if (identical(KINDS[[f]], "numeric")) "number" else "string"))),
  rows = profile_rows
)), tables)

# %% Labels file and charts
path <- do.call(cs_ml_write_labels, c(list(out, rows, labels), extra))
name_of <- function(c) as.character(c)  # noise stays "-1" (drawn gray, listed last)
pr <- cs_ml_project2(X, centers, names_)
show <- cs_ml_even_sample(length(rows))
xs <- pr$P[show + 1L, 1]; ys <- pr$P[show + 1L, 2]
cl <- name_of(labels[show + 1L])
cent <- rep(FALSE, length(show))
lab <- if (!is.null(ROW_ID)) as.character(frame[[ROW_ID]])[show + 1L] else NULL
if (!is.null(pr$C)) {
  xs <- c(xs, pr$C[, 1]); ys <- c(ys, pr$C[, 2])
  cl <- c(cl, name_of(ids)); cent <- c(cent, rep(TRUE, length(ids)))
  if (!is.null(lab)) lab <- c(lab, sprintf("center %d", ids))
}
level_names <- c(as.character(ids), if (values$n_noise > 0) "-1")
charts <- c(list(cs_chart(
  "clusters", "cluster-scatter", "Clusters",
  list(x = cs_col(pr$labels[1], xs, "numeric"), y = cs_col(pr$labels[2], ys, "numeric"),
       cluster = cs_col("Cluster", cl, "categorical", levels = level_names),
       centroid = if (!is.null(pr$C)) cs_col("Center", cent, "boolean"),
       label = if (!is.null(lab)) cs_col("Row", lab, "categorical")),
  note = if (length(show) == length(rows)) NULL else sprintf("%s of %s rows shown.", format(length(show), big.mark = ","), format(length(rows), big.mark = ","))
)), charts)
if (!is.nan(values$silhouette)) {
  wl <- labels[widths$pick + 1L]
  o <- order(wl, -widths$width)
  charts[[length(charts) + 1L]] <- cs_chart(
    "silhouette", "silhouette-plot", "Silhouette widths",
    list(cluster = cs_col("Cluster", as.character(wl[o]), "categorical", levels = as.character(ids)),
         width = cs_col("Silhouette width", widths$width[o], "numeric")),
    note = if (length(widths$pick) == sum(labels != -1)) NULL else sprintf("%s rows sampled for the silhouette.", format(length(widths$pick), big.mark = ","))
  )
}

# %% Result
if (is.null(summary)) {
  summary <- sprintf("%d cluster%s in %s rows", k, if (k != 1) "s" else "", format(length(rows), big.mark = ","))
  if (values$n_noise > 0) summary <- paste0(summary, sprintf(" (%s noise points)", format(values$n_noise, big.mark = ",")))
  if (!is.nan(values$silhouette)) summary <- paste0(summary, sprintf("; mean silhouette %.2f", values$silhouette))
  summary <- paste0(summary, ".")
}
cs_publish(list(
  title = "Choose the number of clusters",
  engine = cs_engine_info("stats", "cluster", "nanoparquet"),
  n = length(rows),
  summary = summary,
  statistics = list(list(key = "k", label = "Clusters", value = k, format = "integer"),
                    list(key = "silhouette", label = "Mean silhouette", value = values$silhouette)),
  tables = tables,
  values = values,
  charts = charts,
  warnings = warnings,
  artifacts = list(list(key = "labels", path = path, format = "parquet")),
  model = list(kind = "clusterer", features = I(names_), params = list(
    algorithm = "kmeans",
    k_min = 2,
    k_max = 5,
    criterion = "prediction_strength",
    n_init = 3,
    references = 10,
    gap_reference = "uniform",
    gap_starts = 1,
    gap_rule = "tibshirani",
    ps_splits = 8,
    ps_cutoff = 0.8,
    icl_variant = "map",
    covariance = "full",
    distance = "auto",
    scale = "standard",
    missing = "drop"
  ))
))
Python

Comparing k = 2–5 with k-means, the prediction strength (largest k at or above 0.8) recommends k = 2 (4 of 5 criteria agree).

Clusters
2
Mean silhouette
0.5818

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

Clusters

ClusterSizeSharesepal_lengthsepal_widthpetal_lengthpetal_width
110066.7%6.2622.8724.9061.676
25033.3%5.0063.4281.4620.2460

Criteria by k

kWithin-cluster SSMean silhouetteCalinski–HarabaszDavies–BouldinPrediction strengthPrediction strength SD
2222.360.5818251.350.59330.99530.0133
3140.900.4565239.480.82750.65370.1215
4114.350.3819206.680.87960.57610.0907
5105.310.3907170.281.0030.44970.0579
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Choose the number of clusters
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.choose_k 1.1.0 · spec 6455065068179c84
# Dataset: ml_iris (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 import ml as csml
from codesplash.ml import cluster as csc
from codesplash.stats.rng import Rng
import math

from scipy.spatial.distance import cdist
from codesplash.ml import cluster_partition as cpart

# %% Data
FEATURES = ["sepal_length", "sepal_width", "petal_length", "petal_width"]
LABEL = "species"  # known groups (external validation only)
ROW_ID = None  # row labels for charts
SEED = 42
KINDS = {
    "sepal_length": "numeric",
    "sepal_width": "numeric",
    "petal_length": "numeric",
    "petal_width": "numeric",
}
LEVELS = {
}
df = pd.read_parquet("tests/parity/fixtures/ml_iris.parquet", columns=list(dict.fromkeys(FEATURES + [c for c in (LABEL, ROW_ID) if c])))
n_input = len(df)
X, rows, names, frame = csc.prepare(df, FEATURES, KINDS, LEVELS, missing="drop", scale="standard")
warnings = []
if len(rows) < n_input:
    warnings.append(f"{n_input - len(rows)} of {n_input} rows were left out because a feature was missing.")
if len(rows) < 3:
    raise ValueError("Clustering needs at least three rows with every feature present.")
truth = frame[LABEL].astype("object").to_numpy() if LABEL else None
out = csml.out_dir("target/academy-parity/run-8142/discover.choose_k/iris_prediction_strength/out-python")
values = {"n_used": len(rows)}
centers = None
center_ids = None
D = None
extra = {}
tables = []
charts = []
summary = None

# %% Clustering
ALGORITHM = "kmeans"
CRITERION = "prediction_strength"
N_INIT = 3
if ALGORITHM != "kmeans" and CRITERION == "gap":
    raise ValueError("The gap statistic is computed for k-means; choose k-means or another criterion.")
if ALGORITHM != "gmm" and CRITERION == "bic":
    raise ValueError("BIC needs the Gaussian mixture; choose that method or another criterion.")
if ALGORITHM == "gmm":
    raise ValueError("Prediction strength is computed for k-means and PAM; choose one of them or another criterion.")
ks = list(range(2, min(5, len(rows) - 1) + 1))
if len(ks) < 2:
    cs.cs_error("CS_E_TOO_FEW_ROWS", what=f"Comparing k = 2 to 5", min=2 + 2, n=len(rows))
values["k_min"], values["k_max"] = ks[0], ks[-1]
D_choose = None
if ALGORITHM == "pam":
    import kmedoids  # GPL and opt-in (advanced tier), so k-means and Gaussian mixtures run without it

    dist = "auto"
    if dist == "auto":
        dist = "gower" if any(KINDS[f] != "numeric" for f in FEATURES) else "euclidean"
    D_choose = csc.gower(frame, FEATURES, KINDS) if dist == "gower" else cdist(X, X)
rng = Rng(SEED)  # shared stream: the same starts in Python and R
fits = {}
crit = {"within": [], "silhouette": [], "calinski_harabasz": [], "davies_bouldin": []}
if ALGORITHM == "gmm":
    crit["bic"] = []
for kk in ks:
    if ALGORITHM == "kmeans":
        raw_k, centers_k, _ = csc.kmeans_fit(X, kk, rng, N_INIT)
    elif ALGORITHM == "pam":
        res = kmedoids.pam(D_choose, kk, init="build")
        raw_k = np.asarray(res.labels, dtype=np.int64)
        centers_k = X[np.asarray(res.medoids, dtype=np.int64)]
    else:
        raw_k, centers_k, bic, _ = csc.gmm_fit(X, kk, "full", rng, N_INIT, seed=SEED)
        crit["bic"].append(bic)
    fits[kk] = (raw_k, centers_k)
    lab = csc.canonical(raw_k)
    crit["within"].append(csc.within_ss(X, lab))
    crit["silhouette"].append(csc.silhouette(lab, X=None if D_choose is not None else X, D=D_choose, seed=SEED)[0])
    crit["calinski_harabasz"].append(csc.calinski_harabasz(X, lab))
    crit["davies_bouldin"].append(csc.davies_bouldin(X, lab))
best = {
    "elbow": ks[csc.kneedle(ks, crit["within"])],
    "silhouette": ks[int(np.nanargmax(crit["silhouette"]))],
    "calinski_harabasz": ks[int(np.nanargmax(crit["calinski_harabasz"]))],
    "davies_bouldin": ks[int(np.nanargmin(crit["davies_bouldin"]))],
}
if ALGORITHM == "gmm":
    best["bic"] = ks[int(np.argmin(crit["bic"]))]
if CRITERION == "gap":
    rng_gap = Rng(SEED + 1)  # a second shared stream for the reference sets and their starts
    refs = list(csc.reference_sets(X, 10, rng_gap))
    gap, se = [], []
    for i, kk in enumerate(ks):
        logw = np.array([math.log(max(csc.kmeans_fit(ref, kk, rng_gap, 1)[2], 1e-300)) for ref in refs])
        gap.append(float(np.mean(logw) - math.log(max(crit["within"][i], 1e-300))))
        se.append(float(np.std(logw, ddof=1) * math.sqrt(1 + 1 / len(refs))))
    crit["gap"], crit["gap_se"] = gap, se
    best["gap"] = csc.gap_choice(ks, gap, se)
# Prediction strength (Tibshirani & Walther 2005): cluster random halves separately and check how often the training
# centers keep each test cluster's pairs together (twin: cs_cp_prediction_strength)
rng_ps = Rng(SEED + 2)  # a third shared stream for the splits and their fits
if ALGORITHM == "kmeans":
    def ps_fit(idx, kk):
        lab_p, cen_p, _ = csc.kmeans_fit(X[idx], kk, rng_ps, N_INIT)
        return lab_p, cen_p

    def ps_assign(idx, cen_p):
        return cpart.assign_nearest(X[idx], cen_p)
else:
    def ps_fit(idx, kk):
        res_p = kmedoids.pam(D_choose[np.ix_(idx, idx)], kk, init="build")
        return np.asarray(res_p.labels, dtype=np.int64), idx[np.asarray(res_p.medoids, dtype=np.int64)]

    def ps_assign(idx, med_p):
        return np.argmin(D_choose[np.ix_(idx, med_p)], axis=1)
ps_mean, ps_sd = cpart.prediction_strength(len(rows), ks, rng_ps, 8, ps_fit, ps_assign)
crit["prediction_strength"], crit["prediction_strength_sd"] = ps_mean, ps_sd
chosen_ps = cpart.ps_choice(ks, ps_mean, 0.8)
if chosen_ps is None:
    chosen_ps = ks[0]
    warnings.append(f"No k reached a prediction strength of 0.8; the smallest k tried is shown. The data may hold no stable clusters.")
best["prediction_strength"] = chosen_ps
for name, scores in crit.items():
    for kk, v in zip(ks, scores):
        values[f"score[{name},{kk}]"] = float(v)
for name, kk in best.items():
    values[f"best_k[{name}]"] = int(kk)
K_BEST = best[CRITERION]
values["recommended_k"] = int(K_BEST)
values["agree"] = sum(1 for v in best.values() if v == K_BEST)
values["n_criteria"] = len(best)
LABELS = {"elbow": "elbow (kneedle)", "silhouette": "mean silhouette", "gap": "gap statistic (first-SE rule)",
          "calinski_harabasz": "Calinski–Harabasz index", "davies_bouldin": "Davies–Bouldin index", "bic": "BIC"}
LABELS["prediction_strength"] = "prediction strength (largest k at or above 0.8)"
values["criterion_label"] = LABELS[CRITERION]
values["algorithm_label"] = {"kmeans": "k-means", "pam": "PAM", "gmm": "a Gaussian mixture"}[ALGORITHM]
raw, centers = fits[K_BEST]
D = D_choose
NAMES = {"within": "Within-cluster SS", "silhouette": "Mean silhouette", "calinski_harabasz": "Calinski–Harabasz",
         "davies_bouldin": "Davies–Bouldin", "gap": "Gap", "bic": "BIC"}
NAMES.update({"prediction_strength": "Prediction strength", "prediction_strength_sd": "Prediction strength SD"})
plot_k, plot_s, plot_c, plot_ch = [], [], [], []
for name in [c for c in ["within", "silhouette", "gap", "calinski_harabasz", "davies_bouldin", "bic", "prediction_strength"] if c in crit]:
    chosen_k = best["elbow" if name == "within" else name]
    for kk, v in zip(ks, crit[name]):
        plot_k.append(kk)
        plot_s.append(float(v))
        plot_c.append(NAMES[name])
        plot_ch.append(bool(kk == chosen_k))
charts.append(cs.chart(
    "choose_k", "elbow-plot", "Criteria by number of clusters",
    {"k": cs.col("Clusters (k)", plot_k, "numeric"), "score": cs.col("Score", plot_s, "numeric"),
     "criterion": cs.col("Criterion", plot_c, "categorical"), "chosen": cs.col("Recommended", plot_ch, "boolean")},
    note=f"Recommended k = {K_BEST} by the {LABELS[CRITERION]}.",
))
cols = [{"key": "k", "label": "k", "type": "integer"}] + [
    {"key": n, "label": NAMES.get(n, "Gap SE" if n == "gap_se" else n), "type": "number"} for n in crit
]
tables.append({
    "key": "choose_k", "title": "Criteria by k", "columns": cols,
    "rows": [{"k": kk, **{n: float(crit[n][i]) for n in crit}} for i, kk in enumerate(ks)],
})
summary = (
    f"Comparing k = {ks[0]}–{ks[-1]} with {values['algorithm_label']}, the {LABELS[CRITERION]} recommends k = {K_BEST} "
    f"({values['agree']} of {values['n_criteria']} criteria agree)."
)

# %% Canonical labels and validation
labels = csc.canonical(raw)
ids = [int(c) for c in sorted(set(labels.tolist())) if c != -1]
k = len(ids)
values["k"] = k
values["n_noise"] = int(np.sum(labels == -1))
if centers is not None:
    # reorder centers to canonical ids: the raw id of each canonical cluster
    raw_of = {c: raw[np.flatnonzero(labels == c)[0]] for c in ids}
    pos = {int(r): i for i, r in enumerate(center_ids if center_ids is not None else range(len(centers)))}
    centers = np.array([centers[pos[int(raw_of[c])]] for c in ids])
    for c, row in zip(ids, centers):
        for name, v in zip(names, row):
            values[f"center[{c},{name}]"] = float(v)
for c, m in csc.sizes(labels).items():
    values[f"size[{c}]"] = m
check = csc.validation(X, labels, truth, D=D, cap=3000, seed=SEED)
widths, picked = check.pop("_widths")
values.update(check)
# per-cluster means of numeric features in their own units (interpretation)
profile_rows = []
for c in ids:
    member = labels == c
    row = {"cluster": c, "size": int(member.sum()), "share": float(member.mean())}
    for f in FEATURES:
        if KINDS[f] == "numeric":
            m = float(np.nanmean(pd.to_numeric(frame[f], errors="coerce").to_numpy(dtype=np.float64)[member]))
            row[f] = m
            values[f"mean[{c},{f}]"] = m
        else:
            top = pd.Series(frame[f].astype("object").to_numpy()[member]).dropna().astype(str).value_counts()
            row[f] = f"{top.index[0]} ({top.iloc[0] / member.sum():.0%})" if len(top) else ""
    profile_rows.append(row)
tables.insert(0, {
    "key": "clusters",
    "title": "Clusters",
    "columns": [
        {"key": "cluster", "label": "Cluster", "type": "integer"},
        {"key": "size", "label": "Size", "type": "integer"},
        {"key": "share", "label": "Share", "type": "percent"},
    ]
    + [{"key": f, "label": f, "type": "number" if KINDS[f] == "numeric" else "string"} for f in FEATURES],
    "rows": profile_rows,
})

# %% Labels file and charts
path = csc.write_labels(out, rows, labels, **extra)
name_of = lambda c: str(c)  # noqa: E731  — noise stays "-1" (drawn gray, listed last)
P, C, axes = csc.project2(X, centers, names)
show = csc.even_sample(len(rows))
point_labels = [str(v) for v in frame[ROW_ID].astype("object").to_numpy()[show]] if ROW_ID else None
xs, ys = list(P[show, 0]), list(P[show, 1])
cl = [name_of(c) for c in labels[show]]
cent = [False] * len(show)
lab = point_labels
if C is not None:
    xs += list(C[:, 0])
    ys += list(C[:, 1])
    cl += [name_of(c) for c in ids]
    cent += [True] * len(ids)
    lab = None if lab is None else lab + [f"center {c}" for c in ids]
level_names = [str(c) for c in ids] + (["-1"] if values["n_noise"] else [])
charts.insert(0, cs.chart(
    "clusters", "cluster-scatter", "Clusters",
    {
        "x": cs.col(axes[0], xs, "numeric"),
        "y": cs.col(axes[1], ys, "numeric"),
        "cluster": cs.col("Cluster", cl, "categorical", levels=level_names),
        "centroid": cs.col("Center", cent, "boolean") if C is not None else None,
        "label": cs.col("Row", lab, "categorical") if lab is not None else None,
    },
    note=None if len(show) == len(rows) else f"{len(show):,} of {len(rows):,} rows shown.",
))
if not np.isnan(values["silhouette"]):
    wl = labels[picked]
    order = np.lexsort((-widths, wl))
    charts.append(cs.chart(
        "silhouette", "silhouette-plot", "Silhouette widths",
        {"cluster": cs.col("Cluster", [str(c) for c in wl[order]], "categorical", levels=[str(c) for c in ids]),
         "width": cs.col("Silhouette width", list(widths[order]), "numeric")},
        note=None if len(picked) == int(np.sum(labels != -1)) else f"{len(picked):,} rows sampled for the silhouette.",
    ))

# %% Result
if summary is None:
    summary = f"{k} cluster{'s' if k != 1 else ''} in {len(rows):,} rows"
    if values["n_noise"]:
        summary += f" ({values['n_noise']:,} noise points)"
    if not np.isnan(values["silhouette"]):
        summary += f"; mean silhouette {values['silhouette']:.2f}"
    summary += "."
cs.publish({
    "title": "Choose the number of clusters",
    "engine": cs.engine_info("scikit-learn", "kmedoids", "numpy", "pandas"),
    "n": len(rows),
    "summary": summary,
    "statistics": [
        {"key": "k", "label": "Clusters", "value": k, "format": "integer"},
        {"key": "silhouette", "label": "Mean silhouette", "value": values["silhouette"]},
    ],
    "tables": tables,
    "values": values,
    "charts": charts,
    "warnings": warnings,
    "artifacts": [{"key": "labels", "path": path, "format": "parquet"}],
    "model": {"kind": "clusterer", "features": names, "params": {
        "algorithm": "kmeans",
        "k_min": 2,
        "k_max": 5,
        "criterion": "prediction_strength",
        "n_init": 3,
        "references": 10,
        "gap_reference": "uniform",
        "gap_starts": 1,
        "gap_rule": "tibshirani",
        "ps_splits": 8,
        "ps_cutoff": 0.8,
        "icl_variant": "map",
        "covariance": "full",
        "distance": "auto",
        "scale": "standard",
        "missing": "drop",
    }},
})

On iris it recommends kk = 2, though there are three species: two of them overlap, and a stable coarse partition can hide real subgroups. Splits must respect subjects and time, and tiny validation clusters make the pair counts noisy.

06

Bootstrap stability with Jaccard

Read

Bootstrap stabilityCluster stability (bootstrap Jaccard)How well each cluster comes back when the data are resampled, as the mean Jaccard overlap with its best match. reruns the whole pipeline (scaling, clustering, everything) on resampled rows. Each original cluster CC is matched to its most similar resampled cluster by Jaccard similarity, J=∣C∩C∗∣/∣C∪C∗∣J=\lvert C\cap C^*\rvert/\lvert C\cup C^*\rvert, and the matches are averaged over resamples.

How stable are the clusters? (bootstrap)Recorded · Python and R agreeRecorded 2026-11-25 · 34 values compared
R

Over 20 bootstrap resamples the 3 k-means clusters have mean Jaccard 0.90 (lowest 0.85); 3 highly stable, 0 dissolve.

Clusters
3
Mean silhouette
0.4565

Clusters

ClusterSizeSharesepal_lengthsepal_widthpetal_lengthpetal_width
15536.7%6.6963.0605.4181.938
24932.7%5.0163.4511.4650.2449
34630.7%5.7042.6354.2151.333

Cluster stability (mean bootstrap Jaccard)

ClusterJaccardReading
10.8559highly stable
20.9849highly stable
30.8535highly stable
The exact R script · R R version 4.5.1 (2025-06-13)
# How stable are the clusters? (bootstrap)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.stability 1.1.1 · spec f4026b527f0f75a0
# Dataset: ml_iris (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("sepal_length", "sepal_width", "petal_length", "petal_width")
LABEL <- "species"  # known groups (external validation only)
ROW_ID <- NULL  # row labels for charts
SEED <- 42
KINDS <- list(
  sepal_length = "numeric",
  sepal_width = "numeric",
  petal_length = "numeric",
  petal_width = "numeric"
)
LEVELS <- list(
)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_iris.parquet", col_select = unique(c(FEATURES, LABEL, ROW_ID))))
n_input <- nrow(df)
prep <- cs_ml_cluster_prepare(df, FEATURES, KINDS, LEVELS, missing = "drop", scale = "standard")
X <- prep$X; rows <- prep$rows; names_ <- prep$names; frame <- prep$frame
warnings <- list()
if (length(rows) < n_input) {
  warnings <- c(warnings, sprintf("%d of %d rows were left out because a feature was missing.", n_input - length(rows), n_input))
}
if (length(rows) < 3) stop("Clustering needs at least three rows with every feature present.")
truth <- if (!is.null(LABEL)) as.character(frame[[LABEL]]) else NULL
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.stability/iris_three/out-r")
values <- list(n_used = length(rows))
centers <- NULL
center_ids <- NULL
D <- NULL
extra <- list()
tables <- list()
charts <- list()
summary <- NULL

# %% Clustering
ALGORITHM <- "kmeans"
K <- 3
BOOTS <- 20
N_INIT <- 5
if (ALGORITHM != "density" && K >= length(rows)) cs_error("CS_E_TOO_FEW_ROWS", what = sprintf("Clustering with k = %d", K), min = K + 1L, n = length(rows))
if (ALGORITHM %in% c("pam", "hierarchical", "density") && length(rows) > 3000) stop("This algorithm keeps every pairwise distance on each resample; use it on at most 3,000 rows (or k-means).")
if (ALGORITHM == "kmeans") {
  algo_label <- "k-means"
  cluster_fit <- function(Xb, rng) cs_ml_kmeans_lloyd(Xb, K, rng, n_init = N_INIT)
} else if (ALGORITHM == "pam") {
  algo_label <- "PAM"
  cluster_fit <- function(Xb, rng) if (nrow(Xb) > K) cs_ml_pam_labels(Xb, K) else seq_len(nrow(Xb)) - 1L
} else if (ALGORITHM == "hierarchical") {
  LINKAGE <- "ward"
  algo_label <- sprintf("hierarchical (%s)", LINKAGE)
  cluster_fit <- function(Xb, rng) {
    if (nrow(Xb) <= K) return(seq_len(nrow(Xb)) - 1L)
    unname(stats::cutree(stats::hclust(stats::dist(Xb), method = if (LINKAGE == "ward") "ward.D2" else LINKAGE), k = K)) - 1L
  }
} else {
  MIN_SAMPLES <- 5
  EPS <- NULL
  if (MIN_SAMPLES > length(rows)) cs_error("CS_E_TOO_FEW_ROWS", what = sprintf("min_samples = %d", MIN_SAMPLES), min = MIN_SAMPLES, n = length(rows))
  .o <- cs_ml_optics(X, MIN_SAMPLES)
  if (is.null(EPS)) {
    finite <- sort(.o$core[is.finite(.o$core)])
    EPS <- finite[cs_ml_kneedle(seq_along(finite), finite) + 1L]
    if (EPS <= 0) EPS <- if (any(finite > 0)) finite[finite > 0][1] else 1
    EPS <- EPS * (1 + 1e-9)  # the knee is a real distance: make the boundary inclusive in both engines
    warnings <- c(warnings, sprintf("Neighborhood radius chosen automatically at the knee of the core distances: %s.", formatC(EPS, digits = 4, format = "g")))
  }
  values$eps <- as.numeric(EPS)
  values$min_samples <- MIN_SAMPLES
  algo_label <- "density"
  cluster_fit <- function(Xb, rng) {
    if (nrow(Xb) < MIN_SAMPLES) return(rep(-1L, nrow(Xb)))
    o <- cs_ml_optics(Xb, MIN_SAMPLES)
    cs_ml_optics_cut(o$order, o$reach, o$core, EPS)
  }
}
base <- cs_ml_canonical(cluster_fit(X, cs_rng(SEED)))
if (!any(base != -1)) stop("No clusters to test: every row is noise at this radius.")
sample <- cs_ml_even_sample(length(rows), 100)
stab <- cs_ml_bootstrap_stability(X, base, K, BOOTS, SEED, cluster_fit, sample, unique = ALGORITHM != "kmeans")
jac <- stab$jaccard
for (i in seq_along(stab$ids)) values[[sprintf("jaccard[%d]", stab$ids[i])]] <- jac[i]
values$mean_jaccard <- mean(jac)
values$min_jaccard <- min(jac)
values$n_dissolved <- sum(jac <= 0.5)
values$n_stable <- sum(jac >= 0.85)
values$pac <- stab$pac
values$boots <- BOOTS
values$algorithm <- ALGORITHM
raw <- base
verdict <- function(j) if (j >= 0.85) "highly stable" else if (j >= 0.75) "stable" else if (j >= 0.6) "a pattern, not crisp" else if (j > 0.5) "weak" else "dissolves"
tables[[length(tables) + 1L]] <- list(
  key = "stability", title = "Cluster stability (mean bootstrap Jaccard)",
  columns = list(list(key = "cluster", label = "Cluster", type = "integer"), list(key = "jaccard", label = "Jaccard", type = "number"),
                 list(key = "verdict", label = "Reading")),
  rows = lapply(seq_along(stab$ids), function(i) list(cluster = stab$ids[i], jaccard = jac[i], verdict = verdict(jac[i])))
)
pos <- order(base[sample + 1L], seq_along(sample), method = "radix")
M <- stab$consensus[pos, pos, drop = FALSE]
grid <- expand.grid(col = seq_along(pos), row = seq_along(pos))
charts[[length(charts) + 1L]] <- cs_chart(
  "consensus", "consensus-heatmap", "How often rows cluster together",
  list(col = cs_col("Row (by cluster)", grid$col, "numeric"), row = cs_col("Row (by cluster)", grid$row, "numeric"),
       share = cs_col("Share of resamples together", M[cbind(grid$row, grid$col)], "numeric")),
  note = sprintf("%d evenly spaced rows grouped by cluster; crisp clusters show solid blocks (PAC = %.2f).", length(sample), stab$pac)
)
summary <- sprintf("Over %d bootstrap resamples the %d %s clusters have mean Jaccard %.2f (lowest %.2f); %d highly stable, %d dissolve.",
                   BOOTS, length(jac), algo_label, mean(jac), min(jac), values$n_stable, values$n_dissolved)

# %% Canonical labels and validation
labels <- cs_ml_canonical(raw)
ids <- sort(unique(labels[labels != -1]))
k <- length(ids)
values$k <- k
values$n_noise <- sum(labels == -1)
if (!is.null(centers)) {
  cid <- if (is.null(center_ids)) seq_len(nrow(centers)) - 1L else center_ids
  raw_of <- vapply(ids, function(c) raw[which(labels == c)[1]], numeric(1))
  centers <- centers[match(raw_of, cid), , drop = FALSE]
  for (i in seq_along(ids)) for (j in seq_along(names_)) {
    values[[sprintf("center[%d,%s]", ids[i], names_[j])]] <- centers[i, j]
  }
}
sz <- cs_ml_cluster_sizes(labels)
for (c in names(sz)) values[[sprintf("size[%s]", c)]] <- sz[[c]]
check <- cs_ml_cluster_validation(X, labels, truth, D = D, cap = 3000, seed = SEED)
widths <- check$.widths
check$.widths <- NULL
values <- c(values, check)
profile_rows <- list()
for (c in ids) {
  member <- labels == c
  row <- list(cluster = c, size = sum(member), share = mean(member))
  for (f in FEATURES) {
    if (identical(KINDS[[f]], "numeric")) {
      m <- mean(suppressWarnings(as.numeric(frame[[f]]))[member], na.rm = TRUE)
      row[[f]] <- m
      values[[sprintf("mean[%d,%s]", c, f)]] <- m
    } else {
      v <- as.character(frame[[f]])[member]
      v <- v[!is.na(v)]
      top <- if (length(v)) sort(table(v), decreasing = TRUE) else NULL
      row[[f]] <- if (length(top)) sprintf("%s (%.0f%%)", names(top)[1], 100 * top[[1]] / sum(member)) else ""
    }
  }
  profile_rows[[length(profile_rows) + 1L]] <- row
}
tables <- c(list(list(
  key = "clusters", title = "Clusters",
  columns = c(list(list(key = "cluster", label = "Cluster", type = "integer"),
                   list(key = "size", label = "Size", type = "integer"),
                   list(key = "share", label = "Share", type = "percent")),
              lapply(FEATURES, function(f) list(key = f, label = f, type = if (identical(KINDS[[f]], "numeric")) "number" else "string"))),
  rows = profile_rows
)), tables)

# %% Labels file and charts
path <- do.call(cs_ml_write_labels, c(list(out, rows, labels), extra))
name_of <- function(c) as.character(c)  # noise stays "-1" (drawn gray, listed last)
pr <- cs_ml_project2(X, centers, names_)
show <- cs_ml_even_sample(length(rows))
xs <- pr$P[show + 1L, 1]; ys <- pr$P[show + 1L, 2]
cl <- name_of(labels[show + 1L])
cent <- rep(FALSE, length(show))
lab <- if (!is.null(ROW_ID)) as.character(frame[[ROW_ID]])[show + 1L] else NULL
if (!is.null(pr$C)) {
  xs <- c(xs, pr$C[, 1]); ys <- c(ys, pr$C[, 2])
  cl <- c(cl, name_of(ids)); cent <- c(cent, rep(TRUE, length(ids)))
  if (!is.null(lab)) lab <- c(lab, sprintf("center %d", ids))
}
level_names <- c(as.character(ids), if (values$n_noise > 0) "-1")
charts <- c(list(cs_chart(
  "clusters", "cluster-scatter", "Clusters",
  list(x = cs_col(pr$labels[1], xs, "numeric"), y = cs_col(pr$labels[2], ys, "numeric"),
       cluster = cs_col("Cluster", cl, "categorical", levels = level_names),
       centroid = if (!is.null(pr$C)) cs_col("Center", cent, "boolean"),
       label = if (!is.null(lab)) cs_col("Row", lab, "categorical")),
  note = if (length(show) == length(rows)) NULL else sprintf("%s of %s rows shown.", format(length(show), big.mark = ","), format(length(rows), big.mark = ","))
)), charts)
if (!is.nan(values$silhouette)) {
  wl <- labels[widths$pick + 1L]
  o <- order(wl, -widths$width)
  charts[[length(charts) + 1L]] <- cs_chart(
    "silhouette", "silhouette-plot", "Silhouette widths",
    list(cluster = cs_col("Cluster", as.character(wl[o]), "categorical", levels = as.character(ids)),
         width = cs_col("Silhouette width", widths$width[o], "numeric")),
    note = if (length(widths$pick) == sum(labels != -1)) NULL else sprintf("%s rows sampled for the silhouette.", format(length(widths$pick), big.mark = ","))
  )
}

# %% Result
if (is.null(summary)) {
  summary <- sprintf("%d cluster%s in %s rows", k, if (k != 1) "s" else "", format(length(rows), big.mark = ","))
  if (values$n_noise > 0) summary <- paste0(summary, sprintf(" (%s noise points)", format(values$n_noise, big.mark = ",")))
  if (!is.nan(values$silhouette)) summary <- paste0(summary, sprintf("; mean silhouette %.2f", values$silhouette))
  summary <- paste0(summary, ".")
}
cs_publish(list(
  title = "How stable are the clusters? (bootstrap)",
  engine = cs_engine_info("codesplashr", "nanoparquet"),
  n = length(rows),
  summary = summary,
  statistics = list(list(key = "k", label = "Clusters", value = k, format = "integer"),
                    list(key = "silhouette", label = "Mean silhouette", value = values$silhouette)),
  tables = tables,
  values = values,
  charts = charts,
  warnings = warnings,
  artifacts = list(list(key = "labels", path = path, format = "parquet")),
  model = list(kind = "clusterer", features = I(names_), params = list(
    algorithm = "kmeans",
    k = 3,
    linkage = "ward",
    min_samples = 5,
    eps = NULL,
    boots = 20,
    n_init = 5,
    scale = "standard",
    missing = "drop"
  ))
))
Python

Over 20 bootstrap resamples the 3 k-means clusters have mean Jaccard 0.90 (lowest 0.85); 3 highly stable, 0 dissolve.

Clusters
3
Mean silhouette
0.4565

Clusters

ClusterSizeSharesepal_lengthsepal_widthpetal_lengthpetal_width
15536.7%6.6963.0605.4181.938
24932.7%5.0163.4511.4650.2449
34630.7%5.7042.6354.2151.333

Cluster stability (mean bootstrap Jaccard)

ClusterJaccardReading
10.8559highly stable
20.9849highly stable
30.8535highly stable
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# How stable are the clusters? (bootstrap)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.stability 1.1.1 · spec f4026b527f0f75a0
# Dataset: ml_iris (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 import ml as csml
from codesplash.ml import cluster as csc
from codesplash.stats.rng import Rng
from scipy.cluster.hierarchy import fcluster, linkage
from scipy.spatial.distance import pdist

from codesplash.ml import discover_ext as dx

# %% Data
FEATURES = ["sepal_length", "sepal_width", "petal_length", "petal_width"]
LABEL = "species"  # known groups (external validation only)
ROW_ID = None  # row labels for charts
SEED = 42
KINDS = {
    "sepal_length": "numeric",
    "sepal_width": "numeric",
    "petal_length": "numeric",
    "petal_width": "numeric",
}
LEVELS = {
}
df = pd.read_parquet("tests/parity/fixtures/ml_iris.parquet", columns=list(dict.fromkeys(FEATURES + [c for c in (LABEL, ROW_ID) if c])))
n_input = len(df)
X, rows, names, frame = csc.prepare(df, FEATURES, KINDS, LEVELS, missing="drop", scale="standard")
warnings = []
if len(rows) < n_input:
    warnings.append(f"{n_input - len(rows)} of {n_input} rows were left out because a feature was missing.")
if len(rows) < 3:
    raise ValueError("Clustering needs at least three rows with every feature present.")
truth = frame[LABEL].astype("object").to_numpy() if LABEL else None
out = csml.out_dir("target/academy-parity/run-8142/discover.stability/iris_three/out-python")
values = {"n_used": len(rows)}
centers = None
center_ids = None
D = None
extra = {}
tables = []
charts = []
summary = None

# %% Clustering
ALGORITHM = "kmeans"
K = 3
BOOTS = 20
N_INIT = 5
if ALGORITHM != "density" and K >= len(rows):
    cs.cs_error("CS_E_TOO_FEW_ROWS", what=f"Clustering with k = {K}", min=K + 1, n=len(rows))
if ALGORITHM in ("pam", "hierarchical", "density") and len(rows) > 3000:
    raise ValueError("This algorithm keeps every pairwise distance on each resample; use it on at most 3,000 rows (or k-means).")
if ALGORITHM == "kmeans":
    algo_label = "k-means"
    cluster_fit = lambda Xb, rng: dx.kmeans_lloyd(Xb, K, rng, n_init=N_INIT)  # noqa: E731
elif ALGORITHM == "pam":
    algo_label = "PAM"
    cluster_fit = lambda Xb, rng: dx.pam_labels(Xb, K) if len(Xb) > K else np.arange(len(Xb))  # noqa: E731
elif ALGORITHM == "hierarchical":
    LINKAGE = "ward"
    algo_label = f"hierarchical ({LINKAGE})"
    cluster_fit = lambda Xb, rng: fcluster(linkage(pdist(Xb), method=LINKAGE), K, criterion="maxclust").astype(np.int64) - 1 if len(Xb) > K else np.arange(len(Xb))  # noqa: E731
else:
    MIN_SAMPLES = 5
    EPS = None
    if MIN_SAMPLES > len(rows):
        cs.cs_error("CS_E_TOO_FEW_ROWS", what=f"min_samples = {MIN_SAMPLES}", min=MIN_SAMPLES, n=len(rows))
    _o = dx.optics(X, MIN_SAMPLES)
    if EPS is None:
        finite = np.sort(_o["core"][np.isfinite(_o["core"])])
        EPS = float(finite[csc.kneedle(np.arange(1, len(finite) + 1), finite)])
        if EPS <= 0:
            EPS = float(finite[finite > 0][0]) if np.any(finite > 0) else 1.0
        EPS *= 1 + 1e-9  # the knee is a real distance: make the boundary inclusive in both engines
        warnings.append(f"Neighborhood radius chosen automatically at the knee of the core distances: {EPS:.4g}.")
    values["eps"] = float(EPS)
    values["min_samples"] = MIN_SAMPLES
    algo_label = "density"

    def cluster_fit(Xb, rng):
        if len(Xb) < MIN_SAMPLES:
            return np.full(len(Xb), -1, dtype=np.int64)
        o = dx.optics(Xb, MIN_SAMPLES)
        return dx.optics_cut(o["order"], o["reach"], o["core"], EPS)
base = csc.canonical(cluster_fit(X, Rng(SEED)))
if not np.any(base != -1):
    raise ValueError("No clusters to test: every row is noise at this radius.")
sample = csc.even_sample(len(rows), 100)
stab = dx.bootstrap_stability(X, base, K, BOOTS, SEED, cluster_fit, sample, unique=ALGORITHM != "kmeans")
jac = stab["jaccard"]
for c, j in zip(stab["ids"], jac):
    values[f"jaccard[{c}]"] = float(j)
values["mean_jaccard"] = float(np.mean(jac))
values["min_jaccard"] = float(np.min(jac))
values["n_dissolved"] = int(np.sum(jac <= 0.5))
values["n_stable"] = int(np.sum(jac >= 0.85))
values["pac"] = stab["pac"]
values["boots"] = BOOTS
values["algorithm"] = ALGORITHM
raw = base
verdict = lambda j: "highly stable" if j >= 0.85 else ("stable" if j >= 0.75 else ("a pattern, not crisp" if j >= 0.6 else ("weak" if j > 0.5 else "dissolves")))  # noqa: E731
tables.append({
    "key": "stability",
    "title": "Cluster stability (mean bootstrap Jaccard)",
    "columns": [{"key": "cluster", "label": "Cluster", "type": "integer"}, {"key": "jaccard", "label": "Jaccard", "type": "number"},
                {"key": "verdict", "label": "Reading"}],
    "rows": [{"cluster": c, "jaccard": float(j), "verdict": verdict(j)} for c, j in zip(stab["ids"], jac)],
})
pos = np.lexsort((np.arange(len(sample)), base[sample]))  # sample rows grouped by cluster
M = stab["consensus"][np.ix_(pos, pos)]
xs, ys, vs = [], [], []
for i in range(len(pos)):
    for j in range(len(pos)):
        xs.append(j + 1)
        ys.append(i + 1)
        vs.append(float(M[i, j]))
charts.append(cs.chart(
    "consensus", "consensus-heatmap", "How often rows cluster together",
    {"col": cs.col("Row (by cluster)", xs, "numeric"), "row": cs.col("Row (by cluster)", ys, "numeric"),
     "share": cs.col("Share of resamples together", vs, "numeric")},
    note=f"{len(sample)} evenly spaced rows grouped by cluster; crisp clusters show solid blocks (PAC = {stab['pac']:.2f}).",
))
summary = (
    f"Over {BOOTS} bootstrap resamples the {len(jac)} {algo_label} clusters have mean Jaccard {np.mean(jac):.2f} "
    f"(lowest {np.min(jac):.2f}); {values['n_stable']} highly stable, {values['n_dissolved']} dissolve."
)

# %% Canonical labels and validation
labels = csc.canonical(raw)
ids = [int(c) for c in sorted(set(labels.tolist())) if c != -1]
k = len(ids)
values["k"] = k
values["n_noise"] = int(np.sum(labels == -1))
if centers is not None:
    # reorder centers to canonical ids: the raw id of each canonical cluster
    raw_of = {c: raw[np.flatnonzero(labels == c)[0]] for c in ids}
    pos = {int(r): i for i, r in enumerate(center_ids if center_ids is not None else range(len(centers)))}
    centers = np.array([centers[pos[int(raw_of[c])]] for c in ids])
    for c, row in zip(ids, centers):
        for name, v in zip(names, row):
            values[f"center[{c},{name}]"] = float(v)
for c, m in csc.sizes(labels).items():
    values[f"size[{c}]"] = m
check = csc.validation(X, labels, truth, D=D, cap=3000, seed=SEED)
widths, picked = check.pop("_widths")
values.update(check)
# per-cluster means of numeric features in their own units (interpretation)
profile_rows = []
for c in ids:
    member = labels == c
    row = {"cluster": c, "size": int(member.sum()), "share": float(member.mean())}
    for f in FEATURES:
        if KINDS[f] == "numeric":
            m = float(np.nanmean(pd.to_numeric(frame[f], errors="coerce").to_numpy(dtype=np.float64)[member]))
            row[f] = m
            values[f"mean[{c},{f}]"] = m
        else:
            top = pd.Series(frame[f].astype("object").to_numpy()[member]).dropna().astype(str).value_counts()
            row[f] = f"{top.index[0]} ({top.iloc[0] / member.sum():.0%})" if len(top) else ""
    profile_rows.append(row)
tables.insert(0, {
    "key": "clusters",
    "title": "Clusters",
    "columns": [
        {"key": "cluster", "label": "Cluster", "type": "integer"},
        {"key": "size", "label": "Size", "type": "integer"},
        {"key": "share", "label": "Share", "type": "percent"},
    ]
    + [{"key": f, "label": f, "type": "number" if KINDS[f] == "numeric" else "string"} for f in FEATURES],
    "rows": profile_rows,
})

# %% Labels file and charts
path = csc.write_labels(out, rows, labels, **extra)
name_of = lambda c: str(c)  # noqa: E731  — noise stays "-1" (drawn gray, listed last)
P, C, axes = csc.project2(X, centers, names)
show = csc.even_sample(len(rows))
point_labels = [str(v) for v in frame[ROW_ID].astype("object").to_numpy()[show]] if ROW_ID else None
xs, ys = list(P[show, 0]), list(P[show, 1])
cl = [name_of(c) for c in labels[show]]
cent = [False] * len(show)
lab = point_labels
if C is not None:
    xs += list(C[:, 0])
    ys += list(C[:, 1])
    cl += [name_of(c) for c in ids]
    cent += [True] * len(ids)
    lab = None if lab is None else lab + [f"center {c}" for c in ids]
level_names = [str(c) for c in ids] + (["-1"] if values["n_noise"] else [])
charts.insert(0, cs.chart(
    "clusters", "cluster-scatter", "Clusters",
    {
        "x": cs.col(axes[0], xs, "numeric"),
        "y": cs.col(axes[1], ys, "numeric"),
        "cluster": cs.col("Cluster", cl, "categorical", levels=level_names),
        "centroid": cs.col("Center", cent, "boolean") if C is not None else None,
        "label": cs.col("Row", lab, "categorical") if lab is not None else None,
    },
    note=None if len(show) == len(rows) else f"{len(show):,} of {len(rows):,} rows shown.",
))
if not np.isnan(values["silhouette"]):
    wl = labels[picked]
    order = np.lexsort((-widths, wl))
    charts.append(cs.chart(
        "silhouette", "silhouette-plot", "Silhouette widths",
        {"cluster": cs.col("Cluster", [str(c) for c in wl[order]], "categorical", levels=[str(c) for c in ids]),
         "width": cs.col("Silhouette width", list(widths[order]), "numeric")},
        note=None if len(picked) == int(np.sum(labels != -1)) else f"{len(picked):,} rows sampled for the silhouette.",
    ))

# %% Result
if summary is None:
    summary = f"{k} cluster{'s' if k != 1 else ''} in {len(rows):,} rows"
    if values["n_noise"]:
        summary += f" ({values['n_noise']:,} noise points)"
    if not np.isnan(values["silhouette"]):
        summary += f"; mean silhouette {values['silhouette']:.2f}"
    summary += "."
cs.publish({
    "title": "How stable are the clusters? (bootstrap)",
    "engine": cs.engine_info("numpy", "numpy", "pandas"),
    "n": len(rows),
    "summary": summary,
    "statistics": [
        {"key": "k", "label": "Clusters", "value": k, "format": "integer"},
        {"key": "silhouette", "label": "Mean silhouette", "value": values["silhouette"]},
    ],
    "tables": tables,
    "values": values,
    "charts": charts,
    "warnings": warnings,
    "artifacts": [{"key": "labels", "path": path, "format": "parquet"}],
    "model": {"kind": "clusterer", "features": names, "params": {
        "algorithm": "kmeans",
        "k": 3,
        "linkage": "ward",
        "min_samples": 5,
        "eps": None,
        "boots": 20,
        "n_init": 5,
        "scale": "standard",
        "missing": "drop",
    }},
})

Shortened for the Academy: 3 chart(s) dropped to stay under 100 KB; 3 chart(s) dropped to stay under 100 KB.

The mean Jaccard was 0.898. Stability is not correctness: a rigid method can split the data the same wrong way every time. And bootstrapping, subsampling and jittering ask different robustness questions, so say which you ran.

07

Resample and recluster

Explore

AExplorable · Do the clusters survive resampling?

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

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

How sure?

Data

3
120
Simulating…

Commit your prediction above to see the result

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

Make your prediction to see the result.

Real groups come back in every resample. On pure noise, k-means still returns three clusters, but each cluster's overlap with its best match falls as the borders move.

08

Where each idea stands in CodeSplash

Read
EntryIn CodeSplash
SigClust (EVA006)Runs in CodeSplash: Is the split significant? (SigClust)
Selective inference (EVA007)Runs in CodeSplash: Are these clusters really different? (selective inference)
Prediction strength (EVA008)Runs in CodeSplash: a criterion in Choose the number of clusters, for k-means and PAM assignment rules
Bootstrap stability (EVA009)Runs in CodeSplash: How stable are the clusters? (bootstrap)
09

Check your understanding

Checkpoint

Check yourself

What is SigClust's null hypothesis?

Show the answer

Answer: b

SigClust asks whether a 2-means split is stronger than one Gaussian cloud would produce, using simulations from a fitted Gaussian.

Check yourself

SigClust rejects its null on gene expression data. What have you shown?

Show the answer

Answer: b

Rejecting Gaussianity is a narrower claim than discovering subtypes. Check alternative explanations before naming groups.

Check yourself

Why is an ordinary t-test between two clusters found by hierarchical clustering invalid?

Show the answer

Answer: b

The algorithm draws boundaries where means differ. Selective inference conditions on that selection to get a valid p-value.

Check yourself

You cluster a UMAP embedding with k-means and use the selective p-value from a hierarchical-clustering method. Is it valid?

Show the answer

Answer: b

Conditioning only corrects for the selection it models. Record the full pipeline and use a method built for it.

Check yourself

How does prediction strength judge a choice of kk?

Show the answer

Answer: a

Agreement on co-membership for new rows says the clusters can be reproduced. The minimum over clusters guards against one cluster that never reappears.

Check yourself

Prediction strength recommends two clusters, but you know there are three overlapping groups. What does that tell you?

Show the answer

Answer: b

High prediction strength favors partitions that reproduce. It can't promise you see every useful subgroup.

Check yourself

For bootstrap stability, what must be rerun on each resample?

Show the answer

Answer: b

Scaling is part of the model. Refitting everything inside each resample is what makes the stability honest.

Check yourself

A clustering is perfectly stable across bootstraps. Is it correct?

Show the answer

Answer: b

Stability rules out flukes of the sample. It doesn't rule out a consistently wrong cluster idea or a nuisance variable.

10

Do it on your own data

In the app

After you choose a clustering, run How stable are the clusters? (bootstrap) with the same settings, add prediction strength in Choose the number of clusters, and test any split you plan to report with SigClust or selective inference before you describe the groups.

Concepts in this lesson