Are your segments real, and what do they mean?
Test stability under resampling, compare with known groups honestly, profile segments without double dipping, and name them only as far as the evidence allows.
What runs in CodeSplash
- How stable are the clusters? (bootstrap) Verified in Python and R
You will be able to
- Read clusterwise Jaccard stability and PAC
- Explain double dipping and use a holdout for honest profiles
- Compare segments and save them as a dataset column
Read first
Would they come back?
ReadCollect the same kind of data again and rerun the clustering. Do the same groups appear? StabilityCluster stability (bootstrap Jaccard)How well each cluster comes back when the data are resampled, as the mean Jaccard overlap with its best match. approximates that with bootstrap resamples.
For each original cluster, the method finds the best-matching cluster in each resample and measures their overlap with Jaccard similarity: shared rows divided by rows in either.
| Mean Jaccard | Reading |
|---|---|
Above 0.85 | Highly stable |
0.6 to 0.75 | A pattern, but not a firm cluster |
0.5 or less | The cluster dissolves |
Make a guess
PredictPredict first
US arrests showed little clumping, and criteria disagreed on . Cluster the 50 states into four groups. How stable do you expect them to be?
Reveal
Mean Jaccard is 0.827 and the lowest is 0.799: only 1 of 4 clusters is highly stable. None dissolves, so they reflect a pattern, not firm groups.
Read the card
ReadOver 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.
Iris with = 3: mean Jaccard 0.898, lowest 0.854, and 3 of 3 highly stable.
Notice what this doesn't show. These clusters are stable and only partly match the species (adjusted Rand 0.645). Stable means reproducible, not correct. An algorithm can reliably find the same wrong split.
The PAC score summarizes how often pairs of rows flip between together and apart. Lower means crisper. Here it's 0.165.
The consensus picture
ExploreThe consensus matrix shows how often two rows land together across resamples. Crisp blocks mean firm groups. Gray between blocks shows rows that keep switching.
View data
| row (by cluster) | column (by cluster) | share of resamples together |
|---|---|---|
| 1 | 1 | 1 |
| 1 | 2 | 0.8250 |
| 1 | 3 | 0.8030 |
| 1 | 4 | 0.8720 |
| 1 | 5 | 0.7890 |
| 1 | 6 | 0.8740 |
| 1 | 7 | 0.7870 |
| 1 | 8 | 0.8120 |
| 1 | 9 | 0.8300 |
| 1 | 10 | 0.7880 |
| 1 | 11 | 0.9000 |
| 1 | 12 | 0.7950 |
| 1 | 13 | 0.7600 |
| 1 | 14 | 0.8330 |
| 1 | 15 | 0.0410 |
| 1 | 16 | 0.1570 |
| 1 | 17 | 0.0310 |
| 1 | 18 | 0.0120 |
| 1 | 19 | 0.0320 |
| 1 | 20 | 0.0620 |
| 1 | 21 | 0.0950 |
| 1 | 22 | 0.1230 |
| 1 | 23 | 0.0180 |
| 1 | 24 | 0.0970 |
| 1 | 25 | 0.0550 |
| 1 | 26 | 0.0030 |
| 1 | 27 | 0.0240 |
| 1 | 28 | 0.0700 |
| 1 | 29 | 0.0020 |
| 1 | 30 | 0.0280 |
| 1 | 31 | 0.0280 |
| 1 | 32 | 0.0530 |
| 2 | 1 | 0.8450 |
| 2 | 2 | 1 |
| 2 | 3 | 0.7880 |
| 2 | 4 | 0.8630 |
| 2 | 5 | 0.8830 |
| 2 | 6 | 0.9120 |
| 2 | 7 | 0.8800 |
| 2 | 8 | 0.7940 |
| 2 | 9 | 0.7040 |
| 2 | 10 | 0.8160 |
| 2 | 11 | 0.7350 |
| 2 | 12 | 0.9090 |
| 2 | 13 | 0.9190 |
| 2 | 14 | 0.8960 |
| 2 | 15 | 0.0190 |
| 2 | 16 | 0.0530 |
| 2 | 17 | 0.0790 |
| 2 | 18 | 0.0340 |
| 2 | 19 | 0.0040 |
| 2 | 20 | 0.0470 |
| 2 | 21 | 0.1480 |
| 2 | 22 | 0.0440 |
| 2 | 23 | 0.1960 |
| 2 | 24 | 0.0140 |
| 2 | 25 | 0.1010 |
| 2 | 26 | 0.0210 |
| 2 | 27 | 0.0230 |
| 2 | 28 | 0.2160 |
First 60 of 1024 rows.
Find a row band that looks gray against two different blocks. In your own data, that's where a person should look: rows with no firm home.
Double dipping
ReadYou clustered on income and age, then tested whether the clusters differ in income. The test is certain to come out "significant", because the clustering created the difference.
This is double dippingDouble dippingTesting differences between groups that were created from the same rows; the tests come out optimistic.: using the same rows to form groups and to test them. Every p-value in that comparison is too small, even on pure noise.
The honest fix is a holdout. Set Hold out rows for honest profiles in k-means: those rows stay out of the fit, get assigned to the nearest center afterwards, and the profile tests use only them.
An honest profile
ReadWith 30% of rows held out, 44 of 150 rows are kept out of the fit.
The Profiles tab shows how each segment differs from the rest. It labels those comparisons as honest when rows were held out, and warns that they're optimistic otherwise. Compare puts two segments side by side, with effect sizes and corrected q-values.
Effects measured on held-out rows are usually smaller. That's the honest size of the difference.
Name with care
ReflectYou can type a name for each segment in Profiles, and it travels with the saved column. Names are powerful, and they stick.
"Budget families" claims more than "younger, lower income, more visits". The first is a story about people, and the data only showed the second. Which of your own segment names say more than your columns do?
Check your understanding
CheckpointCheck yourself
You cluster customers on spending, then run a t-test showing that the clusters differ in spending at p < .001. What does this show?
Show the answer
Answer: b
Rows were grouped to differ in spending. To test a difference honestly, use held-out rows or a variable that wasn't used to cluster, and still report the method.
Check yourself
A cluster has a mean Jaccard of 0.92. Which statement holds?
Show the answer
Answer: b
Stability says the method reproduces it. Whether it means anything needs outside evidence: known groups, domain knowledge, or a useful decision.
Check yourself
Why is the adjusted Rand index preferred to plain percentage agreement with a known label?
Show the answer
Answer: a
It compares pairs of rows, so it doesn't matter what the clusters are numbered, or even how many there are. Zero is about chance level and 1 is perfect agreement.
Do it on your own data
In the appRun How stable are the clusters? from the Checks step, then rerun k-means with a holdout and read Profiles. When you're ready, Save to dataset adds the segment column as a new dataset version; earlier versions stay as they are.
import numpy as np
from sklearn.cluster import KMeans
from sklearn.datasets import load_iris
from sklearn.preprocessing import StandardScaler
X = StandardScaler().fit_transform(load_iris().data)
base = KMeans(n_clusters=3, n_init=5, random_state=1).fit_predict(X)
rng = np.random.default_rng(1)
scores = {c: [] for c in range(3)}
for _ in range(20):
idx = rng.integers(0, len(X), len(X))
labels = KMeans(n_clusters=3, n_init=5, random_state=1).fit(X[idx]).predict(X)
for c in range(3):
a = set(np.flatnonzero(base == c)) & set(idx)
scores[c].append(max(
len(a & set(np.flatnonzero(labels == d))) / max(1, len(a | (set(np.flatnonzero(labels == d)) & set(idx))))
for d in range(3)
))
print({c: round(float(np.mean(v)), 3) for c, v in scores.items()})X <- scale(iris[, 1:4])
set.seed(1)
boot <- fpc::clusterboot(X, B = 20, clustermethod = fpc::kmeansCBI,
k = 3, count = FALSE, seed = 1)
round(boot$bootmean, 3)Recap
Recap- Stability shows that a cluster reproduces; it can't show that it's correct.
- Testing clusters on the rows that formed them is double dipping. Use a holdout.
- Name segments as far as the columns support, and no further.
Concepts in this lesson