Skip to content

k-means and k-medoids for big, messy or directional data

Mini-batch, k-medians, spherical and trimmed k-means, and CLARA and CLARANS for k-medoids — what each changes about the fit and when to reach for it.

Applied ~12 min7 steps

What runs in CodeSplash

You will be able to

  • Choose a k-means variant for large data, outliers or direction-only data
  • Read trimmed rows (−1) as possible outliers, not a cluster
  • Explain how CLARA and CLARANS trade a little fit for much less work

Read first

01

One idea, four ways to fit it

Read

Every k-means variant keeps the same picture: kk centers, each row joins the nearest. What changes is how "nearest" is measured, which rows are allowed to move the centers, and how much data each step looks at.

AlgorithmDistanceCentersReach for it when
Lloydsquared Euclideanmeansthe default
Mini-batchMini-batch k-meansk-means that moves each center a little toward small random batches of rows, so a pass over large data costs much less.squared Euclideanrunning means of random batchesthe data are too large for full passes
k-mediansk-mediansPartitioning with city-block (L1) distance and centers at each cluster's coordinate-wise medians; less pulled by outliers than means.city-block (L1)mediansoutliers or long tails drag means
SphericalSpherical k-meansk-means on rows scaled to length 1, grouping by direction (cosine similarity) and ignoring each row's size.cosinenormalized meansonly direction matters (embeddings, profiles)

All four start from the same k-means++ centers, drawn from the app's shared random stream, so Python and R reach the same clusters.

02

Mini-batch: less work per pass

Reflect

Mini-batch k-means draws a small batch of rows, assigns them to the current centers, and moves each center a little toward its new members. Each center's step shrinks as it sees more rows. On iris with batches of 32 rows it took 25 batch steps and reached a within-cluster sum of squares of 141.

The fit is usually a little worse than Lloyd's. Check it on a sample before trusting it on millions of rows.

03

k-medians and spherical k-means

Predict

Predict first

A state with an extreme assault rate sits far from the rest. Which method's centers move less toward it?

k-meansk-mediansThey are equally affected
Reveal

k-medians. A median ignores how far the extreme value is, only which side it falls on. On the arrests data k-medians reports an L1 objective of 95.2, the total city-block distance from rows to their medians.

Spherical k-means scales every row to length 1 before clustering, so two rows that point the same way are close however long they are. That's what you want for text embeddings: on the topic embeddings it finds 4 clusters with an adjusted Rand index against the known themes of 0.678.

04

Trimming outliers out of the fit

Reflect

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. leaves the share α of rows farthest from their centers out of the fit. On iris, trimming 10% sets aside 15 rows. They get the label −1 and don't pull any center.

k-means clusteringRecorded · Python and R agreeRecorded 2026-11-25 · 41 values compared
R

Trimmed k-means with k = 3: between-cluster variation is 81% of the total (within-cluster sum of squares 86.47).

Clusters
3
Mean silhouette
0.4714

Plots

ClustersWhich rows group together, and how well separated are the groups?
View data
CenterClusterPC1 (73%)PC2 (23%)
false2−2.2650.4800
false2−2.081−0.6741
false2−2.364−0.3419
false2−2.299−0.5974
false2−2.3900.6468
false2−2.0761.489
false2−2.4440.0476
false2−2.2330.2231
false2−2.335−1.115
false2−2.184−0.4690
false2−2.1661.044
false2−2.3260.1331
false2−2.218−0.7287
false2−2.633−0.9615
false-1−2.1991.860
false-1−2.2622.686
false2−2.2081.484
false2−2.1900.4888
false2−1.8991.405
false2−2.3431.128
false2−1.9140.4089
false2−2.2070.9241
false2−2.7740.4583
false2−1.8190.0856
false2−2.2270.1373
false2−1.952−0.6256
false2−2.0510.2422
false2−2.1690.5271
false2−2.1400.3132
false2−2.265−0.3377
false2−2.140−0.5045
false2−1.8320.4237
false-1−2.6151.794
false-1−2.4462.151
false2−2.110−0.4602
false2−2.208−0.2061
false2−2.0450.6616
false2−2.5270.5923
false2−2.430−0.9042
false2−2.1700.2689
false2−2.2860.4417
false-1−1.858−2.337
false2−2.554−0.4791
false2−1.9640.4723
false2−2.1371.142
false2−2.070−0.7111
false2−2.3851.120
false2−2.394−0.3862
false2−2.2290.9980
false2−2.2040.0092
false11.1020.8630
false10.73130.5946
false11.2410.6163
false30.4075−1.754
false11.075−0.2084
false30.3887−0.5933
false10.74650.7730
false-1−0.4873−1.852
false10.92790.0322
false30.0114−1.034

