Skip to content

Partitions at scale and in other geometries

Mini-batch k-means, CLARA and CLARANS trade a little fit for much less work; spherical and kernel k-means change what "close" means. What each approximation assumes, and how to check that it held.

Advanced ~13 min11 steps

What runs in CodeSplash

You will be able to

  • Explain how mini-batch updates, CLARA samples and CLARANS swaps approximate the full fit
  • Say which data break each approximation (skewed batches, rare groups, one lucky seed)
  • Choose spherical k-means when direction carries the signal, and check it with cosine
  • Explain kernel k-means as k-means in a feature space, and why the kernel can invent separation

Read first

01

Two reasons to leave plain k-means

Read

Plain k-means and PAM look at every row on every pass. That breaks down in two ways:

  • Scale. Millions of rows make full passes slow, and PAM's pairwise matrix won't fit. Mini-batch k-meansMini-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., CLARACLARAk-medoids on several random samples; the medoids with the lowest average dissimilarity over all rows win. and CLARANSCLARANSk-medoids by random medoid swaps: keep any swap that lowers the total dissimilarity, stop after a run of failed tries. approximate the same objective with less work.
  • Geometry. Squared Euclidean distance may be the wrong notion of "close". Spherical k-meansSpherical k-meansk-means on rows scaled to length 1, grouping by direction (cosine similarity) and ignoring each row's size. compares directions; kernel k-meansKernel k-meansk-means run in a kernel's feature space, using only kernel values between rows. compares rows in a feature space defined by a kernel.

Each approximation rests on an assumption you can check.

02

Mini-batch: running means

Read

Each step draws a batch, assigns its rows, and nudges each center toward its new members: μk←(1−ηk)μk+ηkx\mu_k \leftarrow (1-\eta_k)\mu_k + \eta_k x with ηk=1/tk\eta_k = 1/t_k, where tkt_k counts the rows center kk has seen. The target is still the full-data k-means cost, but a single noisy step can raise it.

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

Mini-batch k-means with k = 3: between-cluster variation is 76% of the total (within-cluster sum of squares 141.2).

Clusters
3
Mean silhouette
0.4646

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
false2−2.1991.860
false2−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
false2−2.6151.794
false2−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
false2−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
false31.1020.8630
false30.73130.5946
false31.2410.6163
false10.4075−1.754
false11.075−0.2084
false10.3887−0.5933
false30.74650.7730
false1−0.4873−1.852
false10.92790.0322
false10.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.5789
10.5764
10.5763
10.5760
10.5729
10.5668
10.5561
10.5537
10.5492
10.5480
10.5467
10.5431
10.5359
10.5356
10.5076
10.4974
10.4795
10.4712
10.4652
10.4532
10.4502
10.4429
10.4348
10.4286
10.4255
10.4183
10.4165
10.4115
10.4112
10.4075
10.4031
10.3998
10.3995
10.3976
10.3807
10.3798
10.3763
10.3759
10.3741
10.3741
10.3735
10.3432
10.2923
10.2812
10.2780
10.2647
10.2482
10.2437
10.2123
10.1609
10.1573
10.1211
10.0960
10.0723
10.0659
10.0257
10.0167
1−0.0017
1−0.0119
20.7374

First 60 of 150 rows.

Clusters

ClusterSizeSharesepal_lengthsepal_widthpetal_lengthpetal_width
15939.3%5.8642.6934.4341.441
25033.3%5.0063.4281.4620.2460
34127.3%6.8343.1295.5852.015
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 20f3279f7bd2941c
# 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_minibatch/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 <- "minibatch"
TRIM <- 0
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, 32, 5, 3)
  values$n_steps <- f$steps
} else if (ALGORITHM == "kmedians") {
  f <- cs_cp_kmedians(fit_X, K, rng, 3, 300)
  values$objective <- f$objective
} else if (ALGORITHM == "spherical") {
  f <- cs_cp_spherical_kmeans(fit_X, K, rng, 3, 300)
  values$objective <- f$objective
} else {
  f <- cs_cp_trimmed_kmeans(fit_X, K, TRIM, rng, 3, 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 = "minibatch",
    trim = 0,
    batch_size = 32,
    passes = 5,
    n_init = 3,
    max_iter = 300,
    holdout = 0,
    scale = "standard",
    missing = "drop"
  ))
))
Python

Mini-batch k-means with k = 3: between-cluster variation is 76% of the total (within-cluster sum of squares 141.2).

Clusters
3
Mean silhouette
0.4646

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

