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.
What runs in CodeSplash
- EVA006SigClust Runs in CodeSplash
- EVA007Selective inference after hierarchical clustering Runs in CodeSplash (Experimental)
- EVA008Prediction strength Runs in CodeSplash
- EVA009Bootstrap cluster stability with Jaccard matching Runs in CodeSplash
- Is the split significant? (SigClust) Verified in Python and R
- Are these clusters really different? (selective inference) Experimental
- Choose the number of clusters Verified in Python and R
- How stable are the clusters? (bootstrap) Verified in Python and R
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
Clusters always come back
ReadAsk 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:
| Check | Question |
|---|---|
| SigClust | Is the data more than one Gaussian cloud? |
| Selective inference | Do two found clusters differ, given that they were found? |
| Prediction strength | Do new rows reproduce the clusters? |
| Bootstrap stability | Do the clusters survive resampling? |
One cloud, a tiny p-value
PredictPredict 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?
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.
3 pair(s) of 3 clusters (average linkage) tested; clusters 1 and 2: selective p = 0.612 (naive p = 9.48e-12).
- Selective p (1 vs 2)
- .612
- Naive p (1 vs 2)
- < .001
Plots
The naive p ignores that the clusters were found in the same data; the selective p accounts for it.
View data
| Clusters | Test | p-value |
|---|---|---|
| 1 vs 2 | Naive | 9.480e-12 |
| 1 vs 2 | Selective | 0.6123 |
| 1 vs 3 | Naive | 0.0062 |
| 1 vs 3 | Selective | 0.2694 |
| 2 vs 3 | Naive | 1.301e-7 |
| 2 vs 3 | Selective | 0.0817 |
Difference in means for each pair of clusters
| Clusters | Rows (first) | Rows (second) | Distance between means | Naive p | Selective p | Draws kept | Effective draws |
|---|---|---|---|---|---|---|---|
| 1 vs 2 | 71 | 8 | 3.647 | 9.480e-12 | 0.6123 | 156 | 33.510 |
| 1 vs 3 | 71 | 1 | 5.100 | 0.0062 | 0.2694 | 200 | 78.212 |
| 2 vs 3 | 8 | 1 | 8.462 | 1.301e-7 | 0.0817 | 214 | 45.340 |
The exact R script · R R version 4.5.1 (2025-06-13)
# Are these clusters really different? (selective inference)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.cluster_inference 1.0.0 · spec 12586d9a59e1c47d
# Dataset: clu4_sigclust (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
FEATURES <- c("g1", "g2", "g3", "g4", "g5")
SEED <- 42
LINKAGE <- "average"
K <- 3
DRAWS <- 300
SCALE <- "none"
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/clu4_sigclust.parquet", col_select = FEATURES))
n_input <- nrow(df)
cs_check_finite_columns(df, FEATURES) # ±Inf stops with CS_E_NOT_FINITE in both engines
rows <- cs_ml_complete_rows(df, FEATURES)
warnings <- list()
if (length(rows) < n_input) warnings <- c(warnings, sprintf("%d of %d rows were left out because a value was missing.", n_input - length(rows), n_input))
cs_check_rows(length(rows), K + 2, "Selective inference after clustering")
X <- cs_ml_numeric_matrix(df, FEATURES, rows)
if (all(apply(X, 2, function(v) max(v) - min(v)) == 0)) cs_error("CS_E_CONSTANT", column = paste(FEATURES, collapse = ", "))
if (SCALE == "standardize") {
flat <- apply(X, 2, function(v) max(v) - min(v)) == 0
s <- apply(X, 2, stats::sd)
s[flat] <- 1
X <- sweep(sweep(X, 2, colMeans(X)), 2, s, "/")
X[, flat] <- 0 # constant columns exactly 0 in both engines
}
# %% Clusters and the noise SD
labels <- cs_ml_canonical(cs_ml_hclust_cut(X, LINKAGE, K))
k_found <- max(labels)
if (k_found < 2) cs_error("CS_E_UNDEFINED", what = "Selective inference", reason = "the tree has fewer than two clusters at this cut")
sigma <- cs_ml_pooled_sigma(X)
# %% Selective p-value for every pair (shared stream, pair by pair)
rng <- cs_rng(SEED)
pairs <- list()
values <- list(n = length(rows), q = ncol(X), k = k_found, sigma = sigma)
for (a in seq_len(k_found)) {
for (b in seq_len(k_found)) {
if (b <= a) next
res <- cs_ml_selective_pair(X, labels == a, labels == b, LINKAGE, K, sigma, DRAWS, rng)
pairs[[length(pairs) + 1L]] <- list(a = a, b = b, r = res)
values[[sprintf("p_selective[%d-%d]", a, b)]] <- res$p_selective
values[[sprintf("p_naive[%d-%d]", a, b)]] <- res$p_naive
}
}
first <- pairs[[1]]$r
psel <- vapply(pairs, function(x) x$r$p_selective, numeric(1))
values$n_pairs <- length(pairs)
values$p_selective <- first$p_selective
values$p_naive <- first$p_naive
values$distance <- first$stat
values$kept <- first$kept
values$ess <- first$ess
values["min_p_selective"] <- list(if (any(!is.nan(psel))) min(psel[!is.nan(psel)]) else NULL)
pair_name <- function(x, sep = "–") sprintf("%d%s%d", x$a, sep, x$b)
low_ess <- vapply(Filter(function(x) x$r$kept > 0 && x$r$ess < 20, pairs), pair_name, character(1))
if (length(low_ess)) warnings <- c(warnings, paste0("Few effective draws for pair(s) ", paste(low_ess, collapse = ", "), "; raise the number of draws for a steadier p-value."))
none_kept <- vapply(Filter(function(x) x$r$kept == 0, pairs), pair_name, character(1))
if (length(none_kept)) warnings <- c(warnings, paste0("No draw reproduced pair(s) ", paste(none_kept, collapse = ", "), "; their selective p-value is undefined at this number of draws."))
tables <- list(list(
key = "pairs", title = "Difference in means for each pair of clusters",
columns = list(
list(key = "pair", label = "Clusters", type = "string"),
list(key = "n_a", label = "Rows (first)", type = "integer"),
list(key = "n_b", label = "Rows (second)", type = "integer"),
list(key = "distance", label = "Distance between means", type = "number"),
list(key = "p_naive", label = "Naive p", type = "p"),
list(key = "p_selective", label = "Selective p", type = "p"),
list(key = "kept", label = "Draws kept", type = "integer"),
list(key = "ess", label = "Effective draws", type = "number")
),
rows = lapply(pairs, function(x) list(pair = sprintf("%d vs %d", x$a, x$b), n_a = x$r$n1, n_b = x$r$n2, distance = x$r$stat,
p_naive = x$r$p_naive, p_selective = x$r$p_selective, kept = x$r$kept, ess = x$r$ess))
))
# %% Chart: naive vs selective p-values
cats <- character(0)
vals <- numeric(0)
grp <- character(0)
for (x in pairs) {
for (g in list(c("Naive", "p_naive"), c("Selective", "p_selective"))) {
v <- x$r[[g[2]]]
if (!is.nan(v)) {
cats <- c(cats, sprintf("%d vs %d", x$a, x$b))
vals <- c(vals, v)
grp <- c(grp, g[1])
}
}
}
charts <- list(cs_chart("pvalues", "cleveland-dot", "Naive and selective p-values by pair", list(
category = cs_col("Clusters", cats, "categorical", levels = vapply(pairs, function(x) sprintf("%d vs %d", x$a, x$b), character(1))),
value = cs_col("p-value", vals, "numeric"),
group = cs_col("Test", grp, "categorical", levels = c("Naive", "Selective"))
), note = "The naive p ignores that the clusters were found in the same data; the selective p accounts for it."))
# %% Result
ps <- first$p_selective
cs_publish(list(
title = "Are these clusters really different? (selective inference)",
engine = cs_engine_info("codesplashr", "nanoparquet"),
n = length(rows),
summary = sprintf("%d pair(s) of %d clusters (%s linkage) tested; clusters 1 and 2: selective p = %s (naive p = %s).",
length(pairs), k_found, LINKAGE, if (is.nan(ps)) "undefined" else format(signif(ps, 3)), format(signif(first$p_naive, 3))),
statistics = list(list(key = "p_selective", label = "Selective p (1 vs 2)", value = ps, format = "p"),
list(key = "p_naive", label = "Naive p (1 vs 2)", value = first$p_naive, format = "p")),
tables = tables,
values = values,
charts = charts,
warnings = warnings
))
3 pair(s) of 3 clusters (average linkage) tested; clusters 1 and 2: selective p = 0.612 (naive p = 9.48e-12).
- Selective p (1 vs 2)
- .612
- Naive p (1 vs 2)
- < .001
To keep this page light, the plots are shown once, under the R tab.
Difference in means for each pair of clusters
| Clusters | Rows (first) | Rows (second) | Distance between means | Naive p | Selective p | Draws kept | Effective draws |
|---|---|---|---|---|---|---|---|
| 1 vs 2 | 71 | 8 | 3.647 | 9.480e-12 | 0.6123 | 156 | 33.510 |
| 1 vs 3 | 71 | 1 | 5.100 | 0.0062 | 0.2694 | 200 | 78.212 |
| 2 vs 3 | 8 | 1 | 8.462 | 1.301e-7 | 0.0817 | 214 | 45.340 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Are these clusters really different? (selective inference)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.cluster_inference 1.0.0 · spec 12586d9a59e1c47d
# Dataset: clu4_sigclust (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.ml import cluster as csc
from codesplash.ml import cluster_checks as ck
from codesplash.ml import embed as csembed
from codesplash.stats.rng import Rng
# %% Data
FEATURES = ["g1", "g2", "g3", "g4", "g5"]
SEED = 42
LINKAGE = "average"
K = 3
DRAWS = 300
SCALE = "none"
df = pd.read_parquet("tests/parity/fixtures/clu4_sigclust.parquet", columns=FEATURES)
n_input = len(df)
cs.check_finite_columns(df, FEATURES) # ±Inf stops with CS_E_NOT_FINITE in both engines
rows = csembed.complete_rows(df, FEATURES)
warnings = []
if len(rows) < n_input:
warnings.append(f"{n_input - len(rows)} of {n_input} rows were left out because a value was missing.")
cs.check_rows(len(rows), K + 2, "Selective inference after clustering")
X = csembed.numeric_matrix(df, FEATURES, rows)
if np.all(np.ptp(X, axis=0) == 0):
cs.cs_error("CS_E_CONSTANT", column=", ".join(FEATURES))
if SCALE == "standardize":
flat = np.ptp(X, axis=0) == 0
X = csembed.standardize(X, ddof=1)
X[:, flat] = 0.0 # constant columns exactly 0 in both engines
# %% Clusters and the noise SD
labels = csc.canonical(ck.hclust_cut(X, LINKAGE, K))
k_found = int(labels.max())
if k_found < 2:
cs.cs_error("CS_E_UNDEFINED", what="Selective inference", reason="the tree has fewer than two clusters at this cut")
sigma = ck.pooled_sigma(X)
# %% Selective p-value for every pair (shared stream, pair by pair)
rng = Rng(SEED)
pairs = []
values = {"n": len(rows), "q": X.shape[1], "k": k_found, "sigma": sigma}
for a in range(1, k_found + 1):
for b in range(a + 1, k_found + 1):
res = ck.selective_pair(X, labels == a, labels == b, LINKAGE, K, sigma, DRAWS, rng)
pairs.append((a, b, res))
values[f"p_selective[{a}-{b}]"] = res["p_selective"]
values[f"p_naive[{a}-{b}]"] = res["p_naive"]
first = pairs[0][2]
values.update({
"n_pairs": len(pairs), "p_selective": first["p_selective"], "p_naive": first["p_naive"], "distance": first["stat"],
"kept": first["kept"], "ess": first["ess"],
"min_p_selective": min((r["p_selective"] for _, _, r in pairs if r["p_selective"] == r["p_selective"]), default=None),
})
low_ess = [f"{a}–{b}" for a, b, r in pairs if r["kept"] > 0 and r["ess"] < 20]
if low_ess:
warnings.append("Few effective draws for pair(s) " + ", ".join(low_ess) + "; raise the number of draws for a steadier p-value.")
none_kept = [f"{a}–{b}" for a, b, r in pairs if r["kept"] == 0]
if none_kept:
warnings.append("No draw reproduced pair(s) " + ", ".join(none_kept) + "; their selective p-value is undefined at this number of draws.")
tables = [{
"key": "pairs",
"title": "Difference in means for each pair of clusters",
"columns": [
{"key": "pair", "label": "Clusters", "type": "string"},
{"key": "n_a", "label": "Rows (first)", "type": "integer"},
{"key": "n_b", "label": "Rows (second)", "type": "integer"},
{"key": "distance", "label": "Distance between means", "type": "number"},
{"key": "p_naive", "label": "Naive p", "type": "p"},
{"key": "p_selective", "label": "Selective p", "type": "p"},
{"key": "kept", "label": "Draws kept", "type": "integer"},
{"key": "ess", "label": "Effective draws", "type": "number"},
],
"rows": [
{"pair": f"{a} vs {b}", "n_a": r["n1"], "n_b": r["n2"], "distance": r["stat"], "p_naive": r["p_naive"],
"p_selective": r["p_selective"], "kept": r["kept"], "ess": r["ess"]}
for a, b, r in pairs
],
}]
# %% Chart: naive vs selective p-values
cats, vals, grp = [], [], []
for a, b, r in pairs:
for label, key in (("Naive", "p_naive"), ("Selective", "p_selective")):
if r[key] == r[key]:
cats.append(f"{a} vs {b}")
vals.append(r[key])
grp.append(label)
charts = [cs.chart(
"pvalues", "cleveland-dot", "Naive and selective p-values by pair",
{
"category": cs.col("Clusters", cats, "categorical", levels=[f"{a} vs {b}" for a, b, _ in pairs]),
"value": cs.col("p-value", vals, "numeric"),
"group": cs.col("Test", grp, "categorical", levels=["Naive", "Selective"]),
},
note="The naive p ignores that the clusters were found in the same data; the selective p accounts for it.",
)]
# %% Result
ps = first["p_selective"]
cs.publish({
"title": "Are these clusters really different? (selective inference)",
"engine": cs.engine_info("scipy", "numpy", "pandas"),
"n": len(rows),
"summary": (
f"{len(pairs)} pair(s) of {k_found} clusters ({LINKAGE} linkage) tested; clusters 1 and 2: selective p = "
+ (f"{ps:.3g}" if ps == ps else "undefined") + f" (naive p = {first['p_naive']:.3g})."
),
"statistics": [
{"key": "p_selective", "label": "Selective p (1 vs 2)", "value": ps, "format": "p"},
{"key": "p_naive", "label": "Naive p (1 vs 2)", "value": first["p_naive"], "format": "p"},
],
"tables": tables,
"values": values,
"charts": charts,
"warnings": warnings,
})
Selective inference
ReadA 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 , here "hierarchical clustering produced these two clusters": . 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.
0 gives one Gaussian cloud; larger values move half the rows along variable 1.
Linkage
How hierarchical clustering measures the distance between clusters.
Where the tree is cut; clusters 1 and 2 (the two largest) are tested.
Importance-sampling draws; each re-runs the clustering on moved data.
Your data
Simulated with a known number of cloudsThe 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
- 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).
- Your statistic, from the data above.
- The p-value: the area at least as extreme as yours (p = .764).
- The hatched rejection region at α = .050: statistics landing here reject H₀.
The formula
With your numbers
- the two largest clusters the algorithm chose from these same data
- the usual χ test, which ignores that the groups were chosen to be far apart
- 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̄₁ − x̄₂‖ = 3.29, p = .764. The p-value is above α = .050, so the data are compatible with H₀.
SigClust: more than one Gaussian?
ReadSigClustSigClustTests 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 : 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 is as small.
The best 2-means split has cluster index 0.579 (null mean 0.684); p = 0: the split is stronger than one Gaussian cloud would give.
- Cluster index
- 0.5792
- p (simulated)
- < .001
- p (Gaussian fit)
- < .001
Plots
Normal curve fitted to 100 simulated cluster indices; a split far to the left of it is stronger than one cloud would give.
View data
| 5% critical value | Null density (normal fit) | Observed cluster index | Cluster index |
|---|---|---|---|
| 0.6299 | 5.642e-8 | 0.5792 | 0.4810 |
| 0.6299 | 8.078e-8 | 0.5792 | 0.4829 |
| 0.6299 | 1.153e-7 | 0.5792 | 0.4848 |
| 0.6299 | 1.639e-7 | 0.5792 | 0.4867 |
| 0.6299 | 2.323e-7 | 0.5792 | 0.4886 |
| 0.6299 | 3.281e-7 | 0.5792 | 0.4905 |
| 0.6299 | 4.618e-7 | 0.5792 | 0.4924 |
| 0.6299 | 6.479e-7 | 0.5792 | 0.4943 |
| 0.6299 | 9.059e-7 | 0.5792 | 0.4962 |
| 0.6299 | 1.262e-6 | 0.5792 | 0.4981 |
| 0.6299 | 1.753e-6 | 0.5792 | 0.5000 |
| 0.6299 | 2.426e-6 | 0.5792 | 0.5020 |
| 0.6299 | 3.347e-6 | 0.5792 | 0.5039 |
| 0.6299 | 4.601e-6 | 0.5792 | 0.5058 |
| 0.6299 | 6.303e-6 | 0.5792 | 0.5077 |
| 0.6299 | 8.606e-6 | 0.5792 | 0.5096 |
| 0.6299 | 1.171e-5 | 0.5792 | 0.5115 |
| 0.6299 | 1.588e-5 | 0.5792 | 0.5134 |
| 0.6299 | 2.147e-5 | 0.5792 | 0.5153 |
| 0.6299 | 2.892e-5 | 0.5792 | 0.5172 |
| 0.6299 | 3.882e-5 | 0.5792 | 0.5191 |
| 0.6299 | 5.194e-5 | 0.5792 | 0.5210 |
| 0.6299 | 6.925e-5 | 0.5792 | 0.5229 |
| 0.6299 | 9.203e-5 | 0.5792 | 0.5248 |
| 0.6299 | 0.0001 | 0.5792 | 0.5267 |
| 0.6299 | 0.0002 | 0.5792 | 0.5286 |
| 0.6299 | 0.0002 | 0.5792 | 0.5305 |
| 0.6299 | 0.0003 | 0.5792 | 0.5324 |
| 0.6299 | 0.0004 | 0.5792 | 0.5343 |
| 0.6299 | 0.0005 | 0.5792 | 0.5362 |
| 0.6299 | 0.0006 | 0.5792 | 0.5381 |
| 0.6299 | 0.0008 | 0.5792 | 0.5400 |
| 0.6299 | 0.0010 | 0.5792 | 0.5419 |
| 0.6299 | 0.0013 | 0.5792 | 0.5438 |
| 0.6299 | 0.0017 | 0.5792 | 0.5457 |
| 0.6299 | 0.0021 | 0.5792 | 0.5476 |
| 0.6299 | 0.0027 | 0.5792 | 0.5496 |
| 0.6299 | 0.0035 | 0.5792 | 0.5515 |
| 0.6299 | 0.0044 | 0.5792 | 0.5534 |
| 0.6299 | 0.0055 | 0.5792 | 0.5553 |
| 0.6299 | 0.0069 | 0.5792 | 0.5572 |
| 0.6299 | 0.0086 | 0.5792 | 0.5591 |
| 0.6299 | 0.0107 | 0.5792 | 0.5610 |
| 0.6299 | 0.0133 | 0.5792 | 0.5629 |
| 0.6299 | 0.0165 | 0.5792 | 0.5648 |
| 0.6299 | 0.0204 | 0.5792 | 0.5667 |
| 0.6299 | 0.0250 | 0.5792 | 0.5686 |
| 0.6299 | 0.0307 | 0.5792 | 0.5705 |
| 0.6299 | 0.0374 | 0.5792 | 0.5724 |
| 0.6299 | 0.0455 | 0.5792 | 0.5743 |
| 0.6299 | 0.0552 | 0.5792 | 0.5762 |
| 0.6299 | 0.0668 | 0.5792 | 0.5781 |
| 0.6299 | 0.0804 | 0.5792 | 0.5800 |
| 0.6299 | 0.0965 | 0.5792 | 0.5819 |
| 0.6299 | 0.1155 | 0.5792 | 0.5838 |
| 0.6299 | 0.1377 | 0.5792 | 0.5857 |
| 0.6299 | 0.1637 | 0.5792 | 0.5876 |
| 0.6299 | 0.1939 | 0.5792 | 0.5895 |
| 0.6299 | 0.2288 | 0.5792 | 0.5914 |
| 0.6299 | 0.2692 | 0.5792 | 0.5933 |
First 60 of 200 rows.
Covariance eigenvalues: data and null
| Component | Data | Null (simulated) |
|---|---|---|
| 1 | 4.234 | 4.234 |
| 2 | 1.203 | 1.203 |
| 3 | 0.8151 | 1.147 |
| 4 | 0.7625 | 1.147 |
| 5 | 0.6405 | 1.147 |
The exact R script · R R version 4.5.1 (2025-06-13)
# Is the split significant? (SigClust)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.sigclust 1.0.0 · spec 8d6ef312e2dcb35b
# Dataset: clu4_sigclust (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
FEATURES <- c("c1", "c2", "c3", "c4", "c5")
SPLIT <- NULL # optional two-group column to test
SEED <- 42
SIMS <- 100
STARTS <- 3
METHOD <- "soft"
SCALE <- "none"
cols <- unique(c(FEATURES, if (!is.null(SPLIT)) SPLIT))
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/clu4_sigclust.parquet", col_select = cols))
n_input <- nrow(df)
cs_check_finite_columns(df, cols) # ±Inf stops with CS_E_NOT_FINITE in both engines
rows <- cs_ml_complete_rows(df, cols)
warnings <- list()
if (length(rows) < n_input) warnings <- c(warnings, sprintf("%d of %d rows were left out because a value was missing.", n_input - length(rows), n_input))
cs_check_rows(length(rows), 5, "SigClust")
X <- cs_ml_numeric_matrix(df, FEATURES, rows)
if (all(apply(X, 2, function(v) max(v) - min(v)) == 0)) cs_error("CS_E_CONSTANT", column = paste(FEATURES, collapse = ", "))
if (SCALE == "standardize") {
flat <- apply(X, 2, function(v) max(v) - min(v)) == 0
s <- apply(X, 2, stats::sd)
s[flat] <- 1
X <- sweep(sweep(X, 2, colMeans(X)), 2, s, "/")
X[, flat] <- 0 # constant columns exactly 0 in both engines
}
split <- NULL
if (!is.null(SPLIT)) {
lab <- cs_ml_label_text(df[[SPLIT]][rows + 1L])
cs_check_groups(lab, SPLIT, exactly = 2)
levels <- sort(unique(lab), method = "radix")
split <- match(lab, levels) - 1L
}
# %% SigClust
r <- cs_ml_sigclust(X, SIMS, STARTS, METHOD, cs_rng(SEED), split)
lab <- r$labels
sizes <- c(sort(as.integer(table(lab)), decreasing = TRUE), 0L, 0L)
values <- list(n = r$n, d = r$d, ci = r$ci, p_empirical = r$p_empirical, p_gaussian = r$p_gaussian,
sim_mean = r$sim_mean, sim_sd = r$sim_sd, sigma2_background = r$sigma2_background, tau = r$tau,
n_floored = r$n_floored, size_1 = sizes[1], size_2 = sizes[2], sims = SIMS)
if (is.nan(values$tau)) warnings <- c(warnings, "Every eigenvalue is below the background noise level, so the null uses the noise level for all of them.")
eig <- r$eigen
eig0 <- r$eigen_null
tables <- list(list(key = "eigenvalues", title = "Covariance eigenvalues: data and null",
columns = list(list(key = "component", label = "Component", type = "integer"),
list(key = "sample", label = "Data", type = "number"),
list(key = "null", label = "Null (simulated)", type = "number")),
rows = lapply(seq_len(min(length(eig), 50)), function(j) list(component = j, sample = eig[j], null = eig0[j]))))
# %% Null distribution chart (normal fitted to the simulated cluster indices)
sims <- r$sims
m <- values$sim_mean
s <- values$sim_sd
charts <- list()
if (is.finite(s) && s > 0) {
lo <- min(min(sims), values$ci) - 3 * s
hi <- max(max(sims), values$ci) + 3 * s
grid <- seq(lo, hi, length.out = 200)
charts[[1]] <- cs_chart("null", "null-distribution", "Cluster index under one Gaussian cloud", list(
x = cs_col("Cluster index", grid, "numeric"),
density = cs_col("Null density (normal fit)", stats::dnorm(grid, m, s), "numeric"),
observed = cs_col("Observed cluster index", rep(values$ci, length(grid)), "numeric"),
critical_low = cs_col("5% critical value", rep(stats::qnorm(0.05, m, s), length(grid)), "numeric")
), note = sprintf("Normal curve fitted to %d simulated cluster indices; a split far to the left of it is stronger than one cloud would give.", SIMS))
}
# %% Result
p <- values$p_empirical
verdict <- if (p < 0.05) "stronger than one Gaussian cloud would give" else "explained by one Gaussian cloud"
cs_publish(list(
title = "Is the split significant? (SigClust)",
engine = cs_engine_info("codesplashr", "nanoparquet"),
n = values$n,
summary = sprintf("%s has cluster index %.3f (null mean %.3f); p = %s: the split is %s.",
if (!is.null(SPLIT)) "The given split" else "The best 2-means split", values$ci, m, format(signif(p, 3)), verdict),
statistics = list(list(key = "ci", label = "Cluster index", value = values$ci),
list(key = "p_empirical", label = "p (simulated)", value = p, format = "p"),
list(key = "p_gaussian", label = "p (Gaussian fit)", value = values$p_gaussian, format = "p")),
tables = tables,
values = values,
charts = charts,
warnings = warnings
))
The best 2-means split has cluster index 0.579 (null mean 0.684); p = 0: the split is stronger than one Gaussian cloud would give.
- Cluster index
- 0.5792
- p (simulated)
- < .001
- p (Gaussian fit)
- < .001
To keep this page light, the plots are shown once, under the R tab.
Covariance eigenvalues: data and null
| Component | Data | Null (simulated) |
|---|---|---|
| 1 | 4.234 | 4.234 |
| 2 | 1.203 | 1.203 |
| 3 | 0.8151 | 1.147 |
| 4 | 0.7625 | 1.147 |
| 5 | 0.6405 | 1.147 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Is the split significant? (SigClust)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.sigclust 1.0.0 · spec 8d6ef312e2dcb35b
# Dataset: clu4_sigclust (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
from scipy.stats import norm
import codesplash as cs
from codesplash.errors import check_groups
from codesplash.ml import cluster_checks as ck
from codesplash.ml import cluster_compare as cc
from codesplash.ml import embed as csembed
from codesplash.stats.rng import Rng
# %% Data
FEATURES = ["c1", "c2", "c3", "c4", "c5"]
SPLIT = None # optional two-group column to test
SEED = 42
SIMS = 100
STARTS = 3
METHOD = "soft"
SCALE = "none"
cols = list(dict.fromkeys(FEATURES + ([SPLIT] if SPLIT else [])))
df = pd.read_parquet("tests/parity/fixtures/clu4_sigclust.parquet", columns=cols)
n_input = len(df)
cs.check_finite_columns(df, cols) # ±Inf stops with CS_E_NOT_FINITE in both engines
rows = csembed.complete_rows(df, cols)
warnings = []
if len(rows) < n_input:
warnings.append(f"{n_input - len(rows)} of {n_input} rows were left out because a value was missing.")
cs.check_rows(len(rows), 5, "SigClust")
X = csembed.numeric_matrix(df, FEATURES, rows)
if np.all(np.ptp(X, axis=0) == 0):
cs.cs_error("CS_E_CONSTANT", column=", ".join(FEATURES))
if SCALE == "standardize":
flat = np.ptp(X, axis=0) == 0
X = csembed.standardize(X, ddof=1)
X[:, flat] = 0.0 # constant columns exactly 0 in both engines
split = None
if SPLIT:
lab = cc.label_text(df[SPLIT].iloc[rows].tolist())
check_groups(pd.Series(lab, dtype=object), SPLIT, exactly=2)
levels = sorted(set(lab.tolist()))
split = np.array([levels.index(v) for v in lab], dtype=np.int64)
# %% SigClust
r = ck.sigclust(X, SIMS, STARTS, METHOD, Rng(SEED), split)
lab = np.asarray(r["labels"])
sizes = sorted([int(np.sum(lab == c)) for c in np.unique(lab)], reverse=True) + [0, 0]
values = {
"n": r["n"], "d": r["d"], "ci": r["ci"], "p_empirical": r["p_empirical"], "p_gaussian": r["p_gaussian"],
"sim_mean": r["sim_mean"], "sim_sd": r["sim_sd"], "sigma2_background": r["sigma2_background"], "tau": r["tau"],
"n_floored": r["n_floored"], "size_1": sizes[0], "size_2": sizes[1], "sims": SIMS,
}
if values["tau"] != values["tau"]:
warnings.append("Every eigenvalue is below the background noise level, so the null uses the noise level for all of them.")
eig = r["eigen"]
eig0 = r["eigen_null"]
tables = [{
"key": "eigenvalues",
"title": "Covariance eigenvalues: data and null",
"columns": [{"key": "component", "label": "Component", "type": "integer"},
{"key": "sample", "label": "Data", "type": "number"},
{"key": "null", "label": "Null (simulated)", "type": "number"}],
"rows": [{"component": j + 1, "sample": float(eig[j]), "null": float(eig0[j])} for j in range(min(len(eig), 50))],
}]
# %% Null distribution chart (normal fitted to the simulated cluster indices)
sims = r["sims"]
m, s = values["sim_mean"], values["sim_sd"]
charts = []
if s == s and s > 0:
lo = min(float(np.min(sims)), values["ci"]) - 3 * s
hi = max(float(np.max(sims)), values["ci"]) + 3 * s
grid = np.linspace(lo, hi, 200)
charts.append(cs.chart(
"null", "null-distribution", "Cluster index under one Gaussian cloud",
{
"x": cs.col("Cluster index", list(grid), "numeric"),
"density": cs.col("Null density (normal fit)", list(norm.pdf(grid, m, s)), "numeric"),
"observed": cs.col("Observed cluster index", [values["ci"]] * len(grid), "numeric"),
"critical_low": cs.col("5% critical value", [float(norm.ppf(0.05, m, s))] * len(grid), "numeric"),
},
note=f"Normal curve fitted to {SIMS} simulated cluster indices; a split far to the left of it is stronger than one cloud would give.",
))
# %% Result
p = values["p_empirical"]
verdict = "stronger than one Gaussian cloud would give" if p < 0.05 else "explained by one Gaussian cloud"
cs.publish({
"title": "Is the split significant? (SigClust)",
"engine": cs.engine_info("numpy", "scipy", "pandas"),
"n": values["n"],
"summary": f"{'The given split' if SPLIT else 'The best 2-means split'} has cluster index {values['ci']:.3f} (null mean {m:.3f}); p = {p:.3g}: the split is {verdict}.",
"statistics": [
{"key": "ci", "label": "Cluster index", "value": values["ci"]},
{"key": "p_empirical", "label": "p (simulated)", "value": p, "format": "p"},
{"key": "p_gaussian", "label": "p (Gaussian fit)", "value": values["p_gaussian"], "format": "p"},
],
"tables": tables,
"values": values,
"charts": charts,
"warnings": warnings,
})
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.
0 gives one Gaussian cloud; larger values move half the rows along variable 1.
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.
k-means++ starts per split; the best is kept for the data and for every simulation.
Your data
Simulated with a known number of cloudsThe first two of 4 variables, marked by the best 2-means split. Crosses mark the means.
If H₀ were true
- 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).
- Your statistic, from the data above.
- The p-value: the area at least as extreme as yours (p = .888).
- The hatched rejection region at α = .050: statistics landing here reject H₀.
The formula
With your numbers
- cluster index: within-cluster over total sum of squares of the best 2-means split; small means a strong split
- 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 H₀.
Prediction strength: do new rows agree?
ReadPrediction 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 , count the pairs of its rows that the training clusters also put together:
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
View data
| Center | Cluster | PC1 (73%) | PC2 (23%) |
|---|---|---|---|
| false | 2 | −2.265 | 0.4800 |
| false | 2 | −2.081 | −0.6741 |
| false | 2 | −2.364 | −0.3419 |
| false | 2 | −2.299 | −0.5974 |
| false | 2 | −2.390 | 0.6468 |
| false | 2 | −2.076 | 1.489 |
| false | 2 | −2.444 | 0.0476 |
| false | 2 | −2.233 | 0.2231 |
| false | 2 | −2.335 | −1.115 |
| false | 2 | −2.184 | −0.4690 |
| false | 2 | −2.166 | 1.044 |
| false | 2 | −2.326 | 0.1331 |
| false | 2 | −2.218 | −0.7287 |
| false | 2 | −2.633 | −0.9615 |
| false | 2 | −2.199 | 1.860 |
| false | 2 | −2.262 | 2.686 |
| false | 2 | −2.208 | 1.484 |
| false | 2 | −2.190 | 0.4888 |
| false | 2 | −1.899 | 1.405 |
| false | 2 | −2.343 | 1.128 |
| false | 2 | −1.914 | 0.4089 |
| false | 2 | −2.207 | 0.9241 |
| false | 2 | −2.774 | 0.4583 |
| false | 2 | −1.819 | 0.0856 |
| false | 2 | −2.227 | 0.1373 |
| false | 2 | −1.952 | −0.6256 |
| false | 2 | −2.051 | 0.2422 |
| false | 2 | −2.169 | 0.5271 |
| false | 2 | −2.140 | 0.3132 |
| false | 2 | −2.265 | −0.3377 |
| false | 2 | −2.140 | −0.5045 |
| false | 2 | −1.832 | 0.4237 |
| false | 2 | −2.615 | 1.794 |
| false | 2 | −2.446 | 2.151 |
| false | 2 | −2.110 | −0.4602 |
| false | 2 | −2.208 | −0.2061 |
| false | 2 | −2.045 | 0.6616 |
| false | 2 | −2.527 | 0.5923 |
| false | 2 | −2.430 | −0.9042 |
| false | 2 | −2.170 | 0.2689 |
| false | 2 | −2.286 | 0.4417 |
| false | 2 | −1.858 | −2.337 |
| false | 2 | −2.554 | −0.4791 |
| false | 2 | −1.964 | 0.4723 |
| false | 2 | −2.137 | 1.142 |
| false | 2 | −2.070 | −0.7111 |
| false | 2 | −2.385 | 1.120 |
| false | 2 | −2.394 | −0.3862 |
| false | 2 | −2.229 | 0.9980 |
| false | 2 | −2.204 | 0.0092 |
| false | 1 | 1.102 | 0.8630 |
| false | 1 | 0.7313 | 0.5946 |
| false | 1 | 1.241 | 0.6163 |
| false | 1 | 0.4075 | −1.754 |
| false | 1 | 1.075 | −0.2084 |
| false | 1 | 0.3887 | −0.5933 |
| false | 1 | 0.7465 | 0.7730 |
| false | 1 | −0.4873 | −1.852 |
| false | 1 | 0.9279 | 0.0322 |
| false | 1 | 0.0114 | −1.034 |
First 60 of 152 rows.
Recommended k = 2 by the prediction strength (largest k at or above 0.8).
View data
| Recommended | Criterion | Clusters (k) | Score |
|---|---|---|---|
| false | Within-cluster SS | 2 | 222.36 |
| true | Within-cluster SS | 3 | 140.90 |
| false | Within-cluster SS | 4 | 114.35 |
| false | Within-cluster SS | 5 | 105.31 |
| true | Mean silhouette | 2 | 0.5818 |
| false | Mean silhouette | 3 | 0.4565 |
| false | Mean silhouette | 4 | 0.3819 |
| false | Mean silhouette | 5 | 0.3907 |
| true | Calinski–Harabasz | 2 | 251.35 |
| false | Calinski–Harabasz | 3 | 239.48 |
| false | Calinski–Harabasz | 4 | 206.68 |
| false | Calinski–Harabasz | 5 | 170.28 |
| true | Davies–Bouldin | 2 | 0.5933 |
| false | Davies–Bouldin | 3 | 0.8275 |
| false | Davies–Bouldin | 4 | 0.8796 |
| false | Davies–Bouldin | 5 | 1.003 |
| true | Prediction strength | 2 | 0.9953 |
| false | Prediction strength | 3 | 0.6537 |
| false | Prediction strength | 4 | 0.5761 |
| false | Prediction strength | 5 | 0.4497 |
View data
| Cluster | Silhouette width |
|---|---|
| 1 | 0.6662 |
| 1 | 0.6658 |
| 1 | 0.6646 |
| 1 | 0.6605 |
| 1 | 0.6604 |
| 1 | 0.6595 |
| 1 | 0.6580 |
| 1 | 0.6576 |
| 1 | 0.6502 |
| 1 | 0.6491 |
| 1 | 0.6487 |
| 1 | 0.6438 |
| 1 | 0.6386 |
| 1 | 0.6385 |
| 1 | 0.6347 |
| 1 | 0.6337 |
| 1 | 0.6326 |
| 1 | 0.6292 |
| 1 | 0.6289 |
| 1 | 0.6248 |
| 1 | 0.6245 |
| 1 | 0.6202 |
| 1 | 0.6189 |
| 1 | 0.6189 |
| 1 | 0.6176 |
| 1 | 0.6131 |
| 1 | 0.6118 |
| 1 | 0.6114 |
| 1 | 0.6107 |
| 1 | 0.6094 |
| 1 | 0.6084 |
| 1 | 0.6047 |
| 1 | 0.6017 |
| 1 | 0.6016 |
| 1 | 0.6013 |
| 1 | 0.6013 |
| 1 | 0.5981 |
| 1 | 0.5980 |
| 1 | 0.5948 |
| 1 | 0.5897 |
| 1 | 0.5879 |
| 1 | 0.5878 |
| 1 | 0.5870 |
| 1 | 0.5852 |
| 1 | 0.5796 |
| 1 | 0.5772 |
| 1 | 0.5766 |
| 1 | 0.5765 |
| 1 | 0.5729 |
| 1 | 0.5699 |
| 1 | 0.5681 |
| 1 | 0.5665 |
| 1 | 0.5637 |
| 1 | 0.5605 |
| 1 | 0.5578 |
| 1 | 0.5561 |
| 1 | 0.5556 |
| 1 | 0.5504 |
| 1 | 0.5448 |
| 1 | 0.5360 |
First 60 of 150 rows.
Clusters
| Cluster | Size | Share | sepal_length | sepal_width | petal_length | petal_width |
|---|---|---|---|---|---|---|
| 1 | 100 | 66.7% | 6.262 | 2.872 | 4.906 | 1.676 |
| 2 | 50 | 33.3% | 5.006 | 3.428 | 1.462 | 0.2460 |
Criteria by k
| k | Within-cluster SS | Mean silhouette | Calinski–Harabasz | Davies–Bouldin | Prediction strength | Prediction strength SD |
|---|---|---|---|---|---|---|
| 2 | 222.36 | 0.5818 | 251.35 | 0.5933 | 0.9953 | 0.0133 |
| 3 | 140.90 | 0.4565 | 239.48 | 0.8275 | 0.6537 | 0.1215 |
| 4 | 114.35 | 0.3819 | 206.68 | 0.8796 | 0.5761 | 0.0907 |
| 5 | 105.31 | 0.3907 | 170.28 | 1.003 | 0.4497 | 0.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"
))
))
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
| Cluster | Size | Share | sepal_length | sepal_width | petal_length | petal_width |
|---|---|---|---|---|---|---|
| 1 | 100 | 66.7% | 6.262 | 2.872 | 4.906 | 1.676 |
| 2 | 50 | 33.3% | 5.006 | 3.428 | 1.462 | 0.2460 |
Criteria by k
| k | Within-cluster SS | Mean silhouette | Calinski–Harabasz | Davies–Bouldin | Prediction strength | Prediction strength SD |
|---|---|---|---|---|---|---|
| 2 | 222.36 | 0.5818 | 251.35 | 0.5933 | 0.9953 | 0.0133 |
| 3 | 140.90 | 0.4565 | 239.48 | 0.8275 | 0.6537 | 0.1215 |
| 4 | 114.35 | 0.3819 | 206.68 | 0.8796 | 0.5761 | 0.0907 |
| 5 | 105.31 | 0.3907 | 170.28 | 1.003 | 0.4497 | 0.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 = 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.
Bootstrap stability with Jaccard
ReadBootstrap 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 is matched to its most similar resampled cluster by Jaccard similarity, , and the matches are averaged over resamples.
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
| Cluster | Size | Share | sepal_length | sepal_width | petal_length | petal_width |
|---|---|---|---|---|---|---|
| 1 | 55 | 36.7% | 6.696 | 3.060 | 5.418 | 1.938 |
| 2 | 49 | 32.7% | 5.016 | 3.451 | 1.465 | 0.2449 |
| 3 | 46 | 30.7% | 5.704 | 2.635 | 4.215 | 1.333 |
Cluster stability (mean bootstrap Jaccard)
| Cluster | Jaccard | Reading |
|---|---|---|
| 1 | 0.8559 | highly stable |
| 2 | 0.9849 | highly stable |
| 3 | 0.8535 | highly 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"
))
))
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
| Cluster | Size | Share | sepal_length | sepal_width | petal_length | petal_width |
|---|---|---|---|---|---|---|
| 1 | 55 | 36.7% | 6.696 | 3.060 | 5.418 | 1.938 |
| 2 | 49 | 32.7% | 5.016 | 3.451 | 1.465 | 0.2449 |
| 3 | 46 | 30.7% | 5.704 | 2.635 | 4.215 | 1.333 |
Cluster stability (mean bootstrap Jaccard)
| Cluster | Jaccard | Reading |
|---|---|---|
| 1 | 0.8559 | highly stable |
| 2 | 0.9849 | highly stable |
| 3 | 0.8535 | highly 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.
Resample and recluster
ExploreAExplorable · Do the clusters survive resampling?
Would the same clusters come back from a slightly different sample?
k-means always returns k clusters. Will its least stable cluster here come back in resamples (mean Jaccard above 0.75)?
Data
Commit your prediction above to see the result
Make your prediction to see the result.
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.
Where each idea stands in CodeSplash
Read| Entry | In 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) |
Check your understanding
CheckpointCheck 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 ?
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.
Do it on your own data
In the appAfter 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