How many clusters?
The elbow, silhouette, gap statistic and BIC ask different questions, and clear structure shows up on more than one of them.
What runs in CodeSplash
- Choose the number of clusters Verified in Python and R
You will be able to
- Read an elbow plot and a silhouette plot
- Say what the gap statistic and BIC add
- Treat disagreement between criteria as information
No single right number
ReadMore clusters always lower the within-cluster sum of squares. With one cluster per row it reaches zero, and tells you nothing.
So choosing means trading fit against simplicity. Each criterion makes that trade differently, and they can disagree. That's why the Choose the number of clusters method scores every in a range on several criteria at once, and tells you how many agree.
The four questions
Read- Elbow: where do further clusters stop paying off? Look for the bend in the within-cluster sum of squares.
- SilhouetteSilhouette scoreHow well each point sits in its cluster compared with the nearest other cluster, from −1 to 1.: how much closer is a row to its own cluster than to the next one? Higher is better.
- Gap statisticGap statisticCompares within-cluster spread with what structureless reference data gives; a larger gap suggests that k adds real structure.: how much tighter are the clusters than on structureless data with the same range? It's the one criterion here that compares against a no-structure baseline.
- BICBICLike AIC but with a stronger penalty for parameters as n grows; favors simpler models.: for mixture models, how much likelihood do you gain per parameter? Lower is better.
Make a guess
PredictPredict first
Iris has three species, but two of them overlap. On scaled features, what will the gap statistic recommend?
Make your guess between 2 and 6 clusters, then reveal.
Reveal
It recommends = 3. 2 of the 5 criteria the card reports recommend that same .
Read the chart
ExploreAn elbow plot rarely has the crisp bend that textbooks show. Find the point after which the curve flattens, then look for the same answer elsewhere.
View data
| number of clusters k | score | criterion | recommended |
|---|---|---|---|
| 2 | 1009.44 | within-cluster SS | false |
| 2 | 0.4790 | silhouette | false |
| 2 | 1.406 | gap statistic | false |
| 3 | 604.67 | within-cluster SS | false |
| 3 | 0.5390 | silhouette | false |
| 3 | 1.667 | gap statistic | false |
| 4 | 266.55 | within-cluster SS | true |
| 4 | 0.5690 | silhouette | true |
| 4 | 1.883 | gap statistic | true |
| 5 | 212.94 | within-cluster SS | false |
| 5 | 0.5610 | silhouette | false |
| 5 | 1.900 | gap statistic | false |
| 6 | 172.92 | within-cluster SS | false |
| 6 | 0.4890 | silhouette | false |
| 6 | 1.880 | gap statistic | false |
| 7 | 158.52 | within-cluster SS | false |
| 7 | 0.4350 | silhouette | false |
| 7 | 1.844 | gap statistic | false |
| 8 | 143.15 | within-cluster SS | false |
| 8 | 0.3800 | silhouette | false |
| 8 | 1.835 | gap statistic | false |
| 9 | 125.91 | within-cluster SS | false |
| 9 | 0.3080 | silhouette | false |
| 9 | 1.793 | gap statistic | false |
A silhouette plot shows each row as a bar, grouped by cluster. Wide bars mean well-placed rows. Bars below zero mean rows that sit closer to another cluster than to their own.
View data
| cluster | silhouette width |
|---|---|
| 1 | 0.8104 |
| 1 | 0.3858 |
| 1 | 0.7156 |
| 1 | 0.8822 |
| 1 | 0.5280 |
| 1 | 0.8851 |
| 1 | 0.8357 |
| 1 | 0.4391 |
| 1 | 0.3557 |
| 1 | 0.6602 |
| 1 | 0.8691 |
| 1 | 0.9200 |
| 1 | 0.4462 |
| 1 | 0.5385 |
| 1 | 0.9200 |
| 1 | 0.6822 |
| 1 | 0.6435 |
| 1 | 0.6843 |
| 1 | 0.7438 |
| 1 | 0.8095 |
| 1 | 0.8668 |
| 1 | 0.6558 |
| 1 | 0.8134 |
| 1 | 0.5108 |
| 1 | 0.6253 |
| 1 | 0.5719 |
| 1 | 0.4791 |
| 1 | 0.6238 |
| 1 | 0.5644 |
| 1 | 0.5638 |
| 1 | 0.5134 |
| 1 | 0.4693 |
| 1 | 0.8839 |
| 1 | 0.7331 |
| 1 | 0.5453 |
| 1 | 0.6360 |
| 1 | 0.5401 |
| 1 | 0.3675 |
| 1 | 0.9200 |
| 1 | 0.4117 |
| 1 | 0.2508 |
| 1 | 0.6429 |
| 1 | 0.6220 |
| 1 | 0.6689 |
| 1 | 0.6571 |
| 1 | 0.5136 |
| 1 | 0.7785 |
| 1 | 0.5513 |
| 1 | 0.6111 |
| 1 | 0.7136 |
| 1 | 0.9155 |
| 1 | 0.7088 |
| 1 | 0.2273 |
| 1 | 0.5913 |
| 1 | 0.8222 |
| 1 | 0.5787 |
| 1 | 0.6657 |
| 1 | 0.9200 |
| 1 | 0.7597 |
| 1 | 0.8080 |
First 60 of 150 rows.
When criteria disagree
ReadOn US arrests the elbow recommends = 4, but only 1 of 4 criteria recommend that value, and the silhouette at that is modest at 0.334.
That isn't a failure. Recall that the tendency test found little clumping here. States vary smoothly, so there is no natural . A segmentation may still be useful, but say that you chose its size for convenience.
Read the card
In the appComparing 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 |
The exact R script · R R version 4.5.1 (2025-06-13)
# Choose the number of clusters
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.choose_k 1.1.0 · spec 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"
))
))
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 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Choose the number of clusters
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.choose_k 1.1.0 · spec 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 card recommends a , shows what the others say, and returns the clustering at that . With known species held back, adjusted Rand at the chosen is 0.645.
On penguins with a Gaussian mixture, BIC recommends = 3 and adjusted Rand reaches 0.930, where the species separate well on bill and flipper measurements.
Check your understanding
CheckpointCheck yourself
Why can't you choose by picking the lowest within-cluster sum of squares?
Show the answer
Answer: b
A criterion for must penalize complexity or compare against a baseline. The raw sum of squares does neither.
Check yourself
Several rows have negative silhouette values. What does that mean?
Show the answer
Answer: b
Silhouette compares a row's distance to its own cluster with its distance to the nearest other one. Negative values point to overlap or a poor , and don't by themselves justify removing data.
Check yourself
Which criterion is built to compare your clustering with data that has no structure?
Show the answer
Answer: c
The gap statistic simulates reference data over the same range and asks how much tighter your clusters are than the reference's. That's also why it takes longer.
Do it on your own data
In the appOpen a clusterer in Find segments and use its Choose k tab, which runs the k explorer on your current form.
from sklearn.cluster import KMeans
from sklearn.datasets import load_iris
from sklearn.metrics import silhouette_score
from sklearn.preprocessing import StandardScaler
X = StandardScaler().fit_transform(load_iris().data)
for k in range(2, 7):
km = KMeans(n_clusters=k, n_init=5, random_state=1).fit(X)
print(k, round(km.inertia_, 1), round(silhouette_score(X, km.labels_), 3))X <- scale(iris[, 1:4])
set.seed(1)
for (k in 2:6) {
km <- kmeans(X, centers = k, nstart = 5)
sil <- cluster::silhouette(km$cluster, dist(X))
cat(k, round(km$tot.withinss, 1), round(mean(sil[, 3]), 3), "\n")
}Recap
Recap- More clusters always fit better, so every criterion penalizes or compares.
- Clear structure shows up on several criteria at once.
- Disagreement is information. If nothing agrees, there may be no natural , and you should say so.
Concepts in this lesson