Clusters

ClusterSizeSharesepal_lengthsepal_widthpetal_lengthpetal_width
15939.3%5.8642.6934.4341.441
25033.3%5.0063.4281.4620.2460
34127.3%6.8343.1295.5852.015
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 20f3279f7bd2941c
# 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_minibatch/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 = "minibatch"
TRIM = 0 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, 32, 5, 3)
    values["n_steps"] = int(steps)
elif ALGORITHM == "kmedians":
    lab_f, centers, objective, _ = cpart.kmedians(fit_X, K, rng, 3, 300)
    values["objective"] = float(objective)
elif ALGORITHM == "spherical":
    lab_f, centers, objective, _ = cpart.spherical_kmeans(fit_X, K, rng, 3, 300)
    values["objective"] = float(objective)
else:
    lab_f, centers, objective, _ = cpart.trimmed_kmeans(fit_X, K, TRIM, rng, 3, 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": "minibatch",
        "trim": 0,
        "batch_size": 32,
        "passes": 5,
        "n_init": 3,
        "max_iter": 300,
        "holdout": 0,
        "scale": "standard",
        "missing": "drop",
    }},
})

After 25 batch steps the cost is 141, against 140 for full Lloyd passes. Batches must look like the whole table: the app draws them at random. Batches taken in file order from sorted data would bias the early centers.

03

Does it follow change?

Predict

Predict first

Customer behavior shifts halfway through the year. Will mini-batch k-means, run over the whole year, track the shift?

Yes, it keeps learning from new batchesNo, its steps shrink as each center sees more rows
Reveal

No. Each center's step size is one over the number of rows it has seen, so late rows barely move it. The method approximates one fixed partition of all the data. To follow change, refit on recent windows and compare.

04

CLARA: sample, fit, score on everyone

Read

CLARA runs PAM on several random samples. Each sample only proposes medoids; every proposal is scored on all rows, and the lowest full-data cost wins: arg⁡min⁡b∑i=1nmin⁡m∈Mbd(xi,xm)\arg\min_b \sum_{i=1}^{n}\min_{m\in M_b} d(x_i,x_m).

k-medoids (PAM)Recorded · Python and R agreeRecorded 2026-11-25 · 42 values compared
R

CLARA with k = 3 (5 samples of 46 rows) on euclidean dissimilarities: average dissimilarity to the medoid 0.885.

Clusters
3
Mean silhouette
0.4552

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
false2−2.1991.860
false2−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
false2−2.6151.794
false2−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
false3−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
false3−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.5542
10.5524
10.5487
10.5337
10.5333
10.5278
10.5277
10.5252
10.5190
10.5115
10.4949
10.4794
10.4768
10.4755
10.4740
10.4726
10.4646
10.4594
10.4579
10.4432
10.4421
10.4394
10.4321
10.4162
10.4160
10.4114
10.4103
10.4085
10.4071
10.4016
10.3964
10.3749
10.3470
10.3414
10.3225
10.3099
10.2846
10.2587
10.2578
10.2362
10.1616
10.1562
10.1481
10.1274
10.1247
10.1173
10.1034
10.0516
10.0208
10.0202
1−0.0212
1−0.0483
1−0.0610
20.7434
20.7422
20.7382
20.7382
20.7380
20.7330
20.7323

First 60 of 150 rows.

Clusters

ClusterSizeSharesepal_lengthsepal_widthpetal_lengthpetal_width
15335.3%6.7193.0665.4301.949
24932.7%5.0163.4511.4650.2449
34832.0%5.7212.6464.2521.346

Samples (average dissimilarity to the medoid over all rows)

