CDiscover · discover.stability
How stable are the clusters? (bootstrap)
Would the same clusters come back if the data were collected again?
Fits its own clustering of the kind you pick (k-means; PAM or hierarchical on Euclidean distances of the scaled features; or a DBSCAN-like density cut at one radius) with the options set here, re-runs it on bootstrap resamples and asks, for every original cluster, how well its best-matching bootstrap cluster overlaps it (clusterwise Jaccard; Hennig 2007): above 0.85 is highly stable, 0.6–0.75 shows a pattern, 0.5 or less means the cluster dissolves. It doesn't re-run a clustering you saved, so a Gower PAM, HDBSCAN or mixture-model run isn't what gets tested. A consensus matrix (how often two rows land together) and its PAC score summarize how crisp the clustering is. Resamples and starts come from the shared stream, so both engines agree.
A real result
Example “Iris three”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
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 |
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 |
Shortened for the Academy: 3 chart(s) dropped to stay under 100 KB; 3 chart(s) dropped to stay under 100 KB.
Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.
Worked examples in the app
- Regress k not below rowsml_iris · features: sepal_length, sepal_width, petal_length, petal_width
- Iris threeml_iris · features: sepal_length, sepal_width, petal_length, petal_width · label: species
- Iris pamml_iris · features: sepal_length, sepal_width, petal_length, petal_width · label: species
- Usarrests hierarchicalml_usarrests · features: Murder, Assault, UrbanPop, Rape
- Iris densityml_iris · features: sepal_length, sepal_width, petal_length, petal_width
- Usarrests fourml_usarrests · features: Murder, Assault, UrbanPop, Rape
In the guides
Where it sits in the decision guides
- Clustering (k-means, hierarchical) · DS & ML Decision Guide · Discover — find structure without labels
- Discover: cluster quality (silhouette, ARI); coherence (topics); stability and interpretability · DS & ML Decision Guide · How to evaluate — common metrics by question type
- Discover: simplicity vs. fidelity; stability vs. flexibility · DS & ML Decision Guide · Key trade-offs by question type
What you need
- Featuresnumeric / categorical / boolean · 1–200 columns
- Variables that define similarity (scaled; categories as 0/1 columns).
- Known groupscategorical / boolean · 0–1 column
- Optional — compared with the clusters; never used to fit.
- Row labelscategorical / numeric · 0–1 column
- Optional names shown on the chart points.
Choices you make
model
- Clusteringdefault kmeans
The kind of clustering to refit and test. It fits its own version with the settings below (PAM and hierarchical on Euclidean distances), so it shows how stable that kind of clustering is on these features, not whether a saved run with other settings is. Stability belongs to a method, not to the data.
- k-means(default) — Round clusters around means.
- PAM (k-medoids, Euclidean) — Clusters around real rows; less pulled by outliers than k-means. Uses Euclidean distances on the scaled features, not Gower.
- Hierarchical (Euclidean) — A merge tree on Euclidean distances of the scaled features, cut into k clusters.
- Density (DBSCAN-like, one radius) — Dense regions at one radius, cut from an OPTICS ordering; the number of clusters isn't set, and sparse rows become noise. Not HDBSCAN.
- Clusters (k)default 3
Number of clusters to test.
- Linkagedefault ward
How the merge tree measures the distance between two groups.
- Ward(default) — Merges the pair that adds least within-cluster variance; compact, even clusters.
- Complete — Distance between the farthest rows; compact clusters.
- Average — Mean distance between the rows of the two groups.
- Single — Distance between the nearest rows; finds chains, and is sensitive to noise.
- Minimum neighborsdefault 5
Rows needed nearby (the row itself included) to be a core point.
- Neighborhood radiusdefault —
How close counts as nearby, fixed across resamples.
- Bootstrap resamplesdefault 50
More resamples = steadier Jaccard averages (and a slower run).
Advanced
- Starts per fitdefault 5
k-means++ starts per fit; the lowest within-cluster sum of squares wins.
preprocess
- Scale numbersdefault standard
Standardize numbers so each counts equally in distances; turn off only when columns already share one unit.
- Standardize (population SD)(default) — Every variable gets equal weight.
- No scaling — Keep the original units.
- Missing valuesdefault drop
Rows with missing values are left out, or filled with the column median (categories get none).
- Leave the row out(default) — Use complete rows only.
- Fill with the median (categories → none) — Keep every row.
What it reports
- k
- How many groups, studies or clusters the analysis used. Many methods are less reliable when k is small.
- n_used
- How many independent units the analysis used; it sets precision and power.
- n_noise
- How many independent units the analysis used; it sets precision and power.
- silhouette
- How well each point sits in its cluster compared with the nearest other cluster, from −1 to 1.
- mean_jaccard
- How well each cluster comes back when the data are resampled, as the mean Jaccard overlap with its best match.
- min_jaccard
- How well each cluster comes back when the data are resampled, as the mean Jaccard overlap with its best match.
- n_dissolved
- How many independent units the analysis used; it sets precision and power.
- n_stable
- How many independent units the analysis used; it sets precision and power.
- pac
- For each pair of rows, the share of resamples in which they land in the same cluster.
- boots
- Estimates uncertainty by recomputing a statistic on many samples drawn with replacement from your data.
Per group, level or term: jaccard[<cluster>], size[<cluster>], mean[<cluster>,<feature>], algorithm, eps, min_samples, calinski_harabasz, davies_bouldin, ari, ami, nmi
Python and R
Python and R agree to 10 decimals (relative tolerance 1e-9). Python uses numpy; R uses codesplashr.
Default traps between the two languages
- Beyond k-means each drawn row is clustered once (fpc::clusterboot's multipleboot = FALSE). PAM and density use twins with fixed tie rules; hierarchical uses scipy linkage and stats::hclust, whose merges can differ when dissimilarities tie exactly.
- Both engines run a plain Lloyd k-means twin (k-means++ starts from the shared stream, nearest center with ties to the lowest, empty clusters keep their center) on the same bootstrap indices. fpc::clusterboot uses R's random numbers and stats::kmeans (which stops on empty clusters), so its Jaccard values differ draw to draw.
The exact script CodeSplash ran for example “Iris three” · 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",
}},
})
The exact script CodeSplash ran for example “Iris three” · 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"
))
))
Sources
- Hennig C (2007). Cluster-wise assessment of cluster stability. Computational Statistics & Data Analysis 52:258–271.
- Monti S, Tamayo P, Mesirov J, Golub T (2003). Consensus clustering. Machine Learning 52:91–118.
- Șenbabaoğlu Y, Michailidis G, Li JZ (2014). Critical limitations of consensus clustering in class discovery. Scientific Reports 4:6207.
From the CodeSplash method registry · discover.stability v1.1.1.