CDiscover · discover.choose_k
Choose the number of clusters
How many clusters does the data support?
Fits k-means, PAM or a Gaussian mixture for every k in a range and scores each solution: the elbow of the within-cluster sum of squares (kneedle), mean silhouette, Calinski–Harabasz, Davies–Bouldin, the gap statistic (k-means, reference sets from the host's shared random stream) and BIC (mixtures), plus prediction strength (stability of clusters across random halves) and ICL (BIC penalized for overlapping mixture components). The gap statistic can use a box aligned with the principal axes, several starts per reference set and cluster::maxSE's SE rules. Recommends k by the chosen criterion, shows what the others say, and returns the clustering at the recommended k.
A real result
Example “Iris kmeans gap”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
Comparing k = 2–6 with k-means, the gap statistic (first-SE rule) recommends k = 3 (2 of 5 criteria agree).
- Clusters
- 3
- Mean silhouette
- 0.4565
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 | 3 | −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 | 3 | 0.4075 | −1.754 |
| false | 1 | 1.075 | −0.2084 |
| false | 3 | 0.3887 | −0.5933 |
| false | 1 | 0.7465 | 0.7730 |
| false | 3 | −0.4873 | −1.852 |
| false | 1 | 0.9279 | 0.0322 |
| false | 3 | 0.0114 | −1.034 |
First 60 of 153 rows.
Recommended k = 3 by the gap statistic (first-SE rule).
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 |
| false | Within-cluster SS | 6 | 81.534 |
| true | Mean silhouette | 2 | 0.5818 |
| false | Mean silhouette | 3 | 0.4565 |
| false | Mean silhouette | 4 | 0.3819 |
| false | Mean silhouette | 5 | 0.3907 |
| false | Mean silhouette | 6 | 0.3430 |
| false | Gap | 2 | 0.9653 |
| true | Gap | 3 | 1.206 |
| false | Gap | 4 | 1.252 |
| false | Gap | 5 | 1.237 |
| false | Gap | 6 | 1.398 |
| true | Calinski–Harabasz | 2 | 251.35 |
| false | Calinski–Harabasz | 3 | 239.48 |
| false | Calinski–Harabasz | 4 | 206.68 |
| false | Calinski–Harabasz | 5 | 170.28 |
| false | Calinski–Harabasz | 6 | 183.13 |
| true | Davies–Bouldin | 2 | 0.5933 |
| false | Davies–Bouldin | 3 | 0.8275 |
| false | Davies–Bouldin | 4 | 0.8796 |
| false | Davies–Bouldin | 5 | 1.003 |
| false | Davies–Bouldin | 6 | 0.9180 |
View data
| Cluster | Silhouette width |
|---|---|
| 1 | 0.5556 |
| 1 | 0.5553 |
| 1 | 0.5507 |
| 1 | 0.5375 |
| 1 | 0.5353 |
| 1 | 0.5337 |
| 1 | 0.5305 |
| 1 | 0.5290 |
| 1 | 0.5207 |
| 1 | 0.5137 |
| 1 | 0.5015 |
| 1 | 0.4901 |
| 1 | 0.4873 |
| 1 | 0.4826 |
| 1 | 0.4752 |
| 1 | 0.4717 |
| 1 | 0.4645 |
| 1 | 0.4630 |
| 1 | 0.4627 |
| 1 | 0.4583 |
| 1 | 0.4498 |
| 1 | 0.4460 |
| 1 | 0.4357 |
| 1 | 0.4356 |
| 1 | 0.4351 |
| 1 | 0.4233 |
| 1 | 0.4192 |
| 1 | 0.4124 |
| 1 | 0.4121 |
| 1 | 0.4082 |
| 1 | 0.3961 |
| 1 | 0.3831 |
| 1 | 0.3573 |
| 1 | 0.3487 |
| 1 | 0.3404 |
| 1 | 0.3304 |
| 1 | 0.3030 |
| 1 | 0.2903 |
| 1 | 0.2754 |
| 1 | 0.2572 |
| 1 | 0.1811 |
| 1 | 0.1802 |
| 1 | 0.1706 |
| 1 | 0.1612 |
| 1 | 0.1576 |
| 1 | 0.1567 |
| 1 | 0.1210 |
| 1 | 0.0806 |
| 1 | 0.0693 |
| 1 | 0.0491 |
| 1 | 0.0465 |
| 1 | 0.0168 |
| 1 | −0.0033 |
| 1 | −0.0232 |
| 1 | −0.0438 |
| 2 | 0.7426 |
| 2 | 0.7413 |
| 2 | 0.7375 |
| 2 | 0.7374 |
| 2 | 0.7369 |
First 60 of 150 rows.
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 |
Criteria by k
| k | Within-cluster SS | Mean silhouette | Calinski–Harabasz | Davies–Bouldin | Gap | Gap SE |
|---|---|---|---|---|---|---|
| 2 | 222.36 | 0.5818 | 251.35 | 0.5933 | 0.9653 | 0.0234 |
| 3 | 140.90 | 0.4565 | 239.48 | 0.8275 | 1.206 | 0.0343 |
| 4 | 114.35 | 0.3819 | 206.68 | 0.8796 | 1.252 | 0.0618 |
| 5 | 105.31 | 0.3907 | 170.28 | 1.003 | 1.237 | 0.0515 |
| 6 | 81.534 | 0.3430 | 183.13 | 0.9180 | 1.398 | 0.0561 |
Comparing k = 2–6 with k-means, the gap statistic (first-SE rule) recommends k = 3 (2 of 5 criteria agree).
- Clusters
- 3
- Mean silhouette
- 0.4565
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 | 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 |
Criteria by k
| k | Within-cluster SS | Mean silhouette | Calinski–Harabasz | Davies–Bouldin | Gap | Gap SE |
|---|---|---|---|---|---|---|
| 2 | 222.36 | 0.5818 | 251.35 | 0.5933 | 0.9653 | 0.0234 |
| 3 | 140.90 | 0.4565 | 239.48 | 0.8275 | 1.206 | 0.0343 |
| 4 | 114.35 | 0.3819 | 206.68 | 0.8796 | 1.252 | 0.0618 |
| 5 | 105.31 | 0.3907 | 170.28 | 1.003 | 1.237 | 0.0515 |
| 6 | 81.534 | 0.3430 | 183.13 | 0.9180 | 1.398 | 0.0561 |
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 range above rowsml_iris · features: sepal_length, sepal_width, petal_length, petal_width
- Iris kmeans gapml_iris · features: sepal_length, sepal_width, petal_length, petal_width · label: species
- Usarrests elbowml_usarrests · features: Murder, Assault, UrbanPop, Rape · id: state
- Penguins gmm bicml_penguins · features: bill_len, bill_dep, flipper_len · label: species
- Penguins pam gowerml_penguins · features: bill_len, flipper_len, island
- Iris gap pca globalseml_iris · features: sepal_length, sepal_width, petal_length, petal_width · label: species
- Usarrests gap firstseml_usarrests · features: Murder, Assault, UrbanPop, Rape · id: state
- Iris prediction strengthml_iris · features: sepal_length, sepal_width, petal_length, petal_width · label: species
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.
- Known groupscategorical / boolean · 0–1 column
- Optional — compared with the recommended clusters; never used to choose k.
- Row labelscategorical / numeric · 0–1 column
- Optional names shown on the chart points.
Choices you make
model
- Clustering methoddefault kmeans
Clustering method whose k is being chosen.
- k-means(default) — Compares k values using k-means; fast, and suits round clusters of similar size.
- k-medoids (PAM) — Compares k values using k-medoids; slower, less sensitive to outliers, and works with Gower distance.
- Gaussian mixture — Compares k values using a Gaussian mixture; pick it when clusters may be elongated or overlap.
- Smallest kdefault 2
Smallest number of clusters to try.
- Largest kdefault 8
Largest number of clusters to try.
- Recommend bydefault silhouette
Score used to recommend k. Look at several: clear structure shows up on more than one.
- Mean silhouette (highest)(default) — Picks the k whose rows sit best inside their own cluster; a good general rule. For PAM it uses the PAM dissimilarities (Gower when chosen).
- Elbow of the within-cluster sum of squares — Picks the k where adding clusters stops helping much; quick and visual, but the bend can be vague. The sum of squares is Euclidean on the scaled features, even for a Gower PAM.
- Gap statistic, first-SE rule (k-means) — Compares within-cluster spread with uniform reference data and takes the first k within one SE of the next; k-means only.
- Calinski–Harabasz (highest) — Picks the k with the highest between-to-within spread ratio; fast, and favors compact round clusters. Euclidean only: it uses straight-line distance on the scaled features, even for a Gower PAM.
- Davies–Bouldin (lowest) — Picks the k where clusters overlap their nearest neighbors least; fast, and favors well-separated clusters. Euclidean only: it uses straight-line distance on the scaled features, even for a Gower PAM.
- BIC (lowest; Gaussian mixture) — Picks the k with the lowest BIC from a Gaussian mixture; use it with the mixture algorithm.
- ICL (lowest; Gaussian mixture) — BIC plus a penalty for rows split between components, so it prefers well-separated clusters over many overlapping ones; mixtures only.
- Prediction strength (largest k above the cutoff) — Clusters random halves separately and asks how often the other half's centers keep each cluster together; picks the largest k that stays stable. k-means and PAM.
- Starts per kdefault 5
Random starts for each k; the best is kept, so results don't hinge on one unlucky start.
- Gap reference setsdefault 10
Uniform reference data sets for the gap statistic (one k-means start each).
- Gap reference boxdefault uniform
Where the uniform reference data are drawn: each column's range, or a box aligned with the principal axes.
- Column ranges(default) — Uniform over each column's range; the simplest reference and what the gap statistic started with.
- Principal-axes box — Uniform over the range of the data rotated to its principal axes, then rotated back; fairer when columns are correlated (Tibshirani's second reference).
- Gap ruledefault tibshirani
How k is read off the gap curve. Software differs here, so the rule is printed with the result.
- Tibshirani 2001 (smallest k with Gap(k) ≥ Gap(k+1) − s(k+1))(default) — The rule from the original paper; tends to pick a small k.
- First maximum within one SE (cluster::clusGap firstSEmax) — The smallest k within one SE of the first local maximum of the gap curve; R's default.
- Global maximum within one SE (globalSEmax) — The smallest k within one SE of the largest gap; can pick a larger k when the curve keeps rising.
- Random halvesdefault 20
Random splits of the rows into halves; the prediction strength is averaged over them.
- Stability cutoffdefault 0.8
The largest k whose mean prediction strength reaches this is recommended; 0.8–0.9 are conventions, not tests.
- ICL penaltydefault map
How overlap is penalized: by each row's most likely component (mclust's ICL) or by the full soft entropy.
- Most likely component (mclust)(default) — Adds −2 Σ log of each row's top membership probability to the BIC; the same as mclust's ICL with the sign flipped.
- Soft entropy — Adds twice the entropy of all membership probabilities; penalizes every split row, not just its top component.
- Mixture covariancedefault full
Shape of each Gaussian mixture component: full ellipses, axis-aligned, one shared shape, or circles.
- Full(default) — Every component has its own size, shape and tilt; the most flexible, and it needs the most data.
- Diagonal — Components are ellipses along the axes; pick it for wide data or roughly uncorrelated features within clusters.
- Tied — All components share one shape; pick it when clusters look like shifted copies of each other.
- Spherical — Components are circles with their own sizes; the fewest parameters and the closest to k-means.
- PAM dissimilaritydefault auto
Dissimilarity for k-medoids: Gower handles mixed numbers and categories; Euclidean suits numbers only.
- Automatic (Gower when there are categories, else Euclidean)(default) — Uses Gower when any column is categorical and Euclidean otherwise; the usual choice.
- Euclidean on the scaled design — Straight-line distance on scaled numbers; the standard for numeric data, but sensitive to outliers.
- Gower (mixed types) — Averages a per-column difference across numbers and categories; pick it for mixed data.
Advanced
- Starts per reference setdefault 1
k-means starts on each reference data set; more starts make the reference spread less noisy.
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) — Rescales each number to mean 0 and SD 1 so every column counts equally in distances; the safe choice.
- No scaling — Keeps raw values, so wide-ranging columns dominate distances; pick it only when columns share one unit.
- Missing valuesdefault drop
Rows with missing values are left out, or filled with the column median (categories get none).
- Leave the row out(default) — Leaves out rows with a missing value; the clean choice when few are missing.
- Fill with the median (categories → none) — Fills numeric gaps with the median and leaves category gaps as no category; keeps every row, at some cost to the shape.
What it reports
- k
- How many groups, studies or clusters the analysis used. Many methods are less reliable when k is small.
- recommended_k
- Grouping rows so that rows in a group are similar; clusters are a summary, not ground truth.
- 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.
- agree
- How many of the criteria pick the same number of clusters as the recommendation.
- algorithm_label
- The algorithm whose solutions were compared across k, as the summary names it.
- criterion_label
- The criterion the recommendation follows, e.g. the gap statistic (first-SE rule) or BIC.
- k_max
- Smallest and largest number of clusters the comparison tried.
- k_min
- Smallest and largest number of clusters the comparison tried.
- n_criteria
- Number of criteria that voted on the number of clusters.
Per group, level or term: best_k[<criterion>], score[<criterion>,<k>] (within, silhouette, calinski_harabasz, davies_bouldin, gap, gap_se, bic, icl, prediction_strength, prediction_strength_sd), size[<cluster>], mean[<cluster>,<feature>], calinski_harabasz, davies_bouldin, ari, ami, nmi, center[<cluster>,<feature>]
Python and R
Python and R agree to 6 decimals (relative tolerance 1e-6). Python uses scikit-learn, kmedoids; R uses stats, cluster.
Default traps between the two languages
- Prediction strength draws its random halves (and the k-means starts in them) from a third shared stream (seed + 2); the principal-axes gap box uses symmetric eigenvectors signed so each axis's largest entry is positive, so both engines draw the same reference data up to rounding.
- k-means and PAM fits are the same as discover.kmeans / discover.pam (shared k-means++ starts; original PAM); mixtures use the scikit-learn EM twin (discover.gmm). The gap statistic draws its uniform reference sets and their starts from a second shared stream (seed + 1), so both engines score identical references.
The exact script CodeSplash ran for example “Iris kmeans gap” · 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 51c6198b4a3a368d
# 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
# %% 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_kmeans_gap/out-python")
values = {"n_used": len(rows)}
centers = None
center_ids = None
D = None
extra = {}
tables = []
charts = []
summary = None
# %% Clustering
ALGORITHM = "kmeans"
CRITERION = "gap"
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.")
ks = list(range(2, min(6, len(rows) - 1) + 1))
if len(ks) < 2:
cs.cs_error("CS_E_TOO_FEW_ROWS", what=f"Comparing k = 2 to 6", 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, 5, 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)
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"}
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"}
plot_k, plot_s, plot_c, plot_ch = [], [], [], []
for name in [c for c in ["within", "silhouette", "gap", "calinski_harabasz", "davies_bouldin", "bic"] 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": 6,
"criterion": "gap",
"n_init": 3,
"references": 5,
"gap_reference": "uniform",
"gap_starts": 1,
"gap_rule": "tibshirani",
"ps_splits": 20,
"ps_cutoff": 0.8,
"icl_variant": "map",
"covariance": "full",
"distance": "auto",
"scale": "standard",
"missing": "drop",
}},
})
The exact script CodeSplash ran for example “Iris kmeans gap” · 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 51c6198b4a3a368d
# 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_kmeans_gap/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 <- "gap"
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.")
ks <- seq.int(2, min(6, length(rows) - 1))
if (length(ks) < 2) cs_error("CS_E_TOO_FEW_ROWS", what = "Comparing k = 2 to 6", 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(5), 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)
}
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")
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")
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"), 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 = 6,
criterion = "gap",
n_init = 3,
references = 5,
gap_reference = "uniform",
gap_starts = 1,
gap_rule = "tibshirani",
ps_splits = 20,
ps_cutoff = 0.8,
icl_variant = "map",
covariance = "full",
distance = "auto",
scale = "standard",
missing = "drop"
))
))
Sources
- Tibshirani R, Walther G (2005). Cluster validation by prediction strength. J Comput Graph Stat 14(3):511–528.
- Biernacki C, Celeux G, Govaert G (2000). Assessing a mixture model for clustering with the integrated completed likelihood. IEEE TPAMI 22(7):719–725.
- Maechler M et al. cluster::clusGap and maxSE (firstSEmax, globalSEmax rules).
- Tibshirani R, Walther G, Hastie T (2001). Estimating the number of clusters in a data set via the gap statistic. JRSS B 63:411–423.
- Satopää V, Albrecht J, Irwin D, Raghavan B (2011). Finding a 'kneedle' in a haystack. ICDCSW, 166–171.
- Rousseeuw PJ (1987). Silhouettes. J Comput Appl Math 20:53–65.
From the CodeSplash method registry · discover.choose_k v1.1.0.