SampleAverage dissimilarity
10.8853
20.9043
30.9483
40.8853
50.9109
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 b5b4d119be7cdf95
# 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_clara/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))
ALGORITHM <- "clara"
DISTANCE <- "auto"
if (DISTANCE == "auto") DISTANCE <- if (any(unlist(KINDS[FEATURES]) != "numeric")) "gower" else "euclidean"
rng <- cs_rng(SEED)  # shared stream: identical samples / swaps in Python and R
cols <- if (DISTANCE == "gower") cs_cp_gower_ranges(frame, FEATURES, KINDS) else NULL
if (ALGORITHM == "clara") {
  # CLARA: PAM on several samples; the medoids that serve ALL rows best win (twin: clara)
  SAMPLE <- 0
  if (SAMPLE == 0) SAMPLE <- 40 + 2 * K
  SAMPLE <- min(SAMPLE, length(rows))
  if (K >= SAMPLE) stop(sprintf("k = %d needs samples of more than %d rows; the sample size is %d.", K, K, SAMPLE))
  f <- cs_cp_clara(X, cols, DISTANCE, K, rng, 5, SAMPLE)
  values$sample_size <- SAMPLE
  values$best_sample <- which.min(f$costs)
  tables[[length(tables) + 1L]] <- list(
    key = "samples", title = "Samples (average dissimilarity to the medoid over all rows)",
    columns = list(list(key = "sample", label = "Sample", type = "integer"), list(key = "cost", label = "Average dissimilarity", type = "number")),
    rows = lapply(seq_along(f$costs), function(i) list(sample = i, cost = f$costs[i]))
  )
  if (length(rows) <= 5000) {
    D <- if (DISTANCE == "gower") cs_ml_gower(frame, FEATURES, KINDS) else as.matrix(stats::dist(X, method = if (DISTANCE == "manhattan") "manhattan" else "euclidean"))
    dimnames(D) <- NULL
  } else {
    warnings <- c(warnings, "Above 5,000 rows the silhouette uses Euclidean distance on the scaled design, not the chosen dissimilarity.")
  }
  summary <- sprintf("CLARA with k = %d (%d samples of %d rows) on %s dissimilarities: average dissimilarity to the medoid %.3f.", K, 5, SAMPLE, DISTANCE, f$cost)
} else {
  # CLARANS: randomized medoid swaps (twin: clarans)
  if (length(rows) > 5000) stop("CLARANS keeps a full dissimilarity matrix; use it on at most 5,000 rows (or CLARA).")
  D <- if (DISTANCE == "gower") cs_ml_gower(frame, FEATURES, KINDS) else as.matrix(stats::dist(X, method = if (DISTANCE == "manhattan") "manhattan" else "euclidean"))
  dimnames(D) <- NULL
  MAXNB <- 0
  f <- cs_cp_clarans(D, K, rng, 2, if (MAXNB > 0) MAXNB else NULL)
  values$maxneighbor <- f$maxneighbor
  tables[[length(tables) + 1L]] <- list(
    key = "searches", title = "Local searches (average dissimilarity to the medoid)",
    columns = list(list(key = "search", label = "Search", type = "integer"), list(key = "cost", label = "Average dissimilarity", type = "number")),
    rows = lapply(seq_along(f$costs), function(i) list(search = i, cost = f$costs[i]))
  )
  summary <- sprintf("CLARANS with k = %d (%d local searches) on %s dissimilarities: average dissimilarity to the medoid %.3f.", K, 2, DISTANCE, f$cost)
}
raw <- f$labels
medoids <- f$medoids
centers <- X[medoids + 1L, , drop = FALSE]
values$cost <- f$cost
canon <- cs_ml_canonical(raw)
for (m in medoids) values[[sprintf("medoid_row[%d]", canon[m + 1L])]] <- rows[m + 1L]
extra$distance <- f$own

# %% 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 = "clara",
    samples = 5,
    sample_size = 0,
    numlocal = 2,
    maxneighbor = 0,
    distance = "auto",
    max_iter = 100,
    scale = "standard",
    missing = "drop"
  ))
))
Python

CLARA with k = 3 (5 samples of 46 rows) on euclidean dissimilarities: average dissimilarity to the medoid 0.885.

Clusters
3
Mean silhouette
0.4552

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

Clusters

ClusterSizeSharesepal_lengthsepal_widthpetal_lengthpetal_width
15335.3%6.7193.0665.4301.949
24932.7%5.0163.4511.4650.2449
34832.0%5.7212.6464.2521.346

Samples (average dissimilarity to the medoid over all rows)

SampleAverage dissimilarity
10.8853
20.9043
30.9483
40.8853
50.9109
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 b5b4d119be7cdf95
# 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
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.pam/iris_clara/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))
ALGORITHM = "clara"
DISTANCE = "auto"
if DISTANCE == "auto":
    DISTANCE = "gower" if any(KINDS[f] != "numeric" for f in FEATURES) else "euclidean"