First 60 of 153 rows.

Silhouette widthsHow well does each row fit its cluster compared with the next-nearest cluster?
View data
ClusterSilhouette width
10.5612
10.5472
10.5470
10.5450
10.5394
10.5343
10.5331
10.5213
10.5181
10.5178
10.5090
10.5053
10.5051
10.4998
10.4956
10.4750
10.4747
10.4573
10.4517
10.4504
10.4458
10.4309
10.4288
10.4269
10.3965
10.3869
10.3867
10.3652
10.3589
10.3352
10.3317
10.3021
10.2935
10.2159
10.2128
10.2095
10.2008
10.1856
10.1851
10.1212
10.1143
10.1054
10.0967
10.0785
10.0453
10.0378
10.0058
1−0.0190
20.7716
20.7675
20.7673
20.7645
20.7627
20.7625
20.7556
20.7546
20.7533
20.7523
20.7499
20.7464

First 60 of 135 rows.

Clusters

ClusterSizeSharesepal_lengthsepal_widthpetal_lengthpetal_width
14832.0%6.5583.0355.2601.900
24530.0%4.9693.3871.4710.2467
34228.0%5.7862.6714.3451.381
  • 15 rows (10%) farthest from their centers were trimmed: they are labeled −1 and left out of the centers.
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 c0bec8f6fa2393e9
# 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_trimmed/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))
ALGORITHM <- "lloyd"
TRIM <- 0.1
if (is.null(TRIM)) TRIM <- 0
if (TRIM > 0 && ALGORITHM != "lloyd") cs_error("CS_E_INVALID_OPTION", option = "Trim", allowed = "0 unless the algorithm is Lloyd's k-means", value = TRIM)
rng <- cs_rng(SEED)  # shared stream: identical k-means++ starts in Python and R
# Variants (Stage 12.7): twins in codesplash.ml.cluster_partition <-> codesplashr ml_cluster_partition.R
if (ALGORITHM == "spherical") {
  X <- cs_cp_unit_rows(X)  # directions only: every row scaled to length 1
  fit_X <- X[!held, , drop = FALSE]
}
if (ALGORITHM == "minibatch") {
  f <- cs_cp_minibatch_kmeans(fit_X, K, rng, 1024, 10, 5)
  values$n_steps <- f$steps
} else if (ALGORITHM == "kmedians") {
  f <- cs_cp_kmedians(fit_X, K, rng, 5, 300)
  values$objective <- f$objective
} else if (ALGORITHM == "spherical") {
  f <- cs_cp_spherical_kmeans(fit_X, K, rng, 5, 300)
  values$objective <- f$objective
} else {
  f <- cs_cp_trimmed_kmeans(fit_X, K, TRIM, rng, 5, 300)
  values$objective <- f$objective
  values$n_trimmed <- sum(f$labels == -1L)
}
centers <- f$centers
raw <- integer(length(rows))
raw[!held] <- f$labels
if (any(held)) {
  dist_held <- if (ALGORITHM == "kmedians") cs_cp_l1_to_centers(X[held, , drop = FALSE], centers) else cs_cp_sq_to_centers(X[held, , drop = FALSE], centers)
  raw[held] <- max.col(-dist_held, 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)
kept <- raw[!held] >= 0
FX <- fit_X[kept, , drop = FALSE]
own_sq <- cs_cp_sq_to_centers(FX, centers)[cbind(seq_len(nrow(FX)), raw[!held][kept] + 1L)]
inertia <- cs_cp_seq_sum(own_sq)
total_ss <- sum(sweep(FX, 2, colMeans(FX))^2)
values$inertia <- inertia
values$between_ratio <- if (total_ss > 0) 1 - inertia / total_ss else NaN
near <- pmax(raw, 0L) + 1L
if (ALGORITHM == "kmedians") {
  extra$distance <- cs_cp_l1_to_centers(X, centers)[cbind(seq_along(rows), near)]
  if (length(rows) <= 5000) {
    D <- as.matrix(stats::dist(X, method = "manhattan"))  # the silhouette uses the L1 distance k-medians minimizes
    dimnames(D) <- NULL
  } else {
    warnings <- c(warnings, "Above 5,000 rows the silhouette uses Euclidean distance on the scaled design, not the L1 distance k-medians minimizes.")
  }
} else {
  extra$distance <- sqrt(pmax(cs_cp_sq_to_centers(X, centers)[cbind(seq_along(rows), near)], 0))
}
LABEL <- switch(ALGORITHM, minibatch = "Mini-batch k-means", kmedians = "k-medians", spherical = "Spherical k-means", lloyd = "Trimmed k-means")
summary <- sprintf("%s with k = %d: between-cluster variation is %.0f%% of the total (within-cluster sum of squares %s).",
                   LABEL, K, 100 * values$between_ratio, formatC(values$inertia, digits = 4, format = "g"))
if (ALGORITHM == "lloyd") warnings <- c(warnings, sprintf("%d rows (%.0f%%) farthest from their centers were trimmed: they are labeled −1 and left out of the centers.", values$n_trimmed, 100 * TRIM))

# %% 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.1,
    batch_size = 1024,
    passes = 10,
    n_init = 5,
    max_iter = 300,
    holdout = 0,
    scale = "standard",
    missing = "drop"
  ))
))
Python

