Skip to content

Validity indices: silhouette, Calinski–Harabasz, Davies–Bouldin, gap and Hopkins

Internal indices score a partition without labels, and the Hopkins statistic asks whether there is anything to cluster. What each formula rewards, the geometry it quietly assumes, and why the best score is not evidence that clusters exist.

Advanced ~14 min9 steps

What runs in CodeSplash

You will be able to

  • Write silhouette, Calinski–Harabasz and Davies–Bouldin and say which shapes each favors
  • Explain the gap statistic's reference data and why the selection rule must be named
  • Read a Hopkins statistic with its sampling convention and its blind spots
  • Use indices to compare candidate partitions, not to prove that groups exist

Read first

01

Scoring without labels

Read

With no labels, a partition can only be judged by its own geometry: how tight the clusters are and how far apart. Internal indices turn that into a number, so you can compare kk = 3 with kk = 4, or k-means with a mixture, on the same rows.

Two cautions run through this lesson. Each index rewards a particular shape of cluster, usually compact and round. And the best score among the candidates you tried is a comparison, not evidence that real groups exist. For that question, see the next lesson.

02

Silhouette

Read

For row ii, let aia_i be the mean distance to its own cluster and bib_i the mean distance to the nearest other cluster. Its silhouetteSilhouette scoreHow well each point sits in its cluster compared with the nearest other cluster, from −1 to 1. is si=(bi−ai)/max⁡(ai,bi)s_i=(b_i-a_i)/\max(a_i,b_i), between −1 and 1; the index is the mean SS.

On the reference's tiny, well-separated example SS is 0.900; k-means on iris reaches 0.463. Look at the distribution per cluster, not only the mean. Silhouette needs a distance, so use the same one the clustering used, decide how noise rows count, and remember that a silhouette computed on a 2-D map describes the map.

03

Calinski–Harabasz and Davies–Bouldin

Read

Calinski–HarabaszCalinski–Harabasz indexBetween-cluster spread over within-cluster spread. Higher means tighter, better-separated clusters. is a variance ratio: between-cluster scatter over within-cluster scatter, each per degree of freedom,

CH=tr⁡(B)/(k−1)tr⁡(W)/(n−k).CH=\frac{\operatorname{tr}(B)/(k-1)}{\operatorname{tr}(W)/(n-k)}.

Higher is better. Davies–BouldinDavies–Bouldin indexHow much each cluster overlaps its most similar neighbor, on average. Lower is better; 0 is the floor. averages, over clusters, the worst ratio of combined spread to center distance, DB=1k∑imax⁡j≠iSi+Sj∥μi−μj∥DB=\frac1k\sum_i\max_{j\ne i}\frac{S_i+S_j}{\lVert\mu_i-\mu_j\rVert}. Lower is better.

On iris with k-means: CH 241, DB 0.832. Both use centroids and Euclidean scatter, so both favor round, convex clusters and penalize rings, chains and clusters of different density.

04

Two rings

Predict

Predict first

Two nested rings: the inner ring is one group, the outer ring another. k-means instead cuts the picture into left and right halves. Which partition gets the better Calinski–Harabasz score?

The ring partitionk-means' halves
Reveal

k-means' halves. Rings share a center, so the "true" partition has almost no between-cluster scatter. Centroid-based indices reward convex groups; they can't see density or connectivity. Choose an index that matches the cluster idea you care about, or check stability instead.

05

The gap statistic

Read

The gap statisticGap statisticCompares within-cluster spread with what structureless reference data gives; a larger gap suggests that k adds real structure. compares the within-cluster dispersion WkW_k with what the same algorithm gets on reference data with no clusters: Gap(k)=1B∑blog⁡Wkb∗−log⁡Wk\text{Gap}(k)=\frac1B\sum_b\log W^{*}_{kb}-\log W_k. Reference sets are drawn uniformly in the data's bounding box, or in a box aligned with its principal axes.

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

Comparing k = 2–6 with k-means, the gap statistic (firstSEmax rule) recommends k = 4 (2 of 5 criteria agree).

Clusters
4
Mean silhouette
0.3344

Plots