rng = Rng(SEED)  # shared stream: identical samples / swaps in Python and R
cols = cpart.gower_ranges(frame, FEATURES, KINDS) if DISTANCE == "gower" else None
if ALGORITHM == "clara":
    # CLARA: PAM on several samples; the medoids that serve ALL rows best win (twin: cs_cp_clara)
    SAMPLE = 0 or 40 + 2 * K
    SAMPLE = min(SAMPLE, len(rows))
    if K >= SAMPLE:
        raise ValueError(f"k = {K} needs samples of more than {K} rows; the sample size is {SAMPLE}.")
    raw, medoids, cost, own, costs = cpart.clara(X, cols, DISTANCE, K, rng, 5, SAMPLE, 100)
    values["sample_size"] = int(SAMPLE)
    values["best_sample"] = int(np.argmin(costs)) + 1
    tables.append({
        "key": "samples", "title": "Samples (average dissimilarity to the medoid over all rows)",
        "columns": [{"key": "sample", "label": "Sample", "type": "integer"}, {"key": "cost", "label": "Average dissimilarity", "type": "number"}],
        "rows": [{"sample": i + 1, "cost": float(c)} for i, c in enumerate(costs)],
    })
    if len(rows) <= 5000:
        D = csc.gower(frame, FEATURES, KINDS) if DISTANCE == "gower" else cdist(X, X, metric="cityblock" if DISTANCE == "manhattan" else "euclidean")
    else:
        warnings.append("Above 5,000 rows the silhouette uses Euclidean distance on the scaled design, not the chosen dissimilarity.")
    summary = f"CLARA with k = {K} (5 samples of {SAMPLE} rows) on {DISTANCE} dissimilarities: average dissimilarity to the medoid {cost:.3f}."
else:
    # CLARANS: randomized medoid swaps (twin: cs_cp_clarans)
    if len(rows) > 5000:
        raise ValueError("CLARANS keeps a full dissimilarity matrix; use it on at most 5,000 rows (or CLARA).")
    if DISTANCE == "gower":
        D = csc.gower(frame, FEATURES, KINDS)
    else:
        D = cdist(X, X, metric="cityblock" if DISTANCE == "manhattan" else "euclidean")
    raw, medoids, cost, own, costs, maxnb = cpart.clarans(D, K, rng, 2, 0 or None)
    values["maxneighbor"] = int(maxnb)
    tables.append({
        "key": "searches", "title": "Local searches (average dissimilarity to the medoid)",
        "columns": [{"key": "search", "label": "Search", "type": "integer"}, {"key": "cost", "label": "Average dissimilarity", "type": "number"}],
        "rows": [{"search": i + 1, "cost": float(c)} for i, c in enumerate(costs)],
    })
    summary = f"CLARANS with k = {K} (2 local searches) on {DISTANCE} dissimilarities: average dissimilarity to the medoid {cost:.3f}."
centers = X[medoids]
values["cost"] = float(cost)
canon = csc.canonical(raw)
for m in medoids:
    values[f"medoid_row[{int(canon[m])}]"] = int(rows[m])
extra["distance"] = own

# %% 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": "clara",
        "samples": 5,
        "sample_size": 0,
        "numlocal": 2,
        "maxneighbor": 0,
        "distance": "auto",
        "max_iter": 100,
        "scale": "standard",
        "missing": "drop",
    }},
})

With samples of 46 rows the cost is 0.885; PAM on the whole table reaches 0.879. The risk is a small group that no sample catches well: the overall cost can look fine while that group has no medoid of its own. Check rare groups by name, and compare against PAM on a subset you can afford.

05

CLARANS: random swaps, a search budget

Read

CLARANS treats each set of kk medoids as a point in a search. It proposes a random swap, accepts it if the total dissimilarity drops, and gives up on the current start after a set number of failed proposals in a row; then it restarts.

More search helps, but nothing certifies the best answer, and the result depends on the start and the random path. Judge it by the spread of costs over several seeds, not by the luckiest one, and use the same dissimilarity when you compare it with PAM or CLARA.

06

The swaps CLARA and CLARANS cut

Explore

AExplorable · 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?

How sure?

Data

Show

3
0
2.0

Near 1 is almost hard k-means; larger m gives softer memberships.

150
Simulating…

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

PAM tries every swap of a medoid for a non-medoid and keeps the best, which is why it slows down on big tables. CLARA runs the same search on samples; CLARANS tries only random swaps.

07

Spherical k-means: direction only

Read

Spherical k-means scales rows and centers to length 1 and maximizes ∑ixi⊤czi\sum_i x_i^\top c_{z_i}: each row joins the center with the highest cosine similarity, and each center is the normalized sum of its rows. On the topic embeddings its adjusted Rand index against the known themes is 0.678.

It assumes direction is the signal. Check it with cosine-based silhouette and the nearest neighbors of each center, not with a two-dimensional map: a flat projection can't show separation that lives in many dimensions.

