Skip to content

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.

Verified in Python and R Python and R agree to 6 decimals

A real result

Example “Iris kmeans gap”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

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

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

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

First 60 of 153 rows.

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

Recommended k = 3 by the gap statistic (first-SE rule).

View data
RecommendedCriterionClusters (k)Score
falseWithin-cluster SS2222.36
trueWithin-cluster SS3140.90
falseWithin-cluster SS4114.35
falseWithin-cluster SS5105.31
falseWithin-cluster SS681.534
trueMean silhouette20.5818
falseMean silhouette30.4565
falseMean silhouette40.3819
falseMean silhouette50.3907
falseMean silhouette60.3430
falseGap20.9653
trueGap31.206
falseGap41.252
falseGap51.237
falseGap61.398
trueCalinski–Harabasz2251.35
falseCalinski–Harabasz3239.48
falseCalinski–Harabasz4206.68
falseCalinski–Harabasz5170.28
falseCalinski–Harabasz6183.13
trueDavies–Bouldin20.5933
falseDavies–Bouldin30.8275
falseDavies–Bouldin40.8796
falseDavies–Bouldin51.003
falseDavies–Bouldin60.9180
Silhouette widthsHow well does each row fit its cluster compared with the next-nearest cluster?
View data
ClusterSilhouette width
10.5556
10.5553
10.5507
10.5375
10.5353
10.5337
10.5305
10.5290
10.5207
10.5137
10.5015
10.4901
10.4873
10.4826
10.4752
10.4717
10.4645
10.4630
10.4627
10.4583
10.4498
10.4460
10.4357
10.4356
10.4351
10.4233
10.4192
10.4124
10.4121
10.4082
10.3961
10.3831
10.3573
10.3487
10.3404
10.3304
10.3030
10.2903
10.2754
10.2572
10.1811
10.1802
10.1706
10.1612
10.1576
10.1567
10.1210
10.0806
10.0693
10.0491
10.0465
10.0168
1−0.0033
1−0.0232
1−0.0438
20.7426
20.7413
20.7375
20.7374
20.7369

First 60 of 150 rows.

Clusters

ClusterSizeSharesepal_lengthsepal_widthpetal_lengthpetal_width
15536.7%6.6963.0605.4181.938
24932.7%5.0163.4511.4650.2449
34630.7%5.7042.6354.2151.333

Criteria by k

kWithin-cluster SSMean silhouetteCalinski–HarabaszDavies–BouldinGapGap SE
2222.360.5818251.350.59330.96530.0234
3140.900.4565239.480.82751.2060.0343
4114.350.3819206.680.87961.2520.0618
5105.310.3907170.281.0031.2370.0515
681.5340.3430183.130.91801.3980.0561
Python

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

ClusterSizeSharesepal_lengthsepal_widthpetal_lengthpetal_width
15536.7%6.6963.0605.4181.938
24932.7%5.0163.4511.4650.2449
34630.7%5.7042.6354.2151.333

Criteria by k

kWithin-cluster SSMean silhouetteCalinski–HarabaszDavies–BouldinGapGap SE
2222.360.5818251.350.59330.96530.0234
3140.900.4565239.480.82751.2060.0343
4114.350.3819206.680.87961.2520.0618
5105.310.3907170.281.0031.2370.0515
681.5340.3430183.130.91801.3980.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.
Python

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

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.