ClustersWhich rows group together, and how well separated are the groups?
View data
CenterClusterRowPC1 (62%)PC2 (25%)
false4Alabama0.9856−1.133
false4Alaska1.950−1.073
false3Arizona1.7630.7460
false4Arkansas−0.1414−1.120
false3California2.5241.543
false3Colorado1.5150.9876
false1Connecticut−1.3591.089
false1Delaware0.04770.3254
false3Florida3.013−0.0392
false4Georgia1.639−1.279
false1Hawaii−0.91271.570
false2Idaho−1.640−0.2110
false3Illinois1.3790.6818
false1Indiana−0.50550.1516
false2Iowa−2.2540.1041
false1Kansas−0.79690.2702
false2Kentucky−0.7509−0.9584
false4Louisiana1.565−0.8711
false2Maine−2.397−0.3764
false3Maryland1.763−0.4277
false1Massachusetts−0.48621.474
false3Michigan2.1080.1554
false2Minnesota−1.6930.6323
false4Mississippi0.9965−2.394
false3Missouri0.69680.2634
false2Montana−1.185−0.5369
false2Nebraska−1.2660.1940
false3Nevada2.8740.7756
false2New Hampshire−2.3840.0181
false1New Jersey0.18161.450
false3New Mexico1.980−0.1428
false3New York1.6830.8232
false4North Carolina1.123−2.228
false2North Dakota−2.992−0.5991
false1Ohio−0.22600.7422
false1Oklahoma−0.31180.2879
false1Oregon0.05910.5414
false1Pennsylvania−0.88840.5711
false1Rhode Island−0.86381.492
false4South Carolina1.321−1.933
false2South Dakota−1.988−0.8233
false4Tennessee0.9997−0.8603
false3Texas1.3550.4125
false1Utah−0.55061.472
false2Vermont−2.801−1.402
false1Virginia−0.0963−0.1997
false1Washington−0.21690.9701
false2West Virginia−2.109−1.425
false2Wisconsin−2.0800.6113
false1Wyoming−0.6294−0.3210
true1center 1−0.47220.7429
true2center 2−1.965−0.3671
true3center 31.8880.4815
true4center 41.160−1.432
Criteria by number of clustersHow many clusters does the data support?

Recommended k = 4 by the gap statistic (firstSEmax rule).

View data
RecommendedCriterionClusters (k)Score
falseWithin-cluster SS2104.96
falseWithin-cluster SS380.116
trueWithin-cluster SS458.207
falseWithin-cluster SS550.930
falseWithin-cluster SS644.204
trueMean silhouette20.4085
falseMean silhouette30.3139
falseMean silhouette40.3344
falseMean silhouette50.2933
falseMean silhouette60.2858
falseGap20.6222
falseGap30.6713
trueGap40.8239
falseGap50.7758
falseGap60.7806
trueCalinski–Harabasz243.462
falseCalinski–Harabasz335.165
falseCalinski–Harabasz437.352
falseCalinski–Harabasz532.928
falseCalinski–Harabasz631.016
trueDavies–Bouldin20.9697
falseDavies–Bouldin31.043
falseDavies–Bouldin41.036
falseDavies–Bouldin51.118
falseDavies–Bouldin61.171
Silhouette widthsHow well does each row fit its cluster compared with the next-nearest cluster?
View data
ClusterSilhouette width
10.4967
10.4821
10.4479
10.4399
10.4371
10.3387
10.3353
10.3307
10.3279
10.3154
10.3076
10.3047
10.2799
10.2633
10.2272
10.1073
20.5444
20.5443
20.5303
20.5227
20.5044
20.4901
20.4848
20.3969
20.2739
20.2657
20.1416
20.0896
20.0655
30.4670
30.4586
30.4468
30.4268
30.4164
30.3621
30.3499
30.3354
30.3087
30.2965
30.1627
3−0.0343
40.4805
40.4742
40.3829
40.3824
40.2927
40.2280
40.1903
40.0568
4−0.0583

Clusters

ClusterSizeShareMurderAssaultUrbanPopRape
11632.0%5.656138.8873.87518.781
21326.0%3.60078.53852.07712.177
31224.0%10.883256.9278.33332.250
4918.0%13.500245.7853.11123.978

Criteria by k

kWithin-cluster SSMean silhouetteCalinski–HarabaszDavies–BouldinGapGap SE
2104.960.408543.4620.96970.62220.0969
380.1160.313935.1651.0430.67130.0853
458.2070.334437.3521.0360.82390.0681
550.9300.293332.9281.1180.77580.0981
644.2040.285831.0161.1710.78060.1017
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 ae623e8f528b089a
# Dataset: ml_usarrests (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("Murder", "Assault", "UrbanPop", "Rape")
LABEL <- NULL  # known groups (external validation only)
ROW_ID <- "state"  # row labels for charts
SEED <- 42
KINDS <- list(
  Murder = "numeric",
  Assault = "numeric",
  UrbanPop = "numeric",
  Rape = "numeric"
)
LEVELS <- list(
)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_usarrests.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/usarrests_gap_firstse/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 <- 5
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(6), 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_cp_gap_choose(ks, gap, se, "first_se_max")
}
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")
LABELS[["gap"]] <- "gap statistic (firstSEmax rule)"
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 = 5,
    references = 6,
    gap_reference = "uniform",
    gap_starts = 1,
    gap_rule = "first_se_max",
    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 (firstSEmax rule) recommends k = 4 (2 of 5 criteria agree).