08

Kernel k-means: means you never compute

Read

Kernel k-means runs k-means after a map ϕ\phi into a feature space, using only the kernel k(xi,xj)=ϕ(xi)⊤ϕ(xj)k(x_i,x_j)=\phi(x_i)^\top\phi(x_j). The distance from a row to cluster CC needs only kernel values:

k(xi,xi)−2∣C∣∑j∈Ck(xi,xj)+1∣C∣2∑j,l∈Ck(xj,xl)k(x_i,x_i)-\frac{2}{|C|}\sum_{j\in C}k(x_i,x_j)+\frac{1}{|C|^2}\sum_{j,l\in C}k(x_j,x_l)

Spectral clusteringRecorded · Python and R agreeRecorded 2026-11-25 · 27 values compared
R

Kernel k-means with k = 3 (RBF, γ = 0.16): within-cluster kernel distance 34.16.

Clusters
3
Mean silhouette
0.4599

Plots

ClustersWhich rows group together, and how well separated are the groups?
View data
ClusterPC1 (73%)PC2 (23%)
2−2.2650.4800
2−2.081−0.6741
2−2.364−0.3419
2−2.299−0.5974
2−2.3900.6468
2−2.0761.489
2−2.4440.0476
2−2.2330.2231
2−2.335−1.115
2−2.184−0.4690
2−2.1661.044
2−2.3260.1331
2−2.218−0.7287
2−2.633−0.9615
2−2.1991.860
2−2.2622.686
2−2.2081.484
2−2.1900.4888
2−1.8991.405
2−2.3431.128
2−1.9140.4089
2−2.2070.9241
2−2.7740.4583
2−1.8190.0856
2−2.2270.1373
2−1.952−0.6256
2−2.0510.2422
2−2.1690.5271
2−2.1400.3132
2−2.265−0.3377
2−2.140−0.5045
2−1.8320.4237
2−2.6151.794
2−2.4462.151
2−2.110−0.4602
2−2.208−0.2061
2−2.0450.6616
2−2.5270.5923
2−2.430−0.9042
2−2.1700.2689
2−2.2860.4417
2−1.858−2.337
2−2.554−0.4791
2−1.9640.4723
2−2.1371.142
2−2.070−0.7111
2−2.3851.120
2−2.394−0.3862
2−2.2290.9980
2−2.2040.0092
31.1020.8630
30.73130.5946
31.2410.6163
10.4075−1.754
11.075−0.2084
10.3887−0.5933
30.74650.7730
1−0.4873−1.852
10.92790.0322
10.0114−1.034

First 60 of 150 rows.

Silhouette widthsHow well does each row fit its cluster compared with the next-nearest cluster?
View data
ClusterSilhouette width
10.5863
10.5842
10.5840
10.5826
10.5801
10.5686
10.5667
10.5570
10.5559
10.5529
10.5492
10.5439
10.5437
10.5388
10.5004
10.4952
10.4701
10.4695
10.4585
10.4405
10.4390
10.4331
10.4307
10.4261
10.4247
10.4183
10.4163
10.4098
10.4050
10.4035
10.3925
10.3902
10.3797
10.3745
10.3664
10.3451
10.3435
10.3435
10.3409
10.3395
10.3319
10.3178
10.2413
10.2299
10.2191
10.1954
10.1774
10.1743
10.1327
10.0979
10.0859
10.0578
10.0377
20.7342
20.7333
20.7308
20.7288
20.7285
20.7247
20.7244

First 60 of 150 rows.

Clusters

ClusterSizeSharesepal_lengthsepal_widthpetal_lengthpetal_width
15335.3%5.8022.6744.3701.413
25033.3%5.0063.4281.4620.2460
34731.3%6.7813.0965.5111.972
The exact R script · R R version 4.5.1 (2025-06-13)
# Spectral clustering
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.spectral 1.0.0 · spec 41669fadcf152c73
# 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.spectral/iris_kernel_kmeans/out-r")
values <- list(n_used = length(rows))
centers <- NULL
center_ids <- NULL
D <- NULL
extra <- list()
tables <- list()
charts <- list()
summary <- NULL