Trimmed k-means with k = 3: between-cluster variation is 81% of the total (within-cluster sum of squares 86.47).

Clusters
3
Mean silhouette
0.4714

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

Clusters

ClusterSizeSharesepal_lengthsepal_widthpetal_lengthpetal_width
14832.0%6.5583.0355.2601.900
24530.0%4.9693.3871.4710.2467
34228.0%5.7862.6714.3451.381
  • 15 rows (10%) farthest from their centers were trimmed: they are labeled −1 and left out of the centers.
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 c0bec8f6fa2393e9
# 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
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.kmeans/iris_trimmed/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))
ALGORITHM = "lloyd"
TRIM = 0.1 or 0.0
if TRIM > 0 and ALGORITHM != "lloyd":
    cs.cs_error("CS_E_INVALID_OPTION", option="Trim", allowed="0 unless the algorithm is Lloyd's k-means", value=TRIM)
rng = Rng(SEED)  # shared stream: identical k-means++ starts in Python and R
# Variants (Stage 12.7): twins in codesplash.ml.cluster_partition ↔ codesplashr ml_cluster_partition.R
if ALGORITHM == "spherical":
    X = cpart.unit_rows(X)  # directions only: every row scaled to length 1
    fit_X = X[~held]
if ALGORITHM == "minibatch":
    lab_f, centers, _, steps = cpart.minibatch_kmeans(fit_X, K, rng, 1024, 10, 5)
    values["n_steps"] = int(steps)
elif ALGORITHM == "kmedians":
    lab_f, centers, objective, _ = cpart.kmedians(fit_X, K, rng, 5, 300)
    values["objective"] = float(objective)
elif ALGORITHM == "spherical":
    lab_f, centers, objective, _ = cpart.spherical_kmeans(fit_X, K, rng, 5, 300)
    values["objective"] = float(objective)
else:
    lab_f, centers, objective, _ = cpart.trimmed_kmeans(fit_X, K, TRIM, rng, 5, 300)
    values["objective"] = float(objective)
    values["n_trimmed"] = int(np.sum(lab_f == -1))
