Means, medians, medoids and the farthest row: what a partition minimizes
k-means, k-medians, k-medoids, k-center and trimmed k-means all draw k groups, but each minimizes a different cost. The cost decides which rows matter most, what a center is and how outliers pull.
What runs in CodeSplash
- UCL001K-means Runs in CodeSplash
- UCL003K-medoids / Partitioning Around Medoids (PAM) Runs in CodeSplash
- UCL006K-medians Runs in CodeSplash
- UCL007Metric K-center / farthest-first traversal Runs in CodeSplash
- UCL010Trimmed K-means Runs in CodeSplash
- k-means clustering Verified in Python and R
- k-medoids (PAM) Verified in Python and R
- k-center (farthest-first) Verified in Python and R
You will be able to
- Name the cost each partition method minimizes and what its centers are
- Predict how squared, absolute and worst-case costs react to one far-away row
- Check a partition with the numbers that match its own objective
- Say what trimming can hide and why it is not an outlier test
One picture, five costs
ReadEvery method here puts centers down and gives each row to its nearest one. They differ in the cost they push down:
| Method | Minimizes | A center is |
|---|---|---|
| k-meansk-meansSplits rows into k groups by repeatedly assigning each row to its nearest center and moving each center to its group's mean. | sum of squared distances | a mean |
| k-mediansk-mediansPartitioning with city-block (L1) distance and centers at each cluster's coordinate-wise medians; less pulled by outliers than means. | sum of city-block distances | coordinatewise medians |
| k-medoids (PAM) | sum of dissimilarities to the nearest medoidMedoidThe real row with the smallest total dissimilarity to the other rows of its cluster: a center you can open and read. | a real row |
| 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. | the largest distance to a center, | a real row |
| Trimmed k-meansTrimmed k-meansk-means that leaves the share α of rows farthest from their centers out of the fit, so outliers can't pull the centers. | squared distances over the rows it keeps | a mean |
The cost decides which rows matter most. Choose it for your question before you look at the clusters.
One far row
PredictPredict first
You add one row ten times farther from everything than the rest. Which method is most likely to spend a whole center on it?
Reveal
k-center. Its cost is the single worst distance, so leaving that row far from every center is the worst thing it can do. k-means feels the row through a squared distance and drags a mean toward it. k-medians, which sums absolute distances, moves least.
k-means finds a local best
ReadLloyd's algorithm alternates two steps: give each row to its nearest mean, then move each mean to the middle of its rows. The cost never rises, but it stops at a local optimum, so the app runs several starts and keeps the lowest cost.
k-means with k = 3: between-cluster variation is 77% of the total (within-cluster sum of squares 140).
- Clusters
- 3
- Mean silhouette
- 0.4630
Plots
View data
| Center | Cluster | PC1 (73%) | PC2 (23%) |
|---|---|---|---|
| false | 2 | −2.265 | 0.4800 |
| false | 2 | −2.081 | −0.6741 |
| false | 2 | −2.364 | −0.3419 |
| false | 2 | −2.299 | −0.5974 |
| false | 2 | −2.390 | 0.6468 |
| false | 2 | −2.076 | 1.489 |
| false | 2 | −2.444 | 0.0476 |
| false | 2 | −2.233 | 0.2231 |
| false | 2 | −2.335 | −1.115 |
| false | 2 | −2.184 | −0.4690 |
| false | 2 | −2.166 | 1.044 |
| false | 2 | −2.326 | 0.1331 |
| false | 2 | −2.218 | −0.7287 |
| false | 2 | −2.633 | −0.9615 |
| false | 2 | −2.199 | 1.860 |
| false | 2 | −2.262 | 2.686 |
| false | 2 | −2.208 | 1.484 |
| false | 2 | −2.190 | 0.4888 |
| false | 2 | −1.899 | 1.405 |
| false | 2 | −2.343 | 1.128 |
| false | 2 | −1.914 | 0.4089 |
| false | 2 | −2.207 | 0.9241 |
| false | 2 | −2.774 | 0.4583 |
| false | 2 | −1.819 | 0.0856 |
| false | 2 | −2.227 | 0.1373 |
| false | 2 | −1.952 | −0.6256 |
| false | 2 | −2.051 | 0.2422 |
| false | 2 | −2.169 | 0.5271 |
| false | 2 | −2.140 | 0.3132 |
| false | 2 | −2.265 | −0.3377 |
| false | 2 | −2.140 | −0.5045 |
| false | 2 | −1.832 | 0.4237 |
| false | 2 | −2.615 | 1.794 |
| false | 2 | −2.446 | 2.151 |
| false | 2 | −2.110 | −0.4602 |
| false | 2 | −2.208 | −0.2061 |
| false | 2 | −2.045 | 0.6616 |
| false | 2 | −2.527 | 0.5923 |
| false | 2 | −2.430 | −0.9042 |
| false | 2 | −2.170 | 0.2689 |
| false | 2 | −2.286 | 0.4417 |
| false | 2 | −1.858 | −2.337 |
| false | 2 | −2.554 | −0.4791 |
| false | 2 | −1.964 | 0.4723 |
| false | 2 | −2.137 | 1.142 |
| false | 2 | −2.070 | −0.7111 |
| false | 2 | −2.385 | 1.120 |
| false | 2 | −2.394 | −0.3862 |
| false | 2 | −2.229 | 0.9980 |
| false | 2 | −2.204 | 0.0092 |
| false | 3 | 1.102 | 0.8630 |
| false | 3 | 0.7313 | 0.5946 |
| false | 3 | 1.241 | 0.6163 |
| false | 1 | 0.4075 | −1.754 |
| false | 1 | 1.075 | −0.2084 |
| false | 1 | 0.3887 | −0.5933 |
| false | 3 | 0.7465 | 0.7730 |
| false | 1 | −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.5816 |
| 1 | 0.5796 |
| 1 | 0.5796 |
| 1 | 0.5767 |
| 1 | 0.5766 |
| 1 | 0.5641 |
| 1 | 0.5612 |
| 1 | 0.5510 |
| 1 | 0.5493 |
| 1 | 0.5491 |
| 1 | 0.5444 |
| 1 | 0.5418 |
| 1 | 0.5381 |
| 1 | 0.5381 |
| 1 | 0.4980 |
| 1 | 0.4897 |
| 1 | 0.4721 |
| 1 | 0.4702 |
| 1 | 0.4626 |
| 1 | 0.4373 |
| 1 | 0.4348 |
| 1 | 0.4314 |
| 1 | 0.4308 |
| 1 | 0.4279 |
| 1 | 0.4230 |
| 1 | 0.4183 |
| 1 | 0.4156 |
| 1 | 0.4150 |
| 1 | 0.4131 |
| 1 | 0.4056 |
| 1 | 0.3995 |
| 1 | 0.3960 |
| 1 | 0.3936 |
| 1 | 0.3923 |
| 1 | 0.3884 |
| 1 | 0.3716 |
| 1 | 0.3693 |
| 1 | 0.3693 |
| 1 | 0.3492 |
| 1 | 0.3483 |
| 1 | 0.3480 |
| 1 | 0.3368 |
| 1 | 0.2737 |
| 1 | 0.2558 |
| 1 | 0.2341 |
| 1 | 0.2329 |
| 1 | 0.2278 |
| 1 | 0.2188 |
| 1 | 0.1672 |
| 1 | 0.1309 |
| 1 | 0.1221 |
| 1 | 0.0901 |
| 1 | 0.0612 |
| 1 | 0.0458 |
| 1 | 0.0320 |
| 1 | 0.0129 |
| 2 | 0.7373 |
| 2 | 0.7364 |
| 2 | 0.7343 |
| 2 | 0.7319 |
First 60 of 150 rows.
Clusters
| Cluster | Size | Share | sepal_length | sepal_width | petal_length | petal_width |
|---|---|---|---|---|---|---|
| 1 | 56 | 37.3% | 5.834 | 2.677 | 4.421 | 1.436 |
| 2 | 50 | 33.3% | 5.006 | 3.428 | 1.462 | 0.2460 |
| 3 | 44 | 29.3% | 6.807 | 3.120 | 5.523 | 1.982 |
The exact R script · R R version 4.5.1 (2025-06-13)
# k-means clustering
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.kmeans 1.2.0 · spec 6508dce762541c2c
# 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.kmeans/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-means with k = %d", K), min = K + 1L, n = length(rows))
HOLDOUT <- 0
if (is.null(HOLDOUT)) HOLDOUT <- 0
held <- cs_runif(cs_rng(SEED + 7919), length(rows)) < HOLDOUT # rows left out of the fit (shared stream)
fit_X <- X[!held, , drop = FALSE]
if (K >= nrow(fit_X)) cs_error("CS_E_TOO_FEW_ROWS", what = sprintf("k-means with k = %d (after the hold-out)", K), min = K + 1L, n = nrow(fit_X))
rng <- cs_rng(SEED) # shared stream: identical k-means++ starts in Python and R
best <- NULL
for (start in seq_len(10)) {
init <- cs_ml_kmeanspp(fit_X, K, rng)
km <- stats::kmeans(fit_X, centers = init, algorithm = "Lloyd", iter.max = 300)
if (is.null(best) || km$tot.withinss < best$tot.withinss) best <- km
}
centers <- unname(best$centers)
raw <- integer(length(rows))
raw[!held] <- best$cluster - 1L
if (any(held)) {
d2 <- matrix(0, sum(held), K)
for (j in seq_len(ncol(X))) {
diff <- outer(X[held, j], centers[, j], "-")
d2 <- d2 + diff * diff
}
raw[held] <- max.col(-d2, ties.method = "first") - 1L # nearest center, ties -> lowest
extra$holdout <- held
warnings <- c(warnings, sprintf("%d rows were held out of the fit and assigned to their nearest center; segment profiles test only them.", sum(held)))
}
values$n_holdout <- sum(held)
total_ss <- sum(sweep(fit_X, 2, colMeans(fit_X))^2) # over the fitted rows, like the inertia
values$inertia <- best$tot.withinss
values$between_ratio <- if (total_ss > 0) 1 - best$tot.withinss / total_ss else NaN
extra$distance <- sqrt(pmax(rowSums((X - centers[raw + 1L, , drop = FALSE])^2), 0))
summary <- sprintf("k-means with k = %d: between-cluster variation is %.0f%% of the total (within-cluster sum of squares %s).",
K, 100 * values$between_ratio, formatC(values$inertia, digits = 4, 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-means clustering",
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,
algorithm = "lloyd",
trim = 0,
batch_size = 1024,
passes = 10,
n_init = 10,
max_iter = 300,
holdout = 0,
scale = "standard",
missing = "drop"
))
))
k-means with k = 3: between-cluster variation is 77% of the total (within-cluster sum of squares 140).
- Clusters
- 3
- Mean silhouette
- 0.4630
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 | 56 | 37.3% | 5.834 | 2.677 | 4.421 | 1.436 |
| 2 | 50 | 33.3% | 5.006 | 3.428 | 1.462 | 0.2460 |
| 3 | 44 | 29.3% | 6.807 | 3.120 | 5.523 | 1.982 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# k-means clustering
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.kmeans 1.2.0 · spec 6508dce762541c2c
# 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 sklearn.cluster import KMeans
# %% 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.kmeans/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-means with k = {K}", min=K + 1, n=len(rows))
HOLDOUT = 0 or 0.0
held = Rng(SEED + 7919).uniform(len(rows)) < HOLDOUT # rows left out of the fit (shared stream)
fit_X = X[~held]
if K >= len(fit_X):
cs.cs_error("CS_E_TOO_FEW_ROWS", what=f"k-means with k = {K} (after the hold-out)", min=K + 1, n=len(fit_X))
rng = Rng(SEED) # shared stream: identical k-means++ starts in Python and R
best = None
for start in range(10):
init = csc.kmeanspp(fit_X, K, rng)
# Lloyd iterations until no label changes (tol = 0), like stats::kmeans(algorithm = "Lloyd")
km = KMeans(n_clusters=K, init=init, n_init=1, algorithm="lloyd", tol=0.0, max_iter=300).fit(fit_X)
if best is None or km.inertia_ < best.inertia_:
best = km
centers = best.cluster_centers_
raw = np.empty(len(rows), dtype=np.int64)
raw[~held] = best.labels_.astype(np.int64)
if held.any():
d2 = np.zeros((int(held.sum()), K))
for j in range(X.shape[1]):
diff = X[held, j][:, None] - centers[:, j][None, :]
d2 += diff * diff
raw[held] = np.argmin(d2, axis=1) # nearest center, ties → lowest
extra["holdout"] = held
warnings.append(f"{int(held.sum())} rows were held out of the fit and assigned to their nearest center; segment profiles test only them.")
values["n_holdout"] = int(held.sum())
total_ss = float(np.sum((fit_X - fit_X.mean(axis=0)) ** 2)) # over the fitted rows, like the inertia
values["inertia"] = float(best.inertia_)
values["between_ratio"] = 1.0 - float(best.inertia_) / total_ss if total_ss > 0 else float("nan")
extra["distance"] = np.sqrt(np.maximum(((X - centers[raw]) ** 2).sum(axis=1), 0.0))
summary = (
f"k-means with k = {K}: between-cluster variation is {values['between_ratio']:.0%} of the total "
f"(within-cluster sum of squares {values['inertia']:.4g})."
)
# %% 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-means clustering",
"engine": cs.engine_info("scikit-learn", "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,
"algorithm": "lloyd",
"trim": 0,
"batch_size": 1024,
"passes": 10,
"n_init": 10,
"max_iter": 300,
"holdout": 0,
"scale": "standard",
"missing": "drop",
}},
})
On iris with three clusters the cost (inertia) is 140. Compare costs only across starts with the same : inertia always falls as grows. Squared distances make the method assume compact, similarly spread groups; curved or uneven-density groups get split in odd places.
Medoids: real rows, any distance
ReadPAM picks actual rows as medoids and swaps a medoid for a non-medoid whenever the swap lowers the total dissimilarity. Because it never averages, it works with any dissimilarity: Manhattan, Gower for mixed columns, or a precomputed matrix.
PAM with k = 3 on euclidean dissimilarities: average dissimilarity to the medoid 0.879.
- Clusters
- 3
- Mean silhouette
- 0.4566
Plots
View data
| Center | Cluster | PC1 (73%) | PC2 (23%) |
|---|---|---|---|
| false | 2 | −2.265 | 0.4800 |
| false | 2 | −2.081 | −0.6741 |
| false | 2 | −2.364 | −0.3419 |
| false | 2 | −2.299 | −0.5974 |
| false | 2 | −2.390 | 0.6468 |
| false | 2 | −2.076 | 1.489 |
| false | 2 | −2.444 | 0.0476 |
| false | 2 | −2.233 | 0.2231 |
| false | 2 | −2.335 | −1.115 |
| false | 2 | −2.184 | −0.4690 |
| false | 2 | −2.166 | 1.044 |
| false | 2 | −2.326 | 0.1331 |
| false | 2 | −2.218 | −0.7287 |
| false | 2 | −2.633 | −0.9615 |
| false | 2 | −2.199 | 1.860 |
| false | 2 | −2.262 | 2.686 |
| false | 2 | −2.208 | 1.484 |
| false | 2 | −2.190 | 0.4888 |
| false | 2 | −1.899 | 1.405 |
| false | 2 | −2.343 | 1.128 |
| false | 2 | −1.914 | 0.4089 |
| false | 2 | −2.207 | 0.9241 |
| false | 2 | −2.774 | 0.4583 |
| false | 2 | −1.819 | 0.0856 |
| false | 2 | −2.227 | 0.1373 |
| false | 2 | −1.952 | −0.6256 |
| false | 2 | −2.051 | 0.2422 |
| false | 2 | −2.169 | 0.5271 |
| false | 2 | −2.140 | 0.3132 |
| false | 2 | −2.265 | −0.3377 |
| false | 2 | −2.140 | −0.5045 |
| false | 2 | −1.832 | 0.4237 |
| false | 2 | −2.615 | 1.794 |
| false | 2 | −2.446 | 2.151 |
| false | 2 | −2.110 | −0.4602 |
| false | 2 | −2.208 | −0.2061 |
| false | 2 | −2.045 | 0.6616 |
| false | 2 | −2.527 | 0.5923 |
| false | 2 | −2.430 | −0.9042 |
| false | 2 | −2.170 | 0.2689 |
| false | 2 | −2.286 | 0.4417 |
| false | 2 | −1.858 | −2.337 |
| false | 2 | −2.554 | −0.4791 |
| false | 2 | −1.964 | 0.4723 |
| false | 2 | −2.137 | 1.142 |
| false | 2 | −2.070 | −0.7111 |
| false | 2 | −2.385 | 1.120 |
| false | 2 | −2.394 | −0.3862 |
| false | 2 | −2.229 | 0.9980 |
| false | 2 | −2.204 | 0.0092 |
| false | 3 | 1.102 | 0.8630 |
| false | 3 | 0.7313 | 0.5946 |
| false | 3 | 1.241 | 0.6163 |
| false | 1 | 0.4075 | −1.754 |
| false | 1 | 1.075 | −0.2084 |
| false | 1 | 0.3887 | −0.5933 |
| false | 3 | 0.7465 | 0.7730 |
| false | 1 | −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.5827 |
| 1 | 0.5787 |
| 1 | 0.5772 |
| 1 | 0.5746 |
| 1 | 0.5745 |
| 1 | 0.5681 |
| 1 | 0.5586 |
| 1 | 0.5568 |
| 1 | 0.5523 |
| 1 | 0.5495 |
| 1 | 0.5480 |
| 1 | 0.5452 |
| 1 | 0.5431 |
| 1 | 0.5311 |
| 1 | 0.5149 |
| 1 | 0.5074 |
| 1 | 0.4678 |
| 1 | 0.4630 |
| 1 | 0.4629 |
| 1 | 0.4570 |
| 1 | 0.4540 |
| 1 | 0.4364 |
| 1 | 0.4277 |
| 1 | 0.4256 |
| 1 | 0.4212 |
| 1 | 0.4204 |
| 1 | 0.4114 |
| 1 | 0.4038 |
| 1 | 0.3992 |
| 1 | 0.3986 |
| 1 | 0.3970 |
| 1 | 0.3907 |
| 1 | 0.3860 |
| 1 | 0.3756 |
| 1 | 0.3643 |
| 1 | 0.3620 |
| 1 | 0.3574 |
| 1 | 0.3543 |
| 1 | 0.3395 |
| 1 | 0.3392 |
| 1 | 0.3392 |
| 1 | 0.3209 |
| 1 | 0.2825 |
| 1 | 0.2435 |
| 1 | 0.2117 |
| 1 | 0.2098 |
| 1 | 0.1877 |
| 1 | 0.1756 |
| 1 | 0.1464 |
| 1 | 0.1460 |
| 1 | 0.1405 |
| 1 | 0.0627 |
| 1 | 0.0477 |
| 1 | 0.0073 |
| 1 | −0.0679 |
| 2 | 0.7323 |
| 2 | 0.7315 |
| 2 | 0.7293 |
| 2 | 0.7268 |
| 2 | 0.7264 |
First 60 of 150 rows.
Clusters
| Cluster | Size | Share | sepal_length | sepal_width | petal_length | petal_width |
|---|---|---|---|---|---|---|
| 1 | 55 | 36.7% | 5.813 | 2.700 | 4.376 | 1.413 |
| 2 | 50 | 33.3% | 5.006 | 3.428 | 1.462 | 0.2460 |
| 3 | 45 | 30.0% | 6.811 | 3.082 | 5.553 | 1.998 |
The exact R script · R R version 4.5.1 (2025-06-13)
# k-medoids (PAM)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.pam 1.1.0 · spec 895c8174e064ca7b
# 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.pam/iris_euclidean/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("PAM with k = %d", K), min = K + 1L, n = length(rows))
if (length(rows) > 5000) stop("PAM keeps a full dissimilarity matrix; use it on at most 5,000 rows (or k-means).")
DISTANCE <- "auto"
if (DISTANCE == "auto") DISTANCE <- if (any(unlist(KINDS[FEATURES]) != "numeric")) "gower" else "euclidean"
D <- if (DISTANCE == "gower") {
cs_ml_gower(frame, FEATURES, KINDS) # = cluster::daisy(metric = "gower")
} else {
as.matrix(stats::dist(X, method = if (DISTANCE == "manhattan") "manhattan" else "euclidean"))
}
dimnames(D) <- NULL
# Original PAM: BUILD then best-improvement SWAP (pamonce = 0).
res <- cluster::pam(stats::as.dist(D), K, diss = TRUE, pamonce = 0, do.swap = TRUE)
raw <- res$clustering - 1L
medoids <- res$id.med - 1L
centers <- X[medoids + 1L, , drop = FALSE]
own <- D[cbind(seq_along(raw), medoids[raw + 1L] + 1L)]
values$cost <- sum(own) / length(rows)
canon <- cs_ml_canonical(raw)
for (m in medoids) values[[sprintf("medoid_row[%d]", canon[m + 1L])]] <- rows[m + 1L]
extra$distance <- own
summary <- sprintf("PAM with k = %d on %s dissimilarities: average dissimilarity to the medoid %.3f.", K, DISTANCE, values$cost)
# %% 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-medoids (PAM)",
engine = cs_engine_info("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(
k = 3,
algorithm = "pam",
samples = 5,
sample_size = 0,
numlocal = 2,
maxneighbor = 0,
distance = "auto",
max_iter = 100,
scale = "standard",
missing = "drop"
))
))
PAM with k = 3 on euclidean dissimilarities: average dissimilarity to the medoid 0.879.
- Clusters
- 3
- Mean silhouette
- 0.4566
To keep this page light, the plots are shown once, under the R tab.
Clusters
| Cluster | Size | Share | sepal_length | sepal_width | petal_length | petal_width |
|---|---|---|---|---|---|---|
| 1 | 55 | 36.7% | 5.813 | 2.700 | 4.376 | 1.413 |
| 2 | 50 | 33.3% | 5.006 | 3.428 | 1.462 | 0.2460 |
| 3 | 45 | 30.0% | 6.811 | 3.082 | 5.553 | 1.998 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# k-medoids (PAM)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.pam 1.1.0 · spec 895c8174e064ca7b
# Dataset: ml_iris (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import cluster as csc
from codesplash.stats.rng import Rng
import kmedoids
from scipy.spatial.distance import cdist
# %% Data
FEATURES = ["sepal_length", "sepal_width", "petal_length", "petal_width"]
LABEL = "species" # known groups (external validation only)
ROW_ID = None # row labels for charts
SEED = 42
KINDS = {
"sepal_length": "numeric",
"sepal_width": "numeric",
"petal_length": "numeric",
"petal_width": "numeric",
}
LEVELS = {
}
df = pd.read_parquet("tests/parity/fixtures/ml_iris.parquet", columns=list(dict.fromkeys(FEATURES + [c for c in (LABEL, ROW_ID) if c])))
n_input = len(df)
X, rows, names, frame = csc.prepare(df, FEATURES, KINDS, LEVELS, missing="drop", scale="standard")
warnings = []
if len(rows) < n_input:
warnings.append(f"{n_input - len(rows)} of {n_input} rows were left out because a feature was missing.")
if len(rows) < 3:
raise ValueError("Clustering needs at least three rows with every feature present.")
truth = frame[LABEL].astype("object").to_numpy() if LABEL else None
out = csml.out_dir("target/academy-parity/run-8142/discover.pam/iris_euclidean/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"PAM with k = {K}", min=K + 1, n=len(rows))
if len(rows) > 5000:
raise ValueError("PAM keeps a full dissimilarity matrix; use it on at most 5,000 rows (or k-means).")
DISTANCE = "auto"
if DISTANCE == "auto":
DISTANCE = "gower" if any(KINDS[f] != "numeric" for f in FEATURES) else "euclidean"
if DISTANCE == "gower":
D = csc.gower(frame, FEATURES, KINDS) # = cluster::daisy(metric = "gower")
else:
D = cdist(X, X, metric="cityblock" if DISTANCE == "manhattan" else "euclidean")
# Original PAM: BUILD initialization, then best-improvement SWAP (= cluster::pam(pamonce = 0)).
res = kmedoids.pam(D, K, max_iter=100, init="build")
raw = np.asarray(res.labels, dtype=np.int64)
medoids = np.asarray(res.medoids, dtype=np.int64)
centers = X[medoids]
values["cost"] = float(D[np.arange(len(rows)), medoids[raw]].sum()) / len(rows) # average dissimilarity to the medoid
canon = csc.canonical(raw)
for m in medoids:
values[f"medoid_row[{int(canon[m])}]"] = int(rows[m])
extra["distance"] = D[np.arange(len(rows)), medoids[raw]]
summary = f"PAM with k = {K} on {DISTANCE} dissimilarities: average dissimilarity to the medoid {values['cost']:.3f}."
# %% 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-medoids (PAM)",
"engine": cs.engine_info("kmedoids", "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,
"algorithm": "pam",
"samples": 5,
"sample_size": 0,
"numlocal": 2,
"maxneighbor": 0,
"distance": "auto",
"max_iter": 100,
"scale": "standard",
"missing": "drop",
}},
})
Here the average dissimilarity to the nearest medoid is 0.879. Each medoid is a row you can open and read, which makes segments easy to explain. The price is memory: PAM compares rows in pairs, so the matrix grows with the square of the row count. Unsquared distances soften outliers, but a tiny odd group can still win a medoid.
Means, medoids and fuzzy edges
ExploreAExplorable · Means, medoids and fuzzy memberships
What changes when a cluster's center must be a real point, or a point may belong to several clusters?
Far outliers can drag a cluster's center away. Which method keeps closest to the planted groups here?
Data
Show
Near 1 is almost hard k-means; larger m gives softer memberships.
Commit your prediction above to see the result
Make your prediction to see the result.
Far outliers join three round clusters. A mean is pulled toward every point it averages; a medoid stays on a real row. Switch to fuzzy c-means to see memberships soften near the borders.
k-medians: medians per column
Readk-medians gives each row to the nearest center in city-block distance and sets every coordinate of a center to the median of that coordinate in its cluster. On the arrests data its total city-block cost is 95.2.
Two traps. It is not k-medoids: a coordinatewise median is usually not a real row. And the axes matter: rotate the columns, for example by running PCA first, and the answer changes. Use Manhattan distance for silhouette too, so the check matches the fit.
k-center: nobody left far away
Readk-center cares only about the worst-served row. Farthest-first traversal starts at one row and keeps adding the row farthest from every center chosen so far. With a true distance (one that obeys the triangle inequality) the greedy radius is at most twice the best possible.
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
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",
}},
})
The worst distance is 2.57 and 90% of rows sit within 2.33. Agreement with the species is lower than k-means' (adjusted Rand 0.410 against 0.592): k-center covers the space, it doesn't look for groups.
Trimming: a chosen share left out
ReadTrimmed k-means keeps the rows that fit best and fits the centers to those alone. On iris, trimming 10% left out 15 rows.
You choose , and the method obeys it: it removes that share whether or not outliers exist. A real but small cluster can be trimmed away, while a dense clump of bad rows can earn its own center. That is why trimmed rows are not a test with a known false-positive rate. Refit over a few values of and look at who gets left out.
Where each idea stands in CodeSplash
Read| Entry | In CodeSplash |
|---|---|
| K-means (UCL001) | Runs in CodeSplash: k-means |
| K-medoids / PAM (UCL003) | Runs in CodeSplash: k-medoids (PAM) |
| K-medians (UCL006) | Runs as an option of k-means: Algorithm k-medians |
| Metric k-center (UCL007) | Runs in CodeSplash: k-center (farthest-first) |
| Trimmed k-means (UCL010) | Runs as an option of k-means: Trim the farthest share |
Whatever the method, a stable partition can still track a nuisance such as batch, site or missingness. Read the groups in the original columns before you name them.
Check your understanding
CheckpointCheck yourself
Two k-means runs with the same and different starting centers end with different clusters. What does that tell you?
Show the answer
Answer: b
Each step of Lloyd's algorithm lowers the cost, but where it stops depends on the start. That's why the app runs several starts and keeps the lowest within-cluster sum of squares.
Check yourself
Inertia drops from one value of to the next every time you add a cluster. Can you choose by the lowest inertia?
Show the answer
Answer: b
More centers always sit closer to the rows. Compare inertia only between starts at the same , and choose with stability and usefulness.
Check yourself
Your rows mix numbers and categories, and you've built Gower dissimilarities. Which method can use them as they are?
Show the answer
Answer: c
PAM only compares dissimilarities and picks real rows as centers, so it never needs to average a category. k-means and k-medians both compute centers by averaging or taking medians of numbers.
Check yourself
What usually limits PAM on a large table?
Show the answer
Answer: a
PAM compares rows in pairs. For large tables, CLARA and CLARANS cut that cost; that's the next lesson.
Check yourself
You rotate your columns with PCA and rerun k-medians. Should you expect the same clusters?
Show the answer
Answer: b
Euclidean distance survives a rotation; city-block distance doesn't. k-medians is tied to the columns you give it.
Check yourself
Which statement about a k-medians center is true?
Show the answer
Answer: b
k-medians and k-medoids are different objectives. A medoid is a row; a k-medians center is assembled column by column.
Check yourself
You need a few representative stores so that no store is far from one of them. Which method fits that goal?
Show the answer
Answer: b
k-center's cost is the worst-served row, which is the coverage question. k-means minimizes an average and can leave a remote store far away.
Check yourself
How should you check a k-center result?
Show the answer
Answer: b
Check a method against its own target. Silhouette rewards compact groups, which k-center never aimed for.
Check yourself
You run trimmed k-means with = 10% on data that contain no outliers at all. What happens?
Show the answer
Answer: b
The share is a setting, not an estimate. The method always sets aside that fraction, so trimmed rows are candidates to inspect, not proven outliers.
Check yourself
What can go wrong with trimming?
Show the answer
Answer: a
Trimming removes the worst-fitting rows. A genuine small group fits badly, and a tight clump of errors fits well. Refit over several shares and audit who is left out.
Do it on your own data
In the appUnder Find segments, open k-means and switch Algorithm to k-medians or set Trim the farthest share; open k-medoids (PAM) for mixed columns; open k-center (farthest-first) when coverage is the goal. Save each result and compare them on the same rows.
Concepts in this lesson