# %% Clustering
cs_check_finite_columns(frame, FEATURES[vapply(FEATURES, function(f) identical(KINDS[[f]], "numeric"), logical(1))])  # ±Inf stops with CS_E_NOT_FINITE in both engines
K <- 3
ALGO <- "kernel_kmeans"
AFFINITY <- "rbf"
GAMMA <- NULL
n <- length(rows)
if (K >= n) cs_error("CS_E_TOO_FEW_ROWS", what = sprintf("Spectral clustering with k = %d", K), min = K + 1, n = n)
if (n > 3000) stop("Spectral clustering keeps an n × n similarity matrix; use it on at most 3,000 rows.")
if (ALGO == "kernel_kmeans" && AFFINITY == "knn") {
  cs_error("CS_E_INVALID_OPTION", option = "Similarity graph", allowed = "the Gaussian (RBF) kernel for kernel k-means", value = "k nearest neighbors")
}
if (!any(apply(X, 2, function(v) max(v) - min(v)) > 0)) cs_error("CS_E_CONSTANT", column = paste(FEATURES, collapse = ", "))
D2 <- cs_ml_sq_dists(X, X)
g <- if (!is.null(GAMMA)) as.numeric(GAMMA) else cs_ml_rbf_gamma(D2)
if (ALGO == "spectral") {
  nn <- min(10, n - 1)
  if (AFFINITY == "knn") values$n_neighbors <- nn else values$gamma <- g
  emb <- cs_ml_spectral_embed(cs_ml_affinity_matrix(D2, AFFINITY, g, nn), K)
  if (!is.null(emb$isolated)) cs_error("CS_E_UNDEFINED", what = "Spectral clustering", reason = sprintf("%d rows have no similar neighbor (lower the kernel width γ)", emb$isolated))
  ev <- emb$eigenvalues
  if (abs(ev[K] - ev[K + 1]) <= 1e-8 * max(1, abs(ev[K]))) {
    # tied eigenvalues at k: the k-dimensional embedding (and so the clusters) is not unique
    cs_error("CS_E_UNDEFINED", what = sprintf("Spectral clustering with k = %d", K), reason = sprintf("eigenvalues %d and %d of the similarity graph are tied, so the split into %d clusters is not unique; choose another k", K, K + 1, K))
  }
  km <- cs_ml_kmeans_fit(emb$Y, K, cs_rng(SEED), n_init = 5, max_iter = 300)
  raw <- km$labels
  values$embedding_inertia <- km$inertia
  m <- min(length(ev), max(10, K + 1))
  for (i in seq_len(m)) values[[sprintf("eigenvalue[%d]", i)]] <- ev[i]
  values$eigengap <- ev[K] - ev[K + 1]
  cand <- if (min(m, n - 1) > 2) 2:(min(m, n - 1) - 1) else integer(0)
  values$suggested_k <- if (length(cand)) {
    gaps <- vapply(cand, function(j) ev[j] - ev[j + 1], numeric(1))
    cand[which.max(gaps)]
  } else K
  values$n_components <- sum(ev > 1 - 1e-9)
  if (values$n_components > 1) warnings <- c(warnings, sprintf("The similarity graph falls into %d disconnected parts; each part needs at least one cluster.", values$n_components))
  xs <- seq_len(m)
  charts <- c(charts, list(cs_chart(
    "eigenvalues", "elbow-plot", "Eigenvalues of the normalized similarity matrix",
    list(k = cs_col("Eigenvalue (rank)", xs, "numeric"), score = cs_col("Eigenvalue", ev[seq_len(m)], "numeric"),
         chosen = cs_col("Largest gap", xs == values$suggested_k, "boolean")),
    note = sprintf("The largest gap after eigenvalue %d suggests k = %d.", values$suggested_k, values$suggested_k)
  )))
  summary <- sprintf("Spectral clustering with k = %d on a %s graph; the largest eigenvalue gap suggests k = %d.",
                     K, if (AFFINITY == "knn") "nearest-neighbor" else "Gaussian kernel", values$suggested_k)
} else {
  values$gamma <- g
  fit <- cs_ml_kernel_kmeans(exp(-g * D2), K, cs_rng(SEED), n_init = 5, max_iter = 300)
  raw <- fit$labels
  values$objective <- fit$objective
  values$iterations <- fit$iterations
  if (!fit$converged) warnings <- c(warnings, "Kernel k-means stopped at the iteration limit before the clusters settled.")
  if (length(unique(raw)) < K) warnings <- c(warnings, sprintf("%d cluster(s) ended with no rows.", K - length(unique(raw))))
  summary <- sprintf("Kernel k-means with k = %d (RBF, γ = %s): within-cluster kernel distance %s.", K,
                     formatC(g, digits = 3, format = "g"), formatC(values$objective, 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 = "Spectral clustering",
  engine = cs_engine_info("codesplashr", "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 = "kernel_kmeans",
    affinity = "rbf",
    gamma = NULL,
    n_neighbors = 10,
    n_init = 5,
    scale = "standard",
    missing = "drop"
  ))
))
Python