Clusters
4
Mean silhouette
0.3344

To keep this page light, the plots are shown once, under the R tab.

Clusters

ClusterSizeShareMurderAssaultUrbanPopRape
11632.0%5.656138.8873.87518.781
21326.0%3.60078.53852.07712.177
31224.0%10.883256.9278.33332.250
4918.0%13.500245.7853.11123.978

Criteria by k

kWithin-cluster SSMean silhouetteCalinski–HarabaszDavies–BouldinGapGap SE
2104.960.408543.4620.96970.62220.0969
380.1160.313935.1651.0430.67130.0853
458.2070.334437.3521.0360.82390.0681
550.9300.293332.9281.1180.77580.0981
644.2040.285831.0161.1710.78060.1017
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 ae623e8f528b089a
# Dataset: ml_usarrests (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
from codesplash.ml import cluster_partition as cpart

# %% Data
FEATURES = ["Murder", "Assault", "UrbanPop", "Rape"]
LABEL = None  # known groups (external validation only)
ROW_ID = "state"  # row labels for charts
SEED = 42
KINDS = {
    "Murder": "numeric",
    "Assault": "numeric",
    "UrbanPop": "numeric",
    "Rape": "numeric",
}
LEVELS = {
}
df = pd.read_parquet("tests/parity/fixtures/ml_usarrests.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/usarrests_gap_firstse/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 = 5
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, 6, 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"] = cpart.gap_choose(ks, gap, se, "first_se_max")
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"}
LABELS["gap"] = "gap statistic (firstSEmax rule)"
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": 5,
        "references": 6,
        "gap_reference": "uniform",
        "gap_starts": 1,
        "gap_rule": "first_se_max",
        "ps_splits": 20,
        "ps_cutoff": 0.8,
        "icl_variant": "map",
        "covariance": "full",
        "distance": "auto",
        "scale": "standard",
        "missing": "drop",
    }},
})

