Divisive trees, BIRCH, k-center and steadier ways to choose k
Build a tree top-down with DIANA or compress large data with BIRCH, pick representatives that leave no row far away with k-center, and choose k by stability (prediction strength) or ICL.
What runs in CodeSplash
- Hierarchical clustering Verified in Python and R
- k-center (farthest-first) Verified in Python and R
- Choose the number of clusters Verified in Python and R
You will be able to
- Read a divisive tree and its divisive coefficient
- Explain what BIRCH's subclusters are and why they let Ward run on large data
- Say what k-center minimizes and when that beats k-means
- Use prediction strength and ICL as checks on the number of clusters
Split instead of merge
ReadAgglomerative clustering starts from single rows and merges. DIANADivisive analysis (DIANA)Builds the tree top-down: split the widest cluster by peeling off the rows least like the rest, until every row stands alone. goes the other way: start with every row in one cluster, then split the widest cluster by peeling off the rows least like the rest.
Merging decides the top of the tree last, after many small choices. Splitting decides it first, which is why divisive trees are often better at the few big splits people actually read.
View data
| merge left | merge right | height (Ward) | state |
|---|---|---|---|
| −9 | −11 | 0.1947 | Alabama |
| −1 | −4 | 0.2215 | Alaska |
| −3 | −15 | 0.2461 | Arizona |
| −6 | −20 | 0.3183 | Arkansas |
| −13 | −19 | 0.3957 | California |
| −10 | −21 | 0.4048 | Colorado |
| −2 | 3 | 0.4343 | Connecticut |
| −17 | −18 | 0.4533 | Delaware |
| −5 | −16 | 0.4978 | Florida |
| −24 | 4 | 0.6506 | Georgia |
| −8 | −12 | 0.6567 | Hawaii |
| −22 | 6 | 0.6974 | Idaho |
| −14 | 5 | 0.7119 | Illinois |
| 1 | 7 | 0.7506 | Indiana |
| −7 | 9 | 0.8691 | Iowa |
| −23 | 12 | 1.065 | Kansas |
| 11 | 14 | 1.559 | Kentucky |
| 13 | 15 | 1.665 | Louisiana |
| 8 | 10 | 1.879 | Maine |
| 17 | 19 | 2.338 | Maryland |
| 2 | 18 | 2.750 | Massachusetts |
| 16 | 21 | 4.061 | Michigan |
| 20 | 22 | 6.729 | Minnesota |
| — | — | — | Mississippi |
On the arrests data the divisive tree has a divisive coefficientDivisive coefficientAverage of 1 − (diameter of the last cluster holding a row ÷ diameter of all rows); near 1 means strong clustering structure. of 0.851. Values near 1 mean clusters are tight compared with the whole data, but the coefficient grows with the number of rows, so compare it only between data sets of similar size.
Compress first with BIRCH
ReflectWard's method keeps every pairwise distance, so it stops at about 10,000 rows. BIRCHBIRCHOne pass over the rows builds a tree of tight subclusters (count, sum, sum of squares); clustering then runs on their centers. reads the rows once and summarizes them into small, tight subclusters (each a count, a sum and a sum of squares). Ward then clusters the subcluster centers, and every row takes the cluster of its nearest center.
On iris, a small radius turns 150 rows into 37 subclusters. The dendrogram's leaves are those subclusters, not rows.
Leave no row far away: k-center
PredictPredict first
You must place 3 depots so the farthest customer is as close as possible. Which method targets that directly?
Reveal
k-center. It minimizes the covering radiusCovering radiusThe largest distance from any row to its nearest center; farthest-first keeps it within twice the best possible., the largest distance from any row to its nearest center. On iris with 3 centers, every row is within 2.57 of a center, and 95% are within 2.43.
k-centerk-center clusteringChoose k representative rows so the farthest any row is from its nearest one (the covering radius) is as small as possible. uses farthest-first traversal: start at a random row, then keep adding the row farthest from the centers so far. The result is never more than twice the best possible radius.
Coverage has a price
Reflectk-center with k = 3 on euclidean dissimilarities: every row is within 2.57 of a center (95% within 2.43; mean 1.46).
- Clusters
- 3
- Mean silhouette
- 0.4511
Plots
View data
| Center | Cluster | PC1 (73%) | PC2 (23%) |
|---|---|---|---|
| false | 2 | −2.265 | 0.4800 |
| false | 3 | −2.081 | −0.6741 |
| false | 3 | −2.364 | −0.3419 |
| false | 3 | −2.299 | −0.5974 |
| false | 2 | −2.390 | 0.6468 |
| false | 2 | −2.076 | 1.489 |
| false | 3 | −2.444 | 0.0476 |
| false | 2 | −2.233 | 0.2231 |
| false | 3 | −2.335 | −1.115 |
| false | 3 | −2.184 | −0.4690 |
| false | 2 | −2.166 | 1.044 |
| false | 2 | −2.326 | 0.1331 |
| false | 3 | −2.218 | −0.7287 |
| false | 3 | −2.633 | −0.9615 |
| false | 2 | −2.199 | 1.860 |
| false | 2 | −2.262 | 2.686 |
| false | 2 | −2.208 | 1.484 |
| false | 2 | −2.190 | 0.4888 |
| false | 2 | −1.899 | 1.405 |
| false | 2 | −2.343 | 1.128 |
| false | 2 | −1.914 | 0.4089 |
| false | 2 | −2.207 | 0.9241 |
| false | 2 | −2.774 | 0.4583 |
| false | 3 | −1.819 | 0.0856 |
| false | 2 | −2.227 | 0.1373 |
| false | 3 | −1.952 | −0.6256 |
| false | 2 | −2.051 | 0.2422 |
| false | 2 | −2.169 | 0.5271 |
| false | 2 | −2.140 | 0.3132 |
| false | 3 | −2.265 | −0.3377 |
| false | 3 | −2.140 | −0.5045 |
| false | 2 | −1.832 | 0.4237 |
| false | 2 | −2.615 | 1.794 |
| false | 2 | −2.446 | 2.151 |
| false | 3 | −2.110 | −0.4602 |
| false | 3 | −2.208 | −0.2061 |
| false | 2 | −2.045 | 0.6616 |
| false | 2 | −2.527 | 0.5923 |
| false | 3 | −2.430 | −0.9042 |
| false | 2 | −2.170 | 0.2689 |
| false | 2 | −2.286 | 0.4417 |
| false | 3 | −1.858 | −2.337 |
| false | 3 | −2.554 | −0.4791 |
| false | 2 | −1.964 | 0.4723 |
| false | 2 | −2.137 | 1.142 |
| false | 3 | −2.070 | −0.7111 |
| false | 2 | −2.385 | 1.120 |
| false | 3 | −2.394 | −0.3862 |
| false | 2 | −2.229 | 0.9980 |
| false | 3 | −2.204 | 0.0092 |
| false | 1 | 1.102 | 0.8630 |
| false | 1 | 0.7313 | 0.5946 |
| false | 1 | 1.241 | 0.6163 |
| false | 3 | 0.4075 | −1.754 |
| false | 1 | 1.075 | −0.2084 |
| false | 1 | 0.3887 | −0.5933 |
| false | 1 | 0.7465 | 0.7730 |
| false | 3 | −0.4873 | −1.852 |
| false | 1 | 0.9279 | 0.0322 |
| false | 1 | 0.0114 | −1.034 |
First 60 of 153 rows.
View data
| Cluster | Silhouette width |
|---|---|
| 1 | 0.6630 |
| 1 | 0.6628 |
| 1 | 0.6570 |
| 1 | 0.6530 |
| 1 | 0.6506 |
| 1 | 0.6487 |
| 1 | 0.6476 |
| 1 | 0.6464 |
| 1 | 0.6443 |
| 1 | 0.6424 |
| 1 | 0.6392 |
| 1 | 0.6342 |
| 1 | 0.6329 |
| 1 | 0.6312 |
| 1 | 0.6306 |
| 1 | 0.6267 |
| 1 | 0.6247 |
| 1 | 0.6230 |
| 1 | 0.6220 |
| 1 | 0.6214 |
| 1 | 0.6180 |
| 1 | 0.6162 |
| 1 | 0.6150 |
| 1 | 0.6080 |
| 1 | 0.6062 |
| 1 | 0.6019 |
| 1 | 0.6019 |
| 1 | 0.6019 |
| 1 | 0.6015 |
| 1 | 0.6004 |
| 1 | 0.5973 |
| 1 | 0.5923 |
| 1 | 0.5912 |
| 1 | 0.5884 |
| 1 | 0.5878 |
| 1 | 0.5777 |
| 1 | 0.5766 |
| 1 | 0.5725 |
| 1 | 0.5713 |
| 1 | 0.5713 |
| 1 | 0.5708 |
| 1 | 0.5640 |
| 1 | 0.5638 |
| 1 | 0.5637 |
| 1 | 0.5611 |
| 1 | 0.5538 |
| 1 | 0.5525 |
| 1 | 0.5512 |
| 1 | 0.5512 |
| 1 | 0.5509 |
| 1 | 0.5508 |
| 1 | 0.5475 |
| 1 | 0.5420 |
| 1 | 0.5404 |
| 1 | 0.5397 |
| 1 | 0.5394 |
| 1 | 0.5388 |
| 1 | 0.5318 |
| 1 | 0.5280 |
| 1 | 0.5263 |
First 60 of 150 rows.
Clusters
| Cluster | Size | Share | sepal_length | sepal_width | petal_length | petal_width |
|---|---|---|---|---|---|---|
| 1 | 93 | 62.0% | 6.341 | 2.913 | 5.011 | 1.722 |
| 2 | 30 | 20.0% | 5.197 | 3.660 | 1.493 | 0.2667 |
| 3 | 27 | 18.0% | 4.848 | 2.885 | 1.959 | 0.4370 |
The exact R script · R R version 4.5.1 (2025-06-13)
# k-center (farthest-first)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.kcenter 1.0.0 · spec 07ca7406a7a9baff
# 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.kcenter/iris_k3/out-r")
values <- list(n_used = length(rows))
centers <- NULL
center_ids <- NULL
D <- NULL
extra <- list()
tables <- list()
charts <- list()
summary <- NULL
# %% Clustering
K <- 3
if (K >= length(rows)) cs_error("CS_E_TOO_FEW_ROWS", what = sprintf("k-center with k = %d", K), min = K + 1, n = length(rows))
DISTANCE <- "auto"
if (DISTANCE == "auto") DISTANCE <- if (any(unlist(KINDS[FEATURES]) != "numeric")) "gower" else "euclidean"
cols <- if (DISTANCE == "gower") cs_cp_gower_ranges(frame, FEATURES, KINDS) else NULL
# Farthest-first traversal (Gonzalez 1985): each new center is the row farthest from the centers so far, so every
# row lies within the covering radius of a center (at most twice the best possible). Twin: kcenter.
f <- cs_cp_kcenter(X, cols, DISTANCE, K, cs_rng(SEED), 10)
raw <- f$labels
own <- f$own
centers <- X[f$centers + 1L, , drop = FALSE]
values$radius <- f$radius
values$p90_distance <- unname(stats::quantile(own, 0.9))
values$p95_distance <- unname(stats::quantile(own, 0.95))
values$mean_distance <- mean(own)
canon <- cs_ml_canonical(raw)
for (m in f$centers) values[[sprintf("center_row[%d]", canon[m + 1L])]] <- rows[m + 1L]
extra$distance <- own
if (DISTANCE != "euclidean") {
if (length(rows) <= 5000) {
D <- if (DISTANCE == "gower") cs_ml_gower(frame, FEATURES, KINDS) else as.matrix(stats::dist(X, method = "manhattan"))
dimnames(D) <- NULL
} else {
warnings <- c(warnings, "Above 5,000 rows the silhouette uses Euclidean distance on the scaled design, not the chosen dissimilarity.")
}
}
GROUP <- NULL
if (!is.null(GROUP)) {
gdf <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_iris.parquet", col_select = GROUP))
grp <- as.character(gdf[[GROUP]])[rows + 1L]
grp[is.na(grp)] <- "(missing)"
cover <- lapply(sort(unique(grp), method = "radix"), function(g) {
d <- own[grp == g]
list(group = g, n = length(d), mean = mean(d), p95 = unname(stats::quantile(d, 0.95)), max = max(d))
})
tables[[length(tables) + 1L]] <- list(
key = "coverage", title = sprintf("Distance to the nearest center by %s", GROUP),
columns = list(list(key = "group", label = GROUP, type = "string"), list(key = "n", label = "Rows", type = "integer"),
list(key = "mean", label = "Mean distance", type = "number"), list(key = "p95", label = "95th percentile", type = "number"),
list(key = "max", label = "Largest", type = "number")),
rows = cover
)
}
summary <- sprintf("k-center with k = %d on %s dissimilarities: every row is within %s of a center (95%% within %s; mean %s).",
K, DISTANCE, formatC(f$radius, digits = 3, format = "g"), formatC(values$p95_distance, digits = 3, format = "g"),
formatC(values$mean_distance, digits = 3, format = "g"))
# %% 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 = "k-center (farthest-first)",
engine = cs_engine_info("stats", "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(
k = 3,
distance = "auto",
n_init = 10,
scale = "standard",
missing = "drop"
))
))
k-center with k = 3 on euclidean dissimilarities: every row is within 2.57 of a center (95% within 2.43; mean 1.46).
- Clusters
- 3
- Mean silhouette
- 0.4511
To keep this page light, the plots are shown once, under the R tab.
Clusters
| Cluster | Size | Share | sepal_length | sepal_width | petal_length | petal_width |
|---|---|---|---|---|---|---|
| 1 | 93 | 62.0% | 6.341 | 2.913 | 5.011 | 1.722 |
| 2 | 30 | 20.0% | 5.197 | 3.660 | 1.493 | 0.2667 |
| 3 | 27 | 18.0% | 4.848 | 2.885 | 1.959 | 0.4370 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# k-center (farthest-first)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.kcenter 1.0.0 · spec 07ca7406a7a9baff
# 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
from scipy.spatial.distance import cdist
from codesplash.ml import cluster_partition as cpart
# %% 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.kcenter/iris_k3/out-python")
values = {"n_used": len(rows)}
centers = None
center_ids = None
D = None
extra = {}
tables = []
charts = []
summary = None
# %% Clustering
K = 3
if K >= len(rows):
cs.cs_error("CS_E_TOO_FEW_ROWS", what=f"k-center with k = {K}", min=K + 1, n=len(rows))
DISTANCE = "auto"
if DISTANCE == "auto":
DISTANCE = "gower" if any(KINDS[f] != "numeric" for f in FEATURES) else "euclidean"
cols = cpart.gower_ranges(frame, FEATURES, KINDS) if DISTANCE == "gower" else None
# Farthest-first traversal (Gonzalez 1985): each new center is the row farthest from the centers so far, so every
# row lies within the covering radius of a center (at most twice the best possible). Twin: cs_cp_kcenter.
raw, center_rows, radius, own = cpart.kcenter(X, cols, DISTANCE, K, Rng(SEED), 10)
centers = X[center_rows]
values["radius"] = float(radius)
values["p90_distance"] = float(np.quantile(own, 0.9))
values["p95_distance"] = float(np.quantile(own, 0.95))
values["mean_distance"] = float(np.mean(own))
canon = csc.canonical(raw)
for m in center_rows:
values[f"center_row[{int(canon[m])}]"] = int(rows[m])
extra["distance"] = own
if DISTANCE != "euclidean":
if len(rows) <= 5000:
D = csc.gower(frame, FEATURES, KINDS) if DISTANCE == "gower" else cdist(X, X, metric="cityblock")
else:
warnings.append("Above 5,000 rows the silhouette uses Euclidean distance on the scaled design, not the chosen dissimilarity.")
GROUP = None
if GROUP:
grp = pd.read_parquet("tests/parity/fixtures/ml_iris.parquet", columns=[GROUP])[GROUP].astype("object").to_numpy()[rows]
grp = np.array(["(missing)" if pd.isna(g) else str(g) for g in grp], dtype=object)
cover = []
for g in sorted(set(grp.tolist())):
d = own[grp == g]
cover.append({"group": g, "n": int(len(d)), "mean": float(np.mean(d)), "p95": float(np.quantile(d, 0.95)), "max": float(np.max(d))})
tables.append({
"key": "coverage", "title": f"Distance to the nearest center by {GROUP}",
"columns": [
{"key": "group", "label": GROUP, "type": "string"},
{"key": "n", "label": "Rows", "type": "integer"},
{"key": "mean", "label": "Mean distance", "type": "number"},
{"key": "p95", "label": "95th percentile", "type": "number"},
{"key": "max", "label": "Largest", "type": "number"},
],
"rows": cover,
})
summary = (
f"k-center with k = {K} on {DISTANCE} dissimilarities: every row is within {radius:.3g} of a center "
f"(95% within {values['p95_distance']:.3g}; mean {values['mean_distance']:.3g})."
)
# %% 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": "k-center (farthest-first)",
"engine": cs.engine_info("numpy", "scipy", "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": {
"k": 3,
"distance": "auto",
"n_init": 10,
"scale": "standard",
"missing": "drop",
}},
})
Because the worst-served row drives every choice, outliers tend to become centers. That suits coverage, not typical groups: k-means and PAM give a lower average distance than k-center's 1.46.
Set Check coverage by to a group column to see whether some groups are served worse. On the penguins, the coverage table splits the distances by island.
Steadier ways to choose k
ReadPrediction strengthPrediction strengthShare of pairs in each test cluster that centers fitted on the other half also keep together; the weakest cluster counts. splits the rows into random halves, clusters each half, and asks how often the centers from one half keep each cluster of the other half together. Stable clusters score near 1. On iris the recommended is 2, the largest whose mean stays above the cutoff.
View data
| number of clusters k | score | criterion | recommended |
|---|---|---|---|
| 2 | 1009.44 | within-cluster SS | false |
| 2 | 0.4790 | silhouette | false |
| 2 | 1.406 | gap statistic | false |
| 3 | 604.67 | within-cluster SS | false |
| 3 | 0.5390 | silhouette | false |
| 3 | 1.667 | gap statistic | false |
| 4 | 266.55 | within-cluster SS | true |
| 4 | 0.5690 | silhouette | true |
| 4 | 1.883 | gap statistic | true |
| 5 | 212.94 | within-cluster SS | false |
| 5 | 0.5610 | silhouette | false |
| 5 | 1.900 | gap statistic | false |
| 6 | 172.92 | within-cluster SS | false |
| 6 | 0.4890 | silhouette | false |
| 6 | 1.880 | gap statistic | false |
| 7 | 158.52 | within-cluster SS | false |
| 7 | 0.4350 | silhouette | false |
| 7 | 1.844 | gap statistic | false |
| 8 | 143.15 | within-cluster SS | false |
| 8 | 0.3800 | silhouette | false |
| 8 | 1.835 | gap statistic | false |
| 9 | 125.91 | within-cluster SS | false |
| 9 | 0.3080 | silhouette | false |
| 9 | 1.793 | gap statistic | false |
Penalize overlap, name the rule
ReflectICLIntegrated completed likelihoodBIC plus a penalty for fuzzy assignments; lower is better, and it prefers components that form well-separated clusters. is BIC plus a penalty for rows split between mixture components, so it prefers well-separated clusters. On the penguins ICL recommends 3 components and BIC recommends 3. When the two agree, the components are well separated; when ICL picks fewer, some components overlap.
The gap statistic now has choices too: a reference box aligned with the principal axes and the SE rules R's clusGap offers. Different rules can pick different on the same curve, so the result names the rule it used.
Check your understanding
CheckpointCheck yourself
What does k-center minimize?
Show the answer
Answer: b
k-center minimizes the worst case. That makes it good for coverage and sensitive to outliers.
Check yourself
Which task suits k-center better than k-means?
Show the answer
Answer: a
When nothing may be left far from a representative, the worst case is the right target. For typical groups, averages (k-means, PAM) describe the bulk better.
Check yourself
In a BIRCH run, what are the leaves of the dendrogram?
Show the answer
Answer: b
BIRCH compresses rows into subclusters first, then clusters their centers. Each row takes the cluster of its nearest subcluster center.
Check yourself
Prediction strength is 0.95 at k = 2, 0.85 at k = 3 and 0.55 at k = 4 with a cutoff of 0.8. Which k does it recommend?
Show the answer
Answer: b
The rule takes the largest k whose clusters stay stable. The 0.8 cutoff is a convention, so look at the whole curve too.
Check yourself
BIC recommends 4 mixture components and ICL recommends 3. What does that suggest?
Show the answer
Answer: b
ICL adds a penalty for rows split between components. When it picks fewer, some components describe one cluster's shape rather than separate groups.
Do it on your own data
In the appUnder Find segments, open Hierarchical clustering and set Direction to divisive, or Compress first to BIRCH for a large table. k-center (farthest-first) sits with the partitioning methods.
Concepts in this lesson