Kernel k-means with k = 3 (RBF, γ = 0.16): within-cluster kernel distance 34.16.

Clusters
3
Mean silhouette
0.4599

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

Clusters

ClusterSizeSharesepal_lengthsepal_widthpetal_lengthpetal_width
15335.3%5.8022.6744.3701.413
25033.3%5.0063.4281.4620.2460
34731.3%6.7813.0965.5111.972
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Spectral clustering
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.spectral 1.0.0 · spec 41669fadcf152c73
# 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 codesplash.ml import cluster_partitional 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.spectral/iris_kernel_kmeans/out-python")
values = {"n_used": len(rows)}
centers = None
center_ids = None
D = None
extra = {}
tables = []
charts = []
summary = None

# %% Clustering
cs.check_finite_columns(frame, [f for f in FEATURES if KINDS[f] == "numeric"])  # ±Inf stops with CS_E_NOT_FINITE in both engines
K = 3
ALGO = "kernel_kmeans"
AFFINITY = "rbf"
GAMMA = None
n = len(rows)
if K >= n:
    cs.cs_error("CS_E_TOO_FEW_ROWS", what=f"Spectral clustering with k = {K}", min=K + 1, n=n)
if n > 3000:
    raise ValueError("Spectral clustering keeps an n × n similarity matrix; use it on at most 3,000 rows.")
if ALGO == "kernel_kmeans" and AFFINITY == "knn":
    cs.cs_error("CS_E_INVALID_OPTION", option="Similarity graph", allowed="the Gaussian (RBF) kernel for kernel k-means", value="k nearest neighbors")
if not np.any(np.ptp(X, axis=0) > 0):
    cs.cs_error("CS_E_CONSTANT", column=", ".join(FEATURES))
D2 = cpart.pairwise_sq(X)
g = float(GAMMA) if GAMMA is not None else cpart.rbf_gamma(D2)
if ALGO == "spectral":
    nn = min(10, n - 1)
    if AFFINITY == "knn":
        values["n_neighbors"] = nn
    else:
        values["gamma"] = g
    emb = cpart.spectral_embed(cpart.affinity_matrix(D2, AFFINITY, g, nn), K)
    if "isolated" in emb:
        cs.cs_error("CS_E_UNDEFINED", what="Spectral clustering", reason=f"{emb['isolated']} rows have no similar neighbor (lower the kernel width γ)")
    ev = emb["eigenvalues"]
    if abs(ev[K - 1] - ev[K]) <= 1e-8 * max(1.0, abs(ev[K - 1])):
        # tied eigenvalues at k: the k-dimensional embedding (and so the clusters) is not unique
        cs.cs_error("CS_E_UNDEFINED", what=f"Spectral clustering with k = {K}", reason=f"eigenvalues {K} and {K + 1} of the similarity graph are tied, so the split into {K} clusters is not unique; choose another k")
    lab, _, inertia = csc.kmeans_fit(emb["Y"], K, Rng(SEED), n_init=5, max_iter=300)
    raw = lab
    values["embedding_inertia"] = inertia
    m = min(len(ev), max(10, K + 1))
    for i in range(m):
        values[f"eigenvalue[{i + 1}]"] = float(ev[i])
    values["eigengap"] = float(ev[K - 1] - ev[K])
    cand = list(range(2, min(m, n - 1)))
    values["suggested_k"] = int(max(cand, key=lambda j: (ev[j - 1] - ev[j], -j))) if cand else K
    values["n_components"] = int(np.sum(ev > 1.0 - 1e-9))
    if values["n_components"] > 1:
        warnings.append(f"The similarity graph falls into {values['n_components']} disconnected parts; each part needs at least one cluster.")
    xs = list(range(1, m + 1))
    charts.append(cs.chart(
        "eigenvalues", "elbow-plot", "Eigenvalues of the normalized similarity matrix",
        {"k": cs.col("Eigenvalue (rank)", xs, "numeric"), "score": cs.col("Eigenvalue", [float(ev[i]) for i in range(m)], "numeric"),
         "chosen": cs.col("Largest gap", [x == values["suggested_k"] for x in xs], "boolean")},
        note=f"The largest gap after eigenvalue {values['suggested_k']} suggests k = {values['suggested_k']}.",
    ))
    summary = (
        f"Spectral clustering with k = {K} on a {'nearest-neighbor' if AFFINITY == 'knn' else 'Gaussian kernel'} graph; "
        f"the largest eigenvalue gap suggests k = {values['suggested_k']}."
    )