A rule then picks kk from the gap curve and its standard errors, and rules differ (first-SE, global-SE, Tibshirani's original). Name the rule. And a uniform box is a poor "no clusters" picture for data on a curve or with hard limits.

06

Hopkins: is there anything to cluster?

Read

The Hopkins statisticHopkins statisticCompares nearest-neighbor distances from real rows with those from random points; near 0.5 = no structure, near 1 = clumped. compares distances from mm random points in the data's region to their nearest data rows (uiu_i) with distances from mm sampled rows to their nearest other rows (wiw_i): H=∑uid∑uid+∑widH=\frac{\sum u_i^d}{\sum u_i^d+\sum w_i^d}. Near 0.5 means no tendency; near 1 means rows clump.

Is there cluster structure? (Hopkins + VAT)Recorded · Python and R agreeRecorded 2026-11-09 · 8 values compared
R

Hopkins statistic 0.99 (p = 5.62e-25): the rows look clearly clumped.

Hopkins H
0.9937
p (vs. random scatter)
< .001

Hopkins draws

DrawH
10.9928
20.9968
30.9988
40.9982
50.9942
60.9978
70.9986
80.9630
90.9984
100.9982
The exact R script · R R version 4.5.1 (2025-06-13)
# Is there cluster structure? (Hopkins + VAT)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.tendency 1.0.0 · spec 626f768f90a4bac3
# 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")
SEED <- 42
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_iris.parquet", col_select = FEATURES))
n_input <- nrow(df)
warnings <- list()
rows <- cs_ml_complete_rows(df, FEATURES)
if (length(rows) < n_input) {
  warnings <- c(warnings, sprintf("%d of %d rows were left out because a value was missing.", n_input - length(rows), n_input))
}
if (length(rows) < 10) stop("The tendency check needs at least 10 complete rows.")
X <- cs_ml_numeric_matrix(df, FEATURES, rows)
s <- apply(X, 2, stats::sd)
s[s == 0] <- 1
X <- sweep(sweep(X, 2, colMeans(X)), 2, s, "/")

# %% Hopkins statistic (shared-stream sampling)
m <- max(2, min(length(rows) - 1, ceiling(0.1 * length(rows))))
hop <- cs_ml_hopkins(X, m, SEED, reps = 10, power = "dimension")

# %% VAT (<= 500 evenly spaced rows)
vat_rows <- cs_ml_even_sample(length(rows), 500)
D <- cs_ml_euclidean_matrix(X[vat_rows + 1L, , drop = FALSE])
ord <- cs_ml_vat(D)
img <- cs_ml_block_image(D, ord, cap = 80)
b <- img$blocks
values <- list(n = length(rows), m = m, hopkins = hop$hopkins, hopkins_first = hop$first, hopkins_sd = hop$sd,
               p_value = hop$p_value, n_vat = length(vat_rows), vat_check = cs_ml_checksum(as.numeric(ord), seq_along(ord) - 1L))
grid <- expand.grid(col = seq_len(b), row = seq_len(b))
vs <- img$image[cbind(grid$row, grid$col)]
H <- hop$hopkins
verdict <- if (H >= 0.75) "clearly clumped" else if (H >= 0.6) "somewhat clumped" else "close to random scatter"
cs_publish(list(
  title = "Is there cluster structure? (Hopkins + VAT)",
  engine = cs_engine_info("codesplashr", "nanoparquet"),
  n = length(rows),
  summary = sprintf("Hopkins statistic %.2f (p = %s): the rows look %s.", H, format(signif(hop$p_value, 3)), verdict),
  statistics = list(list(key = "hopkins", label = "Hopkins H", value = H),
                    list(key = "p_value", label = "p (vs. random scatter)", value = hop$p_value, format = "p")),
  tables = list(list(key = "draws", title = "Hopkins draws",
                     columns = list(list(key = "draw", label = "Draw", type = "integer"), list(key = "h", label = "H", type = "number")),
                     rows = lapply(seq_along(hop$draws), function(i) list(draw = i, h = hop$draws[i])))),
  charts = list(cs_chart("vat", "vat-heatmap", "Reordered distances (VAT)", list(
    col = cs_col("Column block", grid$col, "numeric"),
    row = cs_col("Row block", grid$row, "numeric"),
    distance = cs_col("Mean distance", vs, "numeric")
  ), note = sprintf("Dark blocks on the diagonal are candidate clusters; %s rows in %d × %d blocks.", format(length(vat_rows), big.mark = ","), b, b))),
  values = values,
  warnings = warnings
))
Python

Hopkins statistic 0.99 (p = 5.62e-25): the rows look clearly clumped.

Hopkins H
0.9937
p (vs. random scatter)
< .001

Hopkins draws

DrawH
10.9928
20.9968
30.9988
40.9982
50.9942
60.9978
70.9986
80.9630
90.9984
100.9982
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Is there cluster structure? (Hopkins + VAT)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.tendency 1.0.0 · spec 626f768f90a4bac3
# 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 math

import numpy as np
import pandas as pd

import codesplash as cs
from codesplash.ml import cluster as csc
from codesplash.ml import discover_ext as dx
from codesplash.ml import embed as csembed

# %% Data
FEATURES = ["sepal_length", "sepal_width", "petal_length", "petal_width"]
SEED = 42
df = pd.read_parquet("tests/parity/fixtures/ml_iris.parquet", columns=FEATURES)
n_input = len(df)
warnings = []
rows = csembed.complete_rows(df, FEATURES)
if len(rows) < n_input:
    warnings.append(f"{n_input - len(rows)} of {n_input} rows were left out because a value was missing.")
if len(rows) < 10:
    raise ValueError("The tendency check needs at least 10 complete rows.")
X = csembed.standardize(csembed.numeric_matrix(df, FEATURES, rows), ddof=1)

# %% Hopkins statistic (shared-stream sampling)
m = max(2, min(len(rows) - 1, math.ceil(0.1 * len(rows))))
hop = dx.hopkins(X, m, SEED, reps=10, power="dimension")

# %% VAT (≤ 500 evenly spaced rows)
vat_rows = csc.even_sample(len(rows), 500)
D = dx.euclidean_matrix(X[vat_rows])
order = dx.vat(D)
image, b = dx.block_image(D, order, cap=80)
values = {
    "n": len(rows), "m": m, "hopkins": hop["hopkins"], "hopkins_first": hop["first"], "hopkins_sd": hop["sd"],
    "p_value": hop["p_value"], "n_vat": len(vat_rows),
    "vat_check": csembed.checksum(order.astype(np.float64), np.arange(len(order))),
}
xs, ys, vs = [], [], []
for i in range(b):
    for j in range(b):
        xs.append(j + 1)
        ys.append(i + 1)
        vs.append(float(image[i, j]))
H = hop["hopkins"]
verdict = "clearly clumped" if H >= 0.75 else ("somewhat clumped" if H >= 0.6 else "close to random scatter")
cs.publish({
    "title": "Is there cluster structure? (Hopkins + VAT)",
    "engine": cs.engine_info("numpy", "scipy", "pandas"),
    "n": len(rows),
    "summary": f"Hopkins statistic {H:.2f} (p = {hop['p_value']:.3g}): the rows look {verdict}.",
    "statistics": [
        {"key": "hopkins", "label": "Hopkins H", "value": H},
        {"key": "p_value", "label": "p (vs. random scatter)", "value": hop["p_value"], "format": "p"},
    ],
    "tables": [{
        "key": "draws",
        "title": "Hopkins draws",
        "columns": [{"key": "draw", "label": "Draw", "type": "integer"}, {"key": "h", "label": "H", "type": "number"}],
        "rows": [{"draw": i + 1, "h": float(h)} for i, h in enumerate(hop["draws"])],
    }],
    "charts": [cs.chart("vat", "vat-heatmap", "Reordered distances (VAT)", {
        "col": cs.col("Column block", xs, "numeric"),
        "row": cs.col("Row block", ys, "numeric"),
        "distance": cs.col("Mean distance", vs, "numeric"),
    }, note=f"Dark blocks on the diagonal are candidate clusters; {len(vat_rows):,} rows in {b} × {b} blocks.")],
    "values": values,
    "warnings": warnings,
})

Shortened for the Academy: 1 chart(s) dropped to stay under 100 KB; 1 chart(s) dropped to stay under 100 KB.

Iris gives 0.994; the arrests data give 0.594 from only 10 probes. A skewed single population, edges, irrelevant columns and duplicates can all push HH up. State the convention and repeat the sampling.

07

Where each idea stands in CodeSplash

Read
EntryIn CodeSplash
Silhouette (EVA001)Runs in CodeSplash: every clustering result, Choose the number of clusters and How stable are the clusters?
Calinski–Harabasz (EVA002)Runs in CodeSplash: same places
Davies–Bouldin (EVA003)Runs in CodeSplash: same places
Gap statistic (EVA004)Runs in CodeSplash: Choose the number of clusters with box or PCA-box references, several starts per reference set and three named SE rules
Hopkins (EVA005)Runs in CodeSplash: Is there cluster structure? (Hopkins + VAT)
08

Check your understanding

Checkpoint

Check yourself

A row has a silhouette of −0.3. What does that mean?

Show the answer

Answer: a

si<0s_i<0 means bi<aib_i<a_i: the nearest other cluster fits the row better. Rows like this are worth inspecting.

Check yourself

DBSCAN labels many rows noise, and the silhouette is computed on the clustered rows only. What must you report?

Show the answer

Answer: b

How noise is handled changes the score. Report it beside the index, or the comparison flatters methods that leave rows out.

Check yourself

What does a higher Calinski–Harabasz index mean?

Show the answer

Answer: b

CH is a variance ratio. It compares partitions on the same data; it carries no p-value.

Check yourself

Why is Calinski–Harabasz a poor judge of DBSCAN on curved clusters?

Show the answer

Answer: a

Curved or nested groups have centroids close together, which CH reads as poor separation.

Check yourself

Which Davies–Bouldin value is better?

Show the answer

Answer: a

DB averages each cluster's worst spread-to-separation ratio, so smaller means better separated.

Check yourself

What can distort Davies–Bouldin comparisons?

Show the answer

Answer: b

Inspect which pair of clusters produces each maximum, and look at cluster sizes alongside the index.

Check yourself

What does the gap statistic compare the data with?

Show the answer

Answer: b

The gap is how much tighter the real clusters are than clusters forced onto structureless reference data.

Check yourself

Two tools compute the gap statistic on the same data and recommend different kk. What's the likeliest reason?

Show the answer

Answer: a

First-SE, global-SE and Tibshirani's rule can pick different kk from the same curve. Name the rule and the reference box.

Check yourself

A Hopkins statistic near 0.5 suggests what?

Show the answer

Answer: b

Under uniform scatter, distances from random points and from data rows are alike, so HH sits near 0.5.

Check yourself

Hopkins is high, but the data are one skewed population. How can that happen?

Show the answer

Answer: a

The reference region matters. Edges, skew, irrelevant columns and duplicates all raise HH without discrete groups.

09

Do it on your own data

In the app

Before clustering, open Is there cluster structure? under Find segments. Then use Choose the number of clusters to compare candidate kk with several criteria at once, and read where they agree.

Concepts in this lesson