raw = np.empty(len(rows), dtype=np.int64)
raw[~held] = lab_f
if held.any():
    dist_held = cpart.l1_to_centers(X[held], centers) if ALGORITHM == "kmedians" else cpart.sq_to_centers(X[held], centers)
    raw[held] = np.argmin(dist_held, 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())
kept = raw[~held] >= 0
FX = fit_X[kept]
own_sq = cpart.sq_to_centers(FX, centers)[np.arange(len(FX)), raw[~held][kept]]
inertia = cpart.seq_sum(own_sq)
total_ss = float(np.sum((FX - FX.mean(axis=0)) ** 2))
values["inertia"] = inertia
values["between_ratio"] = 1.0 - inertia / total_ss if total_ss > 0 else float("nan")
near = np.maximum(raw, 0)
if ALGORITHM == "kmedians":
    extra["distance"] = cpart.l1_to_centers(X, centers)[np.arange(len(rows)), near]
    if len(rows) <= 5000:
        D = cdist(X, X, metric="cityblock")  # the silhouette uses the L1 distance k-medians minimizes
    else:
        warnings.append("Above 5,000 rows the silhouette uses Euclidean distance on the scaled design, not the L1 distance k-medians minimizes.")
else:
    extra["distance"] = np.sqrt(np.maximum(cpart.sq_to_centers(X, centers)[np.arange(len(rows)), near], 0.0))
LABEL = {"minibatch": "Mini-batch k-means", "kmedians": "k-medians", "spherical": "Spherical k-means", "lloyd": "Trimmed k-means"}[ALGORITHM]
summary = f"{LABEL} with k = {K}: between-cluster variation is {values['between_ratio']:.0%} of the total (within-cluster sum of squares {values['inertia']:.4g})."
if ALGORITHM == "lloyd":
    warnings.append(f"{values['n_trimmed']} rows ({TRIM:.0%}) farthest from their centers were trimmed: they are labeled −1 and left out of the centers.")

# %% 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.1,
        "batch_size": 1024,
        "passes": 10,
        "n_init": 5,
        "max_iter": 300,
        "holdout": 0,
        "scale": "standard",
        "missing": "drop",
    }},
})

Trimmed rows are a finding, not a cluster. Look at who they are: if one group is trimmed far more often than the others, the trimming is deciding something about that group.

05

k-medoids on large data: CLARA and CLARANS

Read

PAM compares every pair of rows, so its memory grows with the square of the row count. Two variants cut the work:

  • CLARACLARAk-medoids on several random samples; the medoids with the lowest average dissimilarity over all rows win. runs PAM on several random samples and keeps the medoids with the lowest average dissimilarity over all rows. On iris it drew samples of 46 rows and sample 1 won, with an average dissimilarity of 0.885.
  • CLARANSCLARANSk-medoids by random medoid swaps: keep any swap that lowers the total dissimilarity, stop after a run of failed tries. tries random medoid swaps, keeps the ones that help, and stops after 250 failed tries in a row.

Both work with Gower dissimilarities for mixed data: CLARA on four penguin features (two numeric, two categorical) gives an average dissimilarity of 0.160.

06

Check your understanding

Checkpoint

Check yourself

A trimmed k-means run labels 30 rows as −1. What does that tell you?

Show the answer

Answer: b

Trimming sets aside the share α of rows that fit worst, so the centers describe the rest. Look at them as candidate outliers.

Check yourself

You want to group documents by their embedding vectors, and longer documents have longer vectors. Which algorithm fits?

Show the answer

Answer: b

Spherical k-means scales each row to length 1 first, so document length stops mattering and only the direction of the embedding counts.

Check yourself

How does CLARA choose between the medoids found on its samples?

Show the answer

Answer: c

Each sample only proposes medoids. CLARA scores every proposal on the full data, so one unlucky sample can't decide the result.

Check yourself

What do you give up with mini-batch k-means?

Show the answer

Answer: a

Batches make each step cheap but noisy. The app draws batches from its shared random stream, so the two engines still agree exactly.

07

Do it on your own data

In the app

Under Find segments, open k-means and switch Algorithm, or open k-medoids (PAM) and pick CLARA for a large table.