else:
    values["gamma"] = g
    fit = cpart.kernel_kmeans(np.exp(-g * D2), K, Rng(SEED), n_init=5, max_iter=300)
    raw = fit["labels"]
    values["objective"] = fit["objective"]
    values["iterations"] = fit["iterations"]
    if not fit["converged"]:
        warnings.append("Kernel k-means stopped at the iteration limit before the clusters settled.")
    if len(set(raw.tolist())) < K:
        warnings.append(f"{K - len(set(raw.tolist()))} cluster(s) ended with no rows.")
    summary = f"Kernel k-means with k = {K} (RBF, γ = {g:.3g}): within-cluster kernel distance {values['objective']:.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": "Spectral clustering",
    "engine": cs.engine_info("numpy", "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": "kernel_kmeans",
        "affinity": "rbf",
        "gamma": None,
        "n_neighbors": 10,
        "n_init": 5,
        "scale": "standard",
        "missing": "drop",
    }},
})

Here the RBF width was 0.160. The full kernel matrix costs memory that grows with the square of the rows, and a narrow kernel can make any data look separated. Refit over a few widths before trusting the groups.

09

Where each idea stands in CodeSplash

Read
EntryIn CodeSplash
Mini-batch k-means (UCL002)Runs as an option of k-means: Algorithm Mini-batch k-means
CLARA (UCL004)Runs as an option of k-medoids (PAM): Algorithm CLARA
CLARANS (UCL005)Runs as an option of k-medoids (PAM): Algorithm CLARANS
Spherical k-means (UCL013)Runs as an option of k-means: Algorithm Spherical k-means (cosine)
Kernel k-means (UCL014)Runs in CodeSplash: Spectral clustering, Algorithm Kernel k-means (RBF)

Kernel k-means sits under spectral clustering because the two are close relatives: both cut a similarity structure rather than Euclidean space.

10

Check your understanding

Checkpoint

Check yourself

What does mini-batch k-means try to minimize?

Show the answer

Answer: a

The target doesn't change; only the way of getting there does. That's why you compare its final cost with full k-means on the same rows.

Check yourself

Why do the batches need to be random draws from the whole table?

Show the answer

Answer: b

Each center's step shrinks as it sees more rows, so a biased start sticks. Representative batches keep every step pointed at the full-data objective.

Check yourself

CLARA fits PAM on five samples and gets five sets of medoids. How does it choose?

Show the answer

Answer: b

Samples propose; the full table decides. That keeps one unrepresentative sample from deciding the result.

Check yourself

CLARA's overall cost is close to PAM's. What can it still have missed?

Show the answer

Answer: b

A rare group barely moves the total cost. Check groups you care about by name and try larger samples.

Check yourself

You ran CLARANS once and got a low cost. What's the honest next step?

Show the answer

Answer: b

CLARANS is a randomized search with a budget; nothing certifies that its answer is the best. The spread over seeds tells you how much luck was involved.

Check yourself

When does CLARANS stop searching from its current medoids?

Show the answer

Answer: b

That counter (the maximum number of neighbors) is its search budget. Trying every swap is exactly the work PAM does and CLARANS avoids.

Check yourself

Which data suit spherical k-means best?

Show the answer

Answer: b

Spherical k-means throws away vector length. That's right when length is a nuisance (document length) and wrong when it is the signal.

Check yourself

How should you check spherical k-means clusters?

Show the answer

Answer: b

Check in the geometry the method used. A flat projection can merge or split groups that live in many dimensions.

Check yourself

What does kernel k-means need to compute distances to cluster centers?

Show the answer

Answer: b

Every distance to a feature-space mean expands into sums of kernel values, so the map itself is never computed. The price is a kernel matrix with one entry per pair of rows.

Check yourself

Kernel k-means with a very narrow RBF kernel finds tidy clusters. What should you do before trusting them?

Show the answer

Answer: b

A narrow kernel makes every row look far from every other, so separation can come from the kernel rather than the data.

11

Do it on your own data

In the app

Under Find segments, switch Algorithm in k-means (mini-batch, spherical) or k-medoids (PAM) (CLARA, CLARANS), or open Spectral clustering and choose Kernel k-means (RBF). Save the full fit and the approximate one, and compare their costs on the same rows.

Concepts in this lesson