Skip to content

How many clusters?

The elbow, silhouette, gap statistic and BIC ask different questions, and clear structure shows up on more than one of them.

Applied ~11 min9 steps

What runs in CodeSplash

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

Read first

01

No single right number

Read

More clusters always lower the within-cluster sum of squares. With one cluster per row it reaches zero, and tells you nothing.

So choosing kk 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 kk in a range on several criteria at once, and tells you how many agree.

02

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.
03

Make a guess

Predict

Predict 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 kk = 3. 2 of the 5 criteria the card reports recommend that same kk.

04

Read the chart

Explore

An 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.

Choosing kHow many clusters does the data support?
View data
number of clusters kscorecriterionrecommended
21009.44within-cluster SSfalse
20.4790silhouettefalse
21.406gap statisticfalse
3604.67within-cluster SSfalse
30.5390silhouettefalse
31.667gap statisticfalse
4266.55within-cluster SStrue
40.5690silhouettetrue
41.883gap statistictrue
5212.94within-cluster SSfalse
50.5610silhouettefalse
51.900gap statisticfalse
6172.92within-cluster SSfalse
60.4890silhouettefalse
61.880gap statisticfalse
7158.52within-cluster SSfalse
70.4350silhouettefalse
71.844gap statisticfalse
8143.15within-cluster SSfalse
80.3800silhouettefalse
81.835gap statisticfalse
9125.91within-cluster SSfalse
90.3080silhouettefalse
91.793gap statisticfalse

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.

Silhouette plotHow well does each row fit its cluster compared with the next-nearest cluster?
View data
clustersilhouette width
10.8104
10.3858
10.7156
10.8822
10.5280
10.8851
10.8357
10.4391
10.3557
10.6602
10.8691
10.9200
10.4462
10.5385
10.9200
10.6822
10.6435
10.6843
10.7438
10.8095
10.8668
10.6558
10.8134
10.5108
10.6253
10.5719
10.4791
10.6238
10.5644
10.5638
10.5134
10.4693
10.8839
10.7331
10.5453
10.6360
10.5401
10.3675
10.9200
10.4117
10.2508
10.6429
10.6220
10.6689
10.6571
10.5136
10.7785
10.5513
10.6111
10.7136
10.9155
10.7088
10.2273
10.5913
10.8222
10.5787
10.6657
10.9200
10.7597
10.8080

First 60 of 150 rows.

05

When criteria disagree

Read

On US arrests the elbow recommends kk = 4, but only 1 of 4 criteria recommend that value, and the silhouette at that kk 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 kk. A segmentation may still be useful, but say that you chose its size for convenience.

06

Read the card

In the app
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
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"
  ))
))
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
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 kk, shows what the others say, and returns the clustering at that kk. With known species held back, adjusted Rand at the chosen kk is 0.645.

On penguins with a Gaussian mixture, BIC recommends kk = 3 and adjusted Rand reaches 0.930, where the species separate well on bill and flipper measurements.

07

Check your understanding

Checkpoint

Check yourself

Why can't you choose kk by picking the lowest within-cluster sum of squares?

Show the answer

Answer: b

A criterion for kk 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 kk, 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.

08

Do it on your own data

In the app

Open a clusterer in Find segments and use its Choose k tab, which runs the k explorer on your current form.

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

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 kk, and you should say so.

Concepts in this lesson