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.
What runs in CodeSplash
- EVA001Silhouette coefficient Runs in CodeSplash
- EVA002Calinski–Harabasz index Runs in CodeSplash
- EVA003Davies–Bouldin index Runs in CodeSplash
- EVA004Gap statistic Runs in CodeSplash
- EVA005Hopkins cluster-tendency statistic Runs in CodeSplash
- Choose the number of clusters Verified in Python and R
- Is there cluster structure? (Hopkins + VAT) Verified in Python and R
- k-means clustering Verified in Python and R
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
Scoring without labels
ReadWith 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 = 3 with = 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.
Silhouette
ReadFor row , let be the mean distance to its own cluster and 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 , between −1 and 1; the index is the mean .
On the reference's tiny, well-separated example 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.
Calinski–Harabasz and Davies–Bouldin
ReadCalinski–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,
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, . 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.
Two rings
PredictPredict 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?
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.
The gap statistic
ReadThe 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 with what the same algorithm gets on reference data with no clusters: . Reference sets are drawn uniformly in the data's bounding box, or in a box aligned with its principal axes.
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
View data
| Center | Cluster | Row | PC1 (62%) | PC2 (25%) |
|---|---|---|---|---|
| false | 4 | Alabama | 0.9856 | −1.133 |
| false | 4 | Alaska | 1.950 | −1.073 |
| false | 3 | Arizona | 1.763 | 0.7460 |
| false | 4 | Arkansas | −0.1414 | −1.120 |
| false | 3 | California | 2.524 | 1.543 |
| false | 3 | Colorado | 1.515 | 0.9876 |
| false | 1 | Connecticut | −1.359 | 1.089 |
| false | 1 | Delaware | 0.0477 | 0.3254 |
| false | 3 | Florida | 3.013 | −0.0392 |
| false | 4 | Georgia | 1.639 | −1.279 |
| false | 1 | Hawaii | −0.9127 | 1.570 |
| false | 2 | Idaho | −1.640 | −0.2110 |
| false | 3 | Illinois | 1.379 | 0.6818 |
| false | 1 | Indiana | −0.5055 | 0.1516 |
| false | 2 | Iowa | −2.254 | 0.1041 |
| false | 1 | Kansas | −0.7969 | 0.2702 |
| false | 2 | Kentucky | −0.7509 | −0.9584 |
| false | 4 | Louisiana | 1.565 | −0.8711 |
| false | 2 | Maine | −2.397 | −0.3764 |
| false | 3 | Maryland | 1.763 | −0.4277 |
| false | 1 | Massachusetts | −0.4862 | 1.474 |
| false | 3 | Michigan | 2.108 | 0.1554 |
| false | 2 | Minnesota | −1.693 | 0.6323 |
| false | 4 | Mississippi | 0.9965 | −2.394 |
| false | 3 | Missouri | 0.6968 | 0.2634 |
| false | 2 | Montana | −1.185 | −0.5369 |
| false | 2 | Nebraska | −1.266 | 0.1940 |
| false | 3 | Nevada | 2.874 | 0.7756 |
| false | 2 | New Hampshire | −2.384 | 0.0181 |
| false | 1 | New Jersey | 0.1816 | 1.450 |
| false | 3 | New Mexico | 1.980 | −0.1428 |
| false | 3 | New York | 1.683 | 0.8232 |
| false | 4 | North Carolina | 1.123 | −2.228 |
| false | 2 | North Dakota | −2.992 | −0.5991 |
| false | 1 | Ohio | −0.2260 | 0.7422 |
| false | 1 | Oklahoma | −0.3118 | 0.2879 |
| false | 1 | Oregon | 0.0591 | 0.5414 |
| false | 1 | Pennsylvania | −0.8884 | 0.5711 |
| false | 1 | Rhode Island | −0.8638 | 1.492 |
| false | 4 | South Carolina | 1.321 | −1.933 |
| false | 2 | South Dakota | −1.988 | −0.8233 |
| false | 4 | Tennessee | 0.9997 | −0.8603 |
| false | 3 | Texas | 1.355 | 0.4125 |
| false | 1 | Utah | −0.5506 | 1.472 |
| false | 2 | Vermont | −2.801 | −1.402 |
| false | 1 | Virginia | −0.0963 | −0.1997 |
| false | 1 | Washington | −0.2169 | 0.9701 |
| false | 2 | West Virginia | −2.109 | −1.425 |
| false | 2 | Wisconsin | −2.080 | 0.6113 |
| false | 1 | Wyoming | −0.6294 | −0.3210 |
| true | 1 | center 1 | −0.4722 | 0.7429 |
| true | 2 | center 2 | −1.965 | −0.3671 |
| true | 3 | center 3 | 1.888 | 0.4815 |
| true | 4 | center 4 | 1.160 | −1.432 |
Recommended k = 4 by the gap statistic (firstSEmax rule).
View data
| Recommended | Criterion | Clusters (k) | Score |
|---|---|---|---|
| false | Within-cluster SS | 2 | 104.96 |
| false | Within-cluster SS | 3 | 80.116 |
| true | Within-cluster SS | 4 | 58.207 |
| false | Within-cluster SS | 5 | 50.930 |
| false | Within-cluster SS | 6 | 44.204 |
| true | Mean silhouette | 2 | 0.4085 |
| false | Mean silhouette | 3 | 0.3139 |
| false | Mean silhouette | 4 | 0.3344 |
| false | Mean silhouette | 5 | 0.2933 |
| false | Mean silhouette | 6 | 0.2858 |
| false | Gap | 2 | 0.6222 |
| false | Gap | 3 | 0.6713 |
| true | Gap | 4 | 0.8239 |
| false | Gap | 5 | 0.7758 |
| false | Gap | 6 | 0.7806 |
| true | Calinski–Harabasz | 2 | 43.462 |
| false | Calinski–Harabasz | 3 | 35.165 |
| false | Calinski–Harabasz | 4 | 37.352 |
| false | Calinski–Harabasz | 5 | 32.928 |
| false | Calinski–Harabasz | 6 | 31.016 |
| true | Davies–Bouldin | 2 | 0.9697 |
| false | Davies–Bouldin | 3 | 1.043 |
| false | Davies–Bouldin | 4 | 1.036 |
| false | Davies–Bouldin | 5 | 1.118 |
| false | Davies–Bouldin | 6 | 1.171 |
View data
| Cluster | Silhouette width |
|---|---|
| 1 | 0.4967 |
| 1 | 0.4821 |
| 1 | 0.4479 |
| 1 | 0.4399 |
| 1 | 0.4371 |
| 1 | 0.3387 |
| 1 | 0.3353 |
| 1 | 0.3307 |
| 1 | 0.3279 |
| 1 | 0.3154 |
| 1 | 0.3076 |
| 1 | 0.3047 |
| 1 | 0.2799 |
| 1 | 0.2633 |
| 1 | 0.2272 |
| 1 | 0.1073 |
| 2 | 0.5444 |
| 2 | 0.5443 |
| 2 | 0.5303 |
| 2 | 0.5227 |
| 2 | 0.5044 |
| 2 | 0.4901 |
| 2 | 0.4848 |
| 2 | 0.3969 |
| 2 | 0.2739 |
| 2 | 0.2657 |
| 2 | 0.1416 |
| 2 | 0.0896 |
| 2 | 0.0655 |
| 3 | 0.4670 |
| 3 | 0.4586 |
| 3 | 0.4468 |
| 3 | 0.4268 |
| 3 | 0.4164 |
| 3 | 0.3621 |
| 3 | 0.3499 |
| 3 | 0.3354 |
| 3 | 0.3087 |
| 3 | 0.2965 |
| 3 | 0.1627 |
| 3 | −0.0343 |
| 4 | 0.4805 |
| 4 | 0.4742 |
| 4 | 0.3829 |
| 4 | 0.3824 |
| 4 | 0.2927 |
| 4 | 0.2280 |
| 4 | 0.1903 |
| 4 | 0.0568 |
| 4 | −0.0583 |
Clusters
| Cluster | Size | Share | Murder | Assault | UrbanPop | Rape |
|---|---|---|---|---|---|---|
| 1 | 16 | 32.0% | 5.656 | 138.88 | 73.875 | 18.781 |
| 2 | 13 | 26.0% | 3.600 | 78.538 | 52.077 | 12.177 |
| 3 | 12 | 24.0% | 10.883 | 256.92 | 78.333 | 32.250 |
| 4 | 9 | 18.0% | 13.500 | 245.78 | 53.111 | 23.978 |
Criteria by k
| k | Within-cluster SS | Mean silhouette | Calinski–Harabasz | Davies–Bouldin | Gap | Gap SE |
|---|---|---|---|---|---|---|
| 2 | 104.96 | 0.4085 | 43.462 | 0.9697 | 0.6222 | 0.0969 |
| 3 | 80.116 | 0.3139 | 35.165 | 1.043 | 0.6713 | 0.0853 |
| 4 | 58.207 | 0.3344 | 37.352 | 1.036 | 0.8239 | 0.0681 |
| 5 | 50.930 | 0.2933 | 32.928 | 1.118 | 0.7758 | 0.0981 |
| 6 | 44.204 | 0.2858 | 31.016 | 1.171 | 0.7806 | 0.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"
))
))
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
| Cluster | Size | Share | Murder | Assault | UrbanPop | Rape |
|---|---|---|---|---|---|---|
| 1 | 16 | 32.0% | 5.656 | 138.88 | 73.875 | 18.781 |
| 2 | 13 | 26.0% | 3.600 | 78.538 | 52.077 | 12.177 |
| 3 | 12 | 24.0% | 10.883 | 256.92 | 78.333 | 32.250 |
| 4 | 9 | 18.0% | 13.500 | 245.78 | 53.111 | 23.978 |
Criteria by k
| k | Within-cluster SS | Mean silhouette | Calinski–Harabasz | Davies–Bouldin | Gap | Gap SE |
|---|---|---|---|---|---|---|
| 2 | 104.96 | 0.4085 | 43.462 | 0.9697 | 0.6222 | 0.0969 |
| 3 | 80.116 | 0.3139 | 35.165 | 1.043 | 0.6713 | 0.0853 |
| 4 | 58.207 | 0.3344 | 37.352 | 1.036 | 0.8239 | 0.0681 |
| 5 | 50.930 | 0.2933 | 32.928 | 1.118 | 0.7758 | 0.0981 |
| 6 | 44.204 | 0.2858 | 31.016 | 1.171 | 0.7806 | 0.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 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.
Hopkins: is there anything to cluster?
ReadThe 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 random points in the data's region to their nearest data rows () with distances from sampled rows to their nearest other rows (): . Near 0.5 means no tendency; near 1 means rows clump.
Hopkins statistic 0.99 (p = 5.62e-25): the rows look clearly clumped.
- Hopkins H
- 0.9937
- p (vs. random scatter)
- < .001
Hopkins draws
| Draw | H |
|---|---|
| 1 | 0.9928 |
| 2 | 0.9968 |
| 3 | 0.9988 |
| 4 | 0.9982 |
| 5 | 0.9942 |
| 6 | 0.9978 |
| 7 | 0.9986 |
| 8 | 0.9630 |
| 9 | 0.9984 |
| 10 | 0.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
))
Hopkins statistic 0.99 (p = 5.62e-25): the rows look clearly clumped.
- Hopkins H
- 0.9937
- p (vs. random scatter)
- < .001
Hopkins draws
| Draw | H |
|---|---|
| 1 | 0.9928 |
| 2 | 0.9968 |
| 3 | 0.9988 |
| 4 | 0.9982 |
| 5 | 0.9942 |
| 6 | 0.9978 |
| 7 | 0.9986 |
| 8 | 0.9630 |
| 9 | 0.9984 |
| 10 | 0.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 up. State the convention and repeat the sampling.
Where each idea stands in CodeSplash
Read| Entry | In 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) |
Check your understanding
CheckpointCheck yourself
A row has a silhouette of −0.3. What does that mean?
Show the answer
Answer: a
means : 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 . What's the likeliest reason?
Show the answer
Answer: a
First-SE, global-SE and Tibshirani's rule can pick different 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 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 without discrete groups.
Do it on your own data
In the appBefore clustering, open Is there cluster structure? under Find segments. Then use Choose the number of clusters to compare candidate with several criteria at once, and read where they agree.
Concepts in this lesson