Shapes, peaks and exemplars: spectral clustering, mean shift and affinity propagation
Three clusterers that drop k-means' round-blob picture. Spectral clustering follows connected shapes, mean shift finds density peaks without a k, and affinity propagation picks real rows as exemplars.
What runs in CodeSplash
- Spectral clustering Verified in Python and R
- Mean shift Verified in Python and R
- Affinity propagation Verified in Python and R
You will be able to
- Use a nearest-neighbor graph to separate rings that k-means splits
- Read the eigenvalue plot to suggest k
- Set a mean-shift bandwidth and a noise level
- Explain how the preference controls affinity propagation's cluster count
Rings that k-means can't separate
ReadPicture two rings, one inside the other. k-means looks for round groups around centers, so it cuts both rings in half. The groups here are connected rather than round: each point is close to its neighbors along its own ring.
Spectral clusteringSpectral clusteringClustering on the leading eigenvectors of a similarity graph, so connected shapes such as rings come out whole. uses that. It links each row to its nearest neighbors, takes the leading eigenvectors of the normalized link matrix and runs k-means on those instead of on the raw columns. Rows on the same ring end up next to each other in that new space.
Spectral clustering with k = 2 on a nearest-neighbor graph; the largest eigenvalue gap suggests k = 8.
- Clusters
- 2
- Mean silhouette
- 0.1181
Plots
View data
| Cluster | x | y |
|---|---|---|
| 1 | −1.786 | −0.4692 |
| 2 | −0.2103 | 0.7162 |
| 1 | 0.6283 | 1.552 |
| 2 | −0.4521 | 0.6855 |
| 2 | 0.3024 | 0.2584 |
| 1 | 0.4395 | −1.697 |
| 2 | 0.4331 | −0.0558 |
| 2 | 0.4492 | −0.3593 |
| 2 | −0.4941 | −0.0709 |
| 2 | −0.4685 | −0.5394 |
| 2 | −0.0596 | 0.7036 |
| 2 | −0.7429 | −0.0588 |
| 1 | −1.062 | −1.517 |
| 1 | −0.3127 | 1.659 |
| 2 | −0.4611 | −0.2223 |
| 2 | 0.0235 | 0.5129 |
| 1 | −1.301 | −1.196 |
| 2 | −0.2439 | −0.6075 |
| 2 | −0.6338 | −0.1665 |
| 1 | 0.6791 | −1.553 |
| 2 | −0.6788 | −0.0244 |
| 1 | 0.5619 | 1.673 |
| 1 | −1.808 | −0.5330 |
| 2 | −0.5496 | 0.3045 |
| 2 | −0.2780 | −0.6040 |
| 2 | −0.2550 | 0.7943 |
| 1 | −1.273 | −1.445 |
| 1 | 0.0430 | −1.968 |
| 2 | −0.0387 | −0.6561 |
| 2 | 0.3572 | 0.2670 |
| 2 | −0.5418 | −0.2096 |
| 1 | −1.222 | −1.386 |
| 1 | 0.0128 | −1.606 |
| 1 | −1.266 | −1.102 |
| 1 | 1.488 | −0.5147 |
| 1 | 1.722 | 0.3375 |
| 2 | −0.2139 | −0.5705 |
| 1 | 0.4204 | −1.897 |
| 2 | −0.4659 | −0.4211 |
| 1 | −1.854 | 0.4413 |
| 1 | 1.742 | 0.0514 |
| 1 | −0.2564 | −1.645 |
| 1 | 0.7345 | −1.555 |
| 1 | 0.3494 | 1.599 |
| 1 | 0.9373 | −1.515 |
| 2 | −0.5004 | 0.4092 |
| 2 | −0.4703 | −0.6429 |
| 2 | −0.3817 | −0.5890 |
| 1 | −1.078 | −1.501 |
| 2 | 0.4095 | 0.1630 |
| 2 | −0.5402 | −0.4220 |
| 1 | 1.534 | −1.208 |
| 1 | 0.8112 | 1.521 |
| 2 | 0.2235 | −0.5717 |
| 1 | 0.6529 | −1.479 |
| 1 | 0.9315 | −1.534 |
| 1 | 1.306 | 0.9765 |
| 1 | 1.271 | 1.018 |
| 1 | 1.416 | 0.9223 |
| 1 | 0.4963 | −1.663 |
First 60 of 300 rows.
The largest gap after eigenvalue 8 suggests k = 8.
View data
| Largest gap | Eigenvalue (rank) | Eigenvalue |
|---|---|---|
| false | 1 | 1 |
| false | 2 | 1 |
| false | 3 | 0.9940 |
| false | 4 | 0.9936 |
| false | 5 | 0.9825 |
| false | 6 | 0.9816 |
| false | 7 | 0.9777 |
| true | 8 | 0.9734 |
| false | 9 | 0.9506 |
| false | 10 | 0.9430 |
View data
| Cluster | Silhouette width |
|---|---|
| 1 | −0.1058 |
| 1 | −0.1103 |
| 1 | −0.1161 |
| 1 | −0.1178 |
| 1 | −0.1204 |
| 1 | −0.1207 |
| 1 | −0.1213 |
| 1 | −0.1218 |
| 1 | −0.1242 |
| 1 | −0.1270 |
| 1 | −0.1278 |
| 1 | −0.1282 |
| 1 | −0.1297 |
| 1 | −0.1299 |
| 1 | −0.1308 |
| 1 | −0.1308 |
| 1 | −0.1315 |
| 1 | −0.1325 |
| 1 | −0.1332 |
| 1 | −0.1339 |
| 1 | −0.1346 |
| 1 | −0.1354 |
| 1 | −0.1362 |
| 1 | −0.1366 |
| 1 | −0.1381 |
| 1 | −0.1384 |
| 1 | −0.1399 |
| 1 | −0.1400 |
| 1 | −0.1419 |
| 1 | −0.1426 |
| 1 | −0.1438 |
| 1 | −0.1449 |
| 1 | −0.1451 |
| 1 | −0.1452 |
| 1 | −0.1456 |
| 1 | −0.1474 |
| 1 | −0.1475 |
| 1 | −0.1481 |
| 1 | −0.1493 |
| 1 | −0.1495 |
| 1 | −0.1510 |
| 1 | −0.1513 |
| 1 | −0.1518 |
| 1 | −0.1518 |
| 1 | −0.1538 |
| 1 | −0.1539 |
| 1 | −0.1543 |
| 1 | −0.1544 |
| 1 | −0.1546 |
| 1 | −0.1548 |
| 1 | −0.1556 |
| 1 | −0.1559 |
| 1 | −0.1562 |
| 1 | −0.1584 |
| 1 | −0.1586 |
| 1 | −0.1588 |
| 1 | −0.1602 |
| 1 | −0.1607 |
| 1 | −0.1607 |
| 1 | −0.1608 |
First 60 of 300 rows.
Clusters
| Cluster | Size | Share | x | y |
|---|---|---|---|---|
| 1 | 180 | 60.0% | 0.2747 | 0.0557 |
| 2 | 120 | 40.0% | −0.0334 | 0.0052 |
- The similarity graph falls into 2 disconnected parts; each part needs at least one cluster.
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 638b2a0c45f9d88a
# Dataset: clu2_rings (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("x", "y")
LABEL <- "ring" # known groups (external validation only)
ROW_ID <- NULL # row labels for charts
SEED <- 42
KINDS <- list(
x = "numeric",
y = "numeric"
)
LEVELS <- list(
)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/clu2_rings.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/rings_knn/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 <- 2
ALGO <- "spectral"
AFFINITY <- "knn"
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 = 10, 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 = 10, 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 = 2,
algorithm = "spectral",
affinity = "knn",
gamma = NULL,
n_neighbors = 10,
n_init = 10,
scale = "standard",
missing = "drop"
))
))
Spectral clustering with k = 2 on a nearest-neighbor graph; the largest eigenvalue gap suggests k = 8.
- Clusters
- 2
- Mean silhouette
- 0.1181
To keep this page light, the plots are shown once, under the R tab.
Clusters
| Cluster | Size | Share | x | y |
|---|---|---|---|---|
| 1 | 180 | 60.0% | 0.2747 | 0.0557 |
| 2 | 120 | 40.0% | −0.0334 | 0.0052 |
- The similarity graph falls into 2 disconnected parts; each part needs at least one cluster.
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 638b2a0c45f9d88a
# Dataset: clu2_rings (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 = ["x", "y"]
LABEL = "ring" # known groups (external validation only)
ROW_ID = None # row labels for charts
SEED = 42
KINDS = {
"x": "numeric",
"y": "numeric",
}
LEVELS = {
}
df = pd.read_parquet("tests/parity/fixtures/clu2_rings.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/rings_knn/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 = 2
ALGO = "spectral"
AFFINITY = "knn"
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=10, 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=10, 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": 2,
"algorithm": "spectral",
"affinity": "knn",
"gamma": None,
"n_neighbors": 10,
"n_init": 10,
"scale": "standard",
"missing": "drop",
}},
})
With a 10-nearest-neighbor graph, the clusters match the two rings: the adjusted Rand index with the true ring is 1.
Let the eigenvalues suggest k
ReadThe eigenvalues of the normalized link matrix drop from 1. A large drop after the -th eigenvalue (the eigengapEigengapThe drop between consecutive eigenvalues of the normalized similarity matrix; a large drop after the k-th suggests k clusters.) suggests clusters.
View data
| number of clusters k | score | criterion | recommended |
|---|---|---|---|
| 2 | 1009.44 | within-cluster SS | false |
| 2 | 0.4790 | silhouette | false |
| 2 | 1.406 | gap statistic | false |
| 3 | 604.67 | within-cluster SS | false |
| 3 | 0.5390 | silhouette | false |
| 3 | 1.667 | gap statistic | false |
| 4 | 266.55 | within-cluster SS | true |
| 4 | 0.5690 | silhouette | true |
| 4 | 1.883 | gap statistic | true |
| 5 | 212.94 | within-cluster SS | false |
| 5 | 0.5610 | silhouette | false |
| 5 | 1.900 | gap statistic | false |
| 6 | 172.92 | within-cluster SS | false |
| 6 | 0.4890 | silhouette | false |
| 6 | 1.880 | gap statistic | false |
| 7 | 158.52 | within-cluster SS | false |
| 7 | 0.4350 | silhouette | false |
| 7 | 1.844 | gap statistic | false |
| 8 | 143.15 | within-cluster SS | false |
| 8 | 0.3800 | silhouette | false |
| 8 | 1.835 | gap statistic | false |
| 9 | 125.91 | within-cluster SS | false |
| 9 | 0.3080 | silhouette | false |
| 9 | 1.793 | gap statistic | false |
On iris with the Gaussian kernel, the largest gap suggests = 2. That's the honest answer for iris measurements: two of the species overlap.
Peaks of density with mean shift
ReadMean shiftMean shiftMoves every row uphill on a kernel density estimate; rows that reach the same peak form a cluster. needs no . It moves every row uphill on a smoothed density, step by step, until the row reaches a peak. Rows that reach the same peak form a cluster.
What you set instead is the bandwidth, the radius of the smoothing. A smaller bandwidth finds more, narrower peaks.
Mean shift (gaussian kernel, bandwidth 0.6) found 2 density peaks.
- Clusters
- 2
- Mean silhouette
- 0.7460
Plots
View data
| Center | Cluster | eruptions | waiting |
|---|---|---|---|
| false | 1 | 0.0985 | 0.5971 |
| false | 2 | −1.481 | −1.245 |
| false | 1 | −0.1359 | 0.2287 |
| false | 2 | −1.058 | −0.6556 |
| false | 1 | 0.9174 | 1.039 |
| false | 2 | −0.5309 | −1.171 |
| false | 1 | 1.064 | 1.260 |
| false | 1 | 0.0985 | 1.039 |
| false | 2 | −1.350 | −1.466 |
| false | 1 | 0.7568 | 1.039 |
| false | 2 | −1.452 | −1.245 |
| false | 1 | 0.3767 | 0.9656 |
| false | 1 | 0.6252 | 0.5234 |
| false | 2 | −1.525 | −1.761 |
| false | 1 | 1.064 | 0.8919 |
| false | 2 | −1.159 | −1.393 |
| false | 2 | −1.525 | −0.6556 |
| false | 1 | 1.152 | 0.9656 |
| false | 2 | −1.657 | −1.393 |
| false | 1 | 0.6690 | 0.5971 |
| false | 2 | −1.481 | −1.466 |
| false | 2 | −1.525 | −1.761 |
| false | 1 | −0.0332 | 0.5234 |
| false | 1 | −0.3693 | −0.1398 |
| false | 1 | 0.9174 | 0.2287 |
| false | 1 | 0.0985 | 0.8919 |
| false | 2 | −1.335 | −1.171 |
| false | 1 | 0.5225 | 0.3760 |
| false | 1 | 0.3179 | 0.5234 |
| false | 1 | 0.8297 | 0.5971 |
| false | 1 | 0.7129 | 0.1550 |
| false | 1 | 0.8595 | 0.4497 |
| false | 1 | −0.1060 | −0.3609 |
| false | 1 | 0.4786 | 0.6708 |
| false | 1 | 0.3030 | 0.2287 |
| false | 2 | −1.291 | −1.393 |
| false | 2 | −1.423 | −1.687 |
| false | 1 | 1.181 | 0.6708 |
| false | 2 | −1.452 | −0.8767 |
| false | 1 | 1.137 | 1.408 |
| false | 1 | 0.7568 | 0.6708 |
| false | 2 | −1.409 | −0.9504 |
| false | 1 | 0.9473 | 0.9656 |
| false | 2 | −1.525 | −0.9504 |
| false | 1 | 0.9174 | 0.1550 |
| false | 1 | −0.1499 | 0.8919 |
| false | 1 | 0.3030 | −0.5083 |
| false | 2 | −1.218 | −1.319 |
| false | 1 | 1.005 | 0.8182 |
| false | 2 | −1.306 | −0.8767 |
| false | 1 | 1.152 | 0.3024 |
| false | 1 | 1.078 | 1.408 |
| false | 2 | −1.452 | −1.245 |
| false | 1 | 1.181 | 0.6708 |
| false | 2 | −1.540 | −1.245 |
| false | 1 | 1.225 | 0.8919 |
| false | 1 | 0.2012 | 0.0076 |
| false | 2 | −1.598 | −0.5083 |
| false | 1 | 0.9473 | 0.4497 |
| false | 1 | 0.7278 | 0.7445 |
First 60 of 274 rows.
View data
| Cluster | Silhouette width |
|---|---|
| 1 | 0.8239 |
| 1 | 0.8236 |
| 1 | 0.8234 |
| 1 | 0.8234 |
| 1 | 0.8231 |
| 1 | 0.8228 |
| 1 | 0.8227 |
| 1 | 0.8224 |
| 1 | 0.8219 |
| 1 | 0.8213 |
| 1 | 0.8207 |
| 1 | 0.8204 |
| 1 | 0.8204 |
| 1 | 0.8203 |
| 1 | 0.8194 |
| 1 | 0.8194 |
| 1 | 0.8185 |
| 1 | 0.8181 |
| 1 | 0.8180 |
| 1 | 0.8176 |
| 1 | 0.8169 |
| 1 | 0.8169 |
| 1 | 0.8165 |
| 1 | 0.8149 |
| 1 | 0.8144 |
| 1 | 0.8141 |
| 1 | 0.8137 |
| 1 | 0.8132 |
| 1 | 0.8130 |
| 1 | 0.8130 |
| 1 | 0.8127 |
| 1 | 0.8122 |
| 1 | 0.8112 |
| 1 | 0.8106 |
| 1 | 0.8099 |
| 1 | 0.8098 |
| 1 | 0.8058 |
| 1 | 0.8053 |
| 1 | 0.8052 |
| 1 | 0.8047 |
| 1 | 0.8044 |
| 1 | 0.8041 |
| 1 | 0.8035 |
| 1 | 0.8034 |
| 1 | 0.8031 |
| 1 | 0.8030 |
| 1 | 0.8020 |
| 1 | 0.8011 |
| 1 | 0.8005 |
| 1 | 0.7983 |
| 1 | 0.7982 |
| 1 | 0.7979 |
| 1 | 0.7978 |
| 1 | 0.7970 |
| 1 | 0.7958 |
| 1 | 0.7958 |
| 1 | 0.7956 |
| 1 | 0.7944 |
| 1 | 0.7944 |
| 1 | 0.7939 |
First 60 of 272 rows.
Clusters
| Cluster | Size | Share | eruptions | waiting |
|---|---|---|---|---|
| 1 | 175 | 64.3% | 4.291 | 79.989 |
| 2 | 97 | 35.7% | 2.038 | 54.495 |
The exact R script · R R version 4.5.1 (2025-06-13)
# Mean shift
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.meanshift 1.0.0 · spec f804f74424893500
# Dataset: h_faithful (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("eruptions", "waiting")
LABEL <- NULL # known groups (external validation only)
ROW_ID <- NULL # row labels for charts
SEED <- 42
KINDS <- list(
eruptions = "numeric",
waiting = "numeric"
)
LEVELS <- list(
)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/h_faithful.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.meanshift/faithful_gaussian/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
KERNEL <- "gaussian"
BANDWIDTH <- 0.6
SHARE <- as.numeric(0)
if (length(rows) > 3000) stop("Mean shift climbs from every row against every row; use it on at most 3,000 rows.")
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)
h <- if (!is.null(BANDWIDTH)) as.numeric(BANDWIDTH) else cs_ml_bandwidth_auto(D2)
if (!(h > 0)) cs_error("CS_E_UNDEFINED", what = "The automatic bandwidth", reason = "most rows are identical, so the typical distance between rows is 0 (set a bandwidth)")
fit <- cs_ml_meanshift(X, h, KERNEL, max_iter = 500, tol = 1e-8, min_share = SHARE)
raw <- fit$labels
if (!fit$converged_all) warnings <- c(warnings, "Some rows were still climbing at the step limit; their cluster is where they stopped.")
values$bandwidth <- h
values$n_modes <- nrow(fit$modes)
values$n_noise_modes <- sum(fit$noise)
values$iterations <- fit$iterations
kept <- which(!fit$noise) - 1L
centers <- fit$modes[kept + 1L, , drop = FALSE]
center_ids <- kept
canon <- cs_ml_canonical(raw)
for (j in kept) values[[sprintf("density[%d]", canon[which(raw == j)[1]])]] <- fit$density[j + 1L]
summary <- paste0(sprintf("Mean shift (%s kernel, bandwidth %s) found %d density peak%s", KERNEL, formatC(h, digits = 3, format = "g"),
values$n_modes, if (values$n_modes != 1) "s" else ""),
if (values$n_noise_modes > 0) sprintf("; %d low peak%s became noise", values$n_noise_modes, if (values$n_noise_modes != 1) "s" else "") else "",
".")
# %% 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 = "Mean shift",
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(
bandwidth = 0.6,
kernel = "gaussian",
min_density_share = 0,
max_iter = 500,
scale = "standard",
missing = "drop"
))
))
Mean shift (gaussian kernel, bandwidth 0.6) found 2 density peaks.
- Clusters
- 2
- Mean silhouette
- 0.7460
To keep this page light, the plots are shown once, under the R tab.
Clusters
| Cluster | Size | Share | eruptions | waiting |
|---|---|---|---|---|
| 1 | 175 | 64.3% | 4.291 | 79.989 |
| 2 | 97 | 35.7% | 2.038 | 54.495 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Mean shift
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.meanshift 1.0.0 · spec f804f74424893500
# Dataset: h_faithful (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 = ["eruptions", "waiting"]
LABEL = None # known groups (external validation only)
ROW_ID = None # row labels for charts
SEED = 42
KINDS = {
"eruptions": "numeric",
"waiting": "numeric",
}
LEVELS = {
}
df = pd.read_parquet("tests/parity/fixtures/h_faithful.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.meanshift/faithful_gaussian/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
KERNEL = "gaussian"
BANDWIDTH = 0.6
SHARE = float(0)
if len(rows) > 3000:
raise ValueError("Mean shift climbs from every row against every row; use it on at most 3,000 rows.")
if not np.any(np.ptp(X, axis=0) > 0):
cs.cs_error("CS_E_CONSTANT", column=", ".join(FEATURES))
D2 = cpart.pairwise_sq(X)
h = float(BANDWIDTH) if BANDWIDTH is not None else cpart.bandwidth_auto(D2)
if not h > 0:
cs.cs_error("CS_E_UNDEFINED", what="The automatic bandwidth", reason="most rows are identical, so the typical distance between rows is 0 (set a bandwidth)")
fit = cpart.meanshift(X, h, KERNEL, max_iter=500, tol=1e-8, min_share=SHARE)
raw = fit["labels"]
if not fit["converged_all"]:
warnings.append("Some rows were still climbing at the step limit; their cluster is where they stopped.")
values["bandwidth"] = h
values["n_modes"] = int(len(fit["modes"]))
values["n_noise_modes"] = int(np.sum(fit["noise"]))
values["iterations"] = fit["iterations"]
kept = [j for j in range(len(fit["modes"])) if not fit["noise"][j]]
centers = fit["modes"][kept]
center_ids = np.array(kept, dtype=np.int64)
canon = csc.canonical(raw)
for j in kept:
values[f"density[{int(canon[np.flatnonzero(raw == j)[0]])}]"] = float(fit["density"][j])
summary = (
f"Mean shift ({KERNEL} kernel, bandwidth {h:.3g}) found {values['n_modes']} density peak{'s' if values['n_modes'] != 1 else ''}"
+ (f"; {values['n_noise_modes']} low peak{'s' if values['n_noise_modes'] != 1 else ''} became noise" if values["n_noise_modes"] else "")
+ "."
)
# %% 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": "Mean shift",
"engine": cs.engine_info("numpy", "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": {
"bandwidth": 0.6,
"kernel": "gaussian",
"min_density_share": 0,
"max_iter": 500,
"scale": "standard",
"missing": "drop",
}},
})
On the Old Faithful eruptions, a bandwidth of 0.600 (in standardized units) finds 2 peaks: short eruptions with short waits, and long eruptions with long waits.
Small peaks as noise
ReadA minor peak with a few rows is rarely a segment. The DENCLUE idea marks peaks below a density threshold as noise. Here you set the threshold as a share of the highest peak.
Mean shift (gaussian kernel, bandwidth 0.6) found 4 density peaks; 2 low peaks became noise.
- Clusters
- 2
- Mean silhouette
- 0.4487
Plots
View data
| Center | Cluster | Row | PC1 (62%) | PC2 (25%) |
|---|---|---|---|---|
| false | -1 | Alabama | 0.9856 | −1.133 |
| false | -1 | Alaska | 1.950 | −1.073 |
| false | 2 | Arizona | 1.763 | 0.7460 |
| false | 1 | Arkansas | −0.1414 | −1.120 |
| false | 2 | California | 2.524 | 1.543 |
| false | 2 | Colorado | 1.515 | 0.9876 |
| false | 1 | Connecticut | −1.359 | 1.089 |
| false | 1 | Delaware | 0.0477 | 0.3254 |
| false | 2 | Florida | 3.013 | −0.0392 |
| false | -1 | Georgia | 1.639 | −1.279 |
| false | 1 | Hawaii | −0.9127 | 1.570 |
| false | 1 | Idaho | −1.640 | −0.2110 |
| false | 2 | Illinois | 1.379 | 0.6818 |
| false | 1 | Indiana | −0.5055 | 0.1516 |
| false | 1 | Iowa | −2.254 | 0.1041 |
| false | 1 | Kansas | −0.7969 | 0.2702 |
| false | 1 | Kentucky | −0.7509 | −0.9584 |
| false | -1 | Louisiana | 1.565 | −0.8711 |
| false | 1 | Maine | −2.397 | −0.3764 |
| false | 2 | Maryland | 1.763 | −0.4277 |
| false | 1 | Massachusetts | −0.4862 | 1.474 |
| false | 2 | Michigan | 2.108 | 0.1554 |
| false | 1 | Minnesota | −1.693 | 0.6323 |
| false | -1 | Mississippi | 0.9965 | −2.394 |
| false | 1 | Missouri | 0.6968 | 0.2634 |
| false | 1 | Montana | −1.185 | −0.5369 |
| false | 1 | Nebraska | −1.266 | 0.1940 |
| false | 2 | Nevada | 2.874 | 0.7756 |
| false | 1 | New Hampshire | −2.384 | 0.0181 |
| false | 1 | New Jersey | 0.1816 | 1.450 |
| false | 2 | New Mexico | 1.980 | −0.1428 |
| false | 2 | New York | 1.683 | 0.8232 |
| false | -1 | North Carolina | 1.123 | −2.228 |
| false | 1 | North Dakota | −2.992 | −0.5991 |
| false | 1 | Ohio | −0.2260 | 0.7422 |
| false | 1 | Oklahoma | −0.3118 | 0.2879 |
| false | 1 | Oregon | 0.0591 | 0.5414 |
| false | 1 | Pennsylvania | −0.8884 | 0.5711 |
| false | 1 | Rhode Island | −0.8638 | 1.492 |
| false | -1 | South Carolina | 1.321 | −1.933 |
| false | 1 | South Dakota | −1.988 | −0.8233 |
| false | -1 | Tennessee | 0.9997 | −0.8603 |
| false | 2 | Texas | 1.355 | 0.4125 |
| false | 1 | Utah | −0.5506 | 1.472 |
| false | 1 | Vermont | −2.801 | −1.402 |
| false | 1 | Virginia | −0.0963 | −0.1997 |
| false | 1 | Washington | −0.2169 | 0.9701 |
| false | 1 | West Virginia | −2.109 | −1.425 |
| false | 1 | Wisconsin | −2.080 | 0.6113 |
| false | 1 | Wyoming | −0.6294 | −0.3210 |
| true | 1 | center 1 | −0.6695 | 0.2537 |
| true | 2 | center 2 | 1.724 | 0.2269 |
View data
| Cluster | Silhouette width |
|---|---|
| 1 | 0.6014 |
| 1 | 0.5994 |
| 1 | 0.5954 |
| 1 | 0.5951 |
| 1 | 0.5880 |
| 1 | 0.5823 |
| 1 | 0.5781 |
| 1 | 0.5614 |
| 1 | 0.5578 |
| 1 | 0.5445 |
| 1 | 0.5338 |
| 1 | 0.5234 |
| 1 | 0.5142 |
| 1 | 0.5061 |
| 1 | 0.4783 |
| 1 | 0.4777 |
| 1 | 0.4622 |
| 1 | 0.4286 |
| 1 | 0.4121 |
| 1 | 0.3854 |
| 1 | 0.3534 |
| 1 | 0.3395 |
| 1 | 0.3261 |
| 1 | 0.3224 |
| 1 | 0.3170 |
| 1 | 0.2800 |
| 1 | 0.2647 |
| 1 | 0.1547 |
| 1 | 0.1473 |
| 1 | 0.0658 |
| 1 | −0.2147 |
| 2 | 0.6333 |
| 2 | 0.6087 |
| 2 | 0.5854 |
| 2 | 0.5680 |
| 2 | 0.5667 |
| 2 | 0.5614 |
| 2 | 0.5542 |
| 2 | 0.5178 |
| 2 | 0.4840 |
| 2 | 0.4569 |
| 2 | 0.4268 |
Clusters
| Cluster | Size | Share | Murder | Assault | UrbanPop | Rape |
|---|---|---|---|---|---|---|
| 1 | 31 | 62.0% | 5.003 | 116.48 | 63.839 | 16.339 |
| 2 | 11 | 22.0% | 11.055 | 264.09 | 79.091 | 32.618 |
The exact R script · R R version 4.5.1 (2025-06-13)
# Mean shift
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.meanshift 1.0.0 · spec cc55554e844fcd78
# Dataset: ml_usarrests (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
FEATURES <- c("Murder", "Assault", "UrbanPop", "Rape")
LABEL <- NULL # known groups (external validation only)
ROW_ID <- "state" # row labels for charts
SEED <- 42
KINDS <- list(
Murder = "numeric",
Assault = "numeric",
UrbanPop = "numeric",
Rape = "numeric"
)
LEVELS <- list(
)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_usarrests.parquet", col_select = unique(c(FEATURES, LABEL, ROW_ID))))
n_input <- nrow(df)
prep <- cs_ml_cluster_prepare(df, FEATURES, KINDS, LEVELS, missing = "drop", scale = "standard")
X <- prep$X; rows <- prep$rows; names_ <- prep$names; frame <- prep$frame
warnings <- list()
if (length(rows) < n_input) {
warnings <- c(warnings, sprintf("%d of %d rows were left out because a feature was missing.", n_input - length(rows), n_input))
}
if (length(rows) < 3) stop("Clustering needs at least three rows with every feature present.")
truth <- if (!is.null(LABEL)) as.character(frame[[LABEL]]) else NULL
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.meanshift/usarrests_noise/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
KERNEL <- "gaussian"
BANDWIDTH <- 0.6
SHARE <- as.numeric(0.5)
if (length(rows) > 3000) stop("Mean shift climbs from every row against every row; use it on at most 3,000 rows.")
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)
h <- if (!is.null(BANDWIDTH)) as.numeric(BANDWIDTH) else cs_ml_bandwidth_auto(D2)
if (!(h > 0)) cs_error("CS_E_UNDEFINED", what = "The automatic bandwidth", reason = "most rows are identical, so the typical distance between rows is 0 (set a bandwidth)")
fit <- cs_ml_meanshift(X, h, KERNEL, max_iter = 500, tol = 1e-8, min_share = SHARE)
raw <- fit$labels
if (!fit$converged_all) warnings <- c(warnings, "Some rows were still climbing at the step limit; their cluster is where they stopped.")
values$bandwidth <- h
values$n_modes <- nrow(fit$modes)
values$n_noise_modes <- sum(fit$noise)
values$iterations <- fit$iterations
kept <- which(!fit$noise) - 1L
centers <- fit$modes[kept + 1L, , drop = FALSE]
center_ids <- kept
canon <- cs_ml_canonical(raw)
for (j in kept) values[[sprintf("density[%d]", canon[which(raw == j)[1]])]] <- fit$density[j + 1L]
summary <- paste0(sprintf("Mean shift (%s kernel, bandwidth %s) found %d density peak%s", KERNEL, formatC(h, digits = 3, format = "g"),
values$n_modes, if (values$n_modes != 1) "s" else ""),
if (values$n_noise_modes > 0) sprintf("; %d low peak%s became noise", values$n_noise_modes, if (values$n_noise_modes != 1) "s" else "") else "",
".")
# %% 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 = "Mean shift",
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(
bandwidth = 0.6,
kernel = "gaussian",
min_density_share = 0.5,
max_iter = 500,
scale = "standard",
missing = "drop"
))
))
Mean shift (gaussian kernel, bandwidth 0.6) found 4 density peaks; 2 low peaks became noise.
- Clusters
- 2
- Mean silhouette
- 0.4487
To keep this page light, the plots are shown once, under the R tab.
Clusters
| Cluster | Size | Share | Murder | Assault | UrbanPop | Rape |
|---|---|---|---|---|---|---|
| 1 | 31 | 62.0% | 5.003 | 116.48 | 63.839 | 16.339 |
| 2 | 11 | 22.0% | 11.055 | 264.09 | 79.091 | 32.618 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Mean shift
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.meanshift 1.0.0 · spec cc55554e844fcd78
# Dataset: ml_usarrests (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import cluster as csc
from codesplash.stats.rng import Rng
from codesplash.ml import cluster_partitional as cpart
# %% Data
FEATURES = ["Murder", "Assault", "UrbanPop", "Rape"]
LABEL = None # known groups (external validation only)
ROW_ID = "state" # row labels for charts
SEED = 42
KINDS = {
"Murder": "numeric",
"Assault": "numeric",
"UrbanPop": "numeric",
"Rape": "numeric",
}
LEVELS = {
}
df = pd.read_parquet("tests/parity/fixtures/ml_usarrests.parquet", columns=list(dict.fromkeys(FEATURES + [c for c in (LABEL, ROW_ID) if c])))
n_input = len(df)
X, rows, names, frame = csc.prepare(df, FEATURES, KINDS, LEVELS, missing="drop", scale="standard")
warnings = []
if len(rows) < n_input:
warnings.append(f"{n_input - len(rows)} of {n_input} rows were left out because a feature was missing.")
if len(rows) < 3:
raise ValueError("Clustering needs at least three rows with every feature present.")
truth = frame[LABEL].astype("object").to_numpy() if LABEL else None
out = csml.out_dir("target/academy-parity/run-8142/discover.meanshift/usarrests_noise/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
KERNEL = "gaussian"
BANDWIDTH = 0.6
SHARE = float(0.5)
if len(rows) > 3000:
raise ValueError("Mean shift climbs from every row against every row; use it on at most 3,000 rows.")
if not np.any(np.ptp(X, axis=0) > 0):
cs.cs_error("CS_E_CONSTANT", column=", ".join(FEATURES))
D2 = cpart.pairwise_sq(X)
h = float(BANDWIDTH) if BANDWIDTH is not None else cpart.bandwidth_auto(D2)
if not h > 0:
cs.cs_error("CS_E_UNDEFINED", what="The automatic bandwidth", reason="most rows are identical, so the typical distance between rows is 0 (set a bandwidth)")
fit = cpart.meanshift(X, h, KERNEL, max_iter=500, tol=1e-8, min_share=SHARE)
raw = fit["labels"]
if not fit["converged_all"]:
warnings.append("Some rows were still climbing at the step limit; their cluster is where they stopped.")
values["bandwidth"] = h
values["n_modes"] = int(len(fit["modes"]))
values["n_noise_modes"] = int(np.sum(fit["noise"]))
values["iterations"] = fit["iterations"]
kept = [j for j in range(len(fit["modes"])) if not fit["noise"][j]]
centers = fit["modes"][kept]
center_ids = np.array(kept, dtype=np.int64)
canon = csc.canonical(raw)
for j in kept:
values[f"density[{int(canon[np.flatnonzero(raw == j)[0]])}]"] = float(fit["density"][j])
summary = (
f"Mean shift ({KERNEL} kernel, bandwidth {h:.3g}) found {values['n_modes']} density peak{'s' if values['n_modes'] != 1 else ''}"
+ (f"; {values['n_noise_modes']} low peak{'s' if values['n_noise_modes'] != 1 else ''} became noise" if values["n_noise_modes"] else "")
+ "."
)
# %% 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": "Mean shift",
"engine": cs.engine_info("numpy", "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": {
"bandwidth": 0.6,
"kernel": "gaussian",
"min_density_share": 0.5,
"max_iter": 500,
"scale": "standard",
"missing": "drop",
}},
})
With the threshold at half the top peak's density, 2 low peaks become noise and 8 states are left unassigned.
Exemplars with affinity propagation
ReadAffinity propagationAffinity propagationRows exchange messages until some emerge as exemplars; every row joins its most similar exemplar. also finds the number of clusters itself, but it centers every cluster on a real row, an exemplar. Rows exchange two kinds of messages until a stable set of exemplars emerges:
- responsibility: how well suited a candidate is to represent a row;
- availability: how much a row should rely on that candidate.
Each row's preference (its similarity to itself) controls how readily it becomes an exemplar. The median similarity gives a moderate number. The minimum gives few.
Affinity propagation picked 9 exemplar rows (preference -6.24, the median similarity) in 24 rounds.
- Clusters
- 9
- Mean silhouette
- 0.3413
Plots
View data
| Center | Cluster | PC1 (73%) | PC2 (23%) |
|---|---|---|---|
| false | 1 | −2.265 | 0.4800 |
| false | 3 | −2.081 | −0.6741 |
| false | 3 | −2.364 | −0.3419 |
| false | 3 | −2.299 | −0.5974 |
| false | 1 | −2.390 | 0.6468 |
| false | 1 | −2.076 | 1.489 |
| false | 3 | −2.444 | 0.0476 |
| false | 3 | −2.233 | 0.2231 |
| false | 3 | −2.335 | −1.115 |
| false | 3 | −2.184 | −0.4690 |
| false | 1 | −2.166 | 1.044 |
| false | 3 | −2.326 | 0.1331 |
| false | 3 | −2.218 | −0.7287 |
| false | 3 | −2.633 | −0.9615 |
| false | 1 | −2.199 | 1.860 |
| false | 1 | −2.262 | 2.686 |
| false | 1 | −2.208 | 1.484 |
| false | 1 | −2.190 | 0.4888 |
| false | 1 | −1.899 | 1.405 |
| false | 1 | −2.343 | 1.128 |
| false | 1 | −1.914 | 0.4089 |
| false | 1 | −2.207 | 0.9241 |
| false | 1 | −2.774 | 0.4583 |
| false | 3 | −1.819 | 0.0856 |
| false | 3 | −2.227 | 0.1373 |
| false | 3 | −1.952 | −0.6256 |
| false | 3 | −2.051 | 0.2422 |
| false | 1 | −2.169 | 0.5271 |
| false | 1 | −2.140 | 0.3132 |
| false | 3 | −2.265 | −0.3377 |
| false | 3 | −2.140 | −0.5045 |
| false | 1 | −1.832 | 0.4237 |
| false | 1 | −2.615 | 1.794 |
| false | 1 | −2.446 | 2.151 |
| false | 3 | −2.110 | −0.4602 |
| false | 3 | −2.208 | −0.2061 |
| false | 1 | −2.045 | 0.6616 |
| false | 1 | −2.527 | 0.5923 |
| false | 3 | −2.430 | −0.9042 |
| false | 1 | −2.170 | 0.2689 |
| false | 1 | −2.286 | 0.4417 |
| false | 3 | −1.858 | −2.337 |
| false | 3 | −2.554 | −0.4791 |
| false | 1 | −1.964 | 0.4723 |
| false | 1 | −2.137 | 1.142 |
| false | 3 | −2.070 | −0.7111 |
| false | 1 | −2.385 | 1.120 |
| false | 3 | −2.394 | −0.3862 |
| false | 1 | −2.229 | 0.9980 |
| false | 3 | −2.204 | 0.0092 |
| false | 7 | 1.102 | 0.8630 |
| false | 7 | 0.7313 | 0.5946 |
| false | 7 | 1.241 | 0.6163 |
| false | 6 | 0.4075 | −1.754 |
| false | 2 | 1.075 | −0.2084 |
| false | 4 | 0.3887 | −0.5933 |
| false | 7 | 0.7465 | 0.7730 |
| false | 6 | −0.4873 | −1.852 |
| false | 7 | 0.9279 | 0.0322 |
| false | 4 | 0.0114 | −1.034 |
First 60 of 159 rows.
View data
| Cluster | Silhouette width |
|---|---|
| 1 | 0.5690 |
| 1 | 0.5688 |
| 1 | 0.5625 |
| 1 | 0.5618 |
| 1 | 0.5592 |
| 1 | 0.5549 |
| 1 | 0.5326 |
| 1 | 0.5303 |
| 1 | 0.5219 |
| 1 | 0.5074 |
| 1 | 0.5042 |
| 1 | 0.4918 |
| 1 | 0.4245 |
| 1 | 0.4022 |
| 1 | 0.3659 |
| 1 | 0.3308 |
| 1 | 0.3191 |
| 1 | 0.2885 |
| 1 | 0.2836 |
| 1 | 0.2157 |
| 1 | 0.1719 |
| 1 | 0.1682 |
| 1 | 0.1667 |
| 1 | 0.1153 |
| 1 | 0.0666 |
| 1 | −0.0286 |
| 2 | 0.3760 |
| 2 | 0.3552 |
| 2 | 0.3516 |
| 2 | 0.3453 |
| 2 | 0.3023 |
| 2 | 0.3023 |
| 2 | 0.2214 |
| 2 | 0.2168 |
| 2 | 0.2143 |
| 2 | 0.2100 |
| 2 | 0.1799 |
| 2 | 0.1745 |
| 2 | 0.1722 |
| 2 | 0.1714 |
| 2 | 0.1687 |
| 2 | 0.1654 |
| 2 | 0.1597 |
| 2 | 0.1250 |
| 2 | 0.1156 |
| 2 | 0.0395 |
| 2 | −0.0917 |
| 2 | −0.1082 |
| 2 | −0.1472 |
| 2 | −0.1804 |
| 2 | −0.2032 |
| 3 | 0.6503 |
| 3 | 0.6468 |
| 3 | 0.6348 |
| 3 | 0.6337 |
| 3 | 0.6261 |
| 3 | 0.6244 |
| 3 | 0.6139 |
| 3 | 0.6110 |
| 3 | 0.6046 |
First 60 of 150 rows.
Clusters
| Cluster | Size | Share | sepal_length | sepal_width | petal_length | petal_width |
|---|---|---|---|---|---|---|
| 1 | 26 | 17.3% | 5.242 | 3.700 | 1.469 | 0.2692 |
| 2 | 25 | 16.7% | 6.120 | 2.784 | 5.060 | 1.780 |
| 3 | 24 | 16.0% | 4.750 | 3.133 | 1.454 | 0.2208 |
| 4 | 18 | 12.0% | 5.722 | 2.828 | 4.189 | 1.294 |
| 5 | 16 | 10.7% | 6.612 | 3.175 | 5.513 | 2.256 |
| 6 | 15 | 10.0% | 5.513 | 2.353 | 3.893 | 1.193 |
| 7 | 14 | 9.3% | 6.571 | 3.079 | 4.750 | 1.514 |
| 8 | 9 | 6.0% | 7.433 | 2.922 | 6.267 | 1.989 |
| 9 | 3 | 2.0% | 7.600 | 3.733 | 6.400 | 2.233 |
The exact R script · R R version 4.5.1 (2025-06-13)
# Affinity propagation
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.affinity_prop 1.0.0 · spec d39e53eb5c539b90
# 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.affinity_prop/iris_median/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
PREFERENCE <- "median"
DISTANCE <- "auto"
n <- length(rows)
if (n > 3000) stop("Affinity propagation keeps three n × n message matrices; use it on at most 3,000 rows.")
if (DISTANCE == "auto") DISTANCE <- if (any(unlist(KINDS[FEATURES]) != "numeric")) "gower" else "euclidean"
if (DISTANCE == "gower") {
D <- cs_ml_gower(frame, FEATURES, KINDS) # = cluster::daisy(metric = "gower")
dimnames(D) <- NULL
S <- -(D * D)
} else if (DISTANCE == "manhattan") {
D <- matrix(0, n, n)
for (cc in seq_len(ncol(X))) D <- D + abs(outer(X[, cc], X[, cc], "-"))
S <- -(D * D)
} else {
S <- -cs_ml_sq_dists(X, X) # similarity = minus the squared Euclidean distance (Frey & Dueck)
}
off <- S[upper.tri(S)]
if (!any(off < 0)) cs_error("CS_E_CONSTANT", column = paste(FEATURES, collapse = ", "))
pref <- if (PREFERENCE == "median") stats::median(off) else min(off)
fit <- cs_ml_affinity_propagation(S, pref, damping = as.numeric(0.5), max_iter = 200, convergence_iter = 15)
if (!length(fit$exemplars)) cs_error("CS_E_NO_CONVERGENCE", what = "Affinity propagation (no exemplar emerged; raise the damping or the iteration limit)")
if (!fit$converged) warnings <- c(warnings, "The messages were still changing at the iteration limit; the exemplars may not be final (raise the damping).")
raw <- fit$labels
ex <- fit$exemplars
centers <- X[ex + 1L, , drop = FALSE]
values$preference_value <- pref
values$iterations <- fit$iterations
Sp <- S
diag(Sp) <- pref
values$net_similarity <- sum(Sp[cbind(seq_len(n), ex[raw + 1L] + 1L)])
canon <- cs_ml_canonical(raw)
for (e in ex) values[[sprintf("exemplar_row[%d]", canon[e + 1L])]] <- rows[e + 1L]
extra$exemplar <- (seq_len(n) - 1L) %in% ex
summary <- sprintf("Affinity propagation picked %d exemplar rows (preference %s, the %s similarity) in %d rounds.",
length(ex), formatC(pref, digits = 3, format = "g"), PREFERENCE, fit$iterations)
# %% 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 = "Affinity propagation",
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(
preference = "median",
distance = "auto",
damping = 0.5,
max_iter = 200,
convergence_iter = 15,
scale = "standard",
missing = "drop"
))
))
Affinity propagation picked 9 exemplar rows (preference -6.24, the median similarity) in 24 rounds.
- Clusters
- 9
- Mean silhouette
- 0.3413
To keep this page light, the plots are shown once, under the R tab.
Clusters
| Cluster | Size | Share | sepal_length | sepal_width | petal_length | petal_width |
|---|---|---|---|---|---|---|
| 1 | 26 | 17.3% | 5.242 | 3.700 | 1.469 | 0.2692 |
| 2 | 25 | 16.7% | 6.120 | 2.784 | 5.060 | 1.780 |
| 3 | 24 | 16.0% | 4.750 | 3.133 | 1.454 | 0.2208 |
| 4 | 18 | 12.0% | 5.722 | 2.828 | 4.189 | 1.294 |
| 5 | 16 | 10.7% | 6.613 | 3.175 | 5.512 | 2.256 |
| 6 | 15 | 10.0% | 5.513 | 2.353 | 3.893 | 1.193 |
| 7 | 14 | 9.3% | 6.571 | 3.079 | 4.750 | 1.514 |
| 8 | 9 | 6.0% | 7.433 | 2.922 | 6.267 | 1.989 |
| 9 | 3 | 2.0% | 7.600 | 3.733 | 6.400 | 2.233 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Affinity propagation
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.affinity_prop 1.0.0 · spec d39e53eb5c539b90
# 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.affinity_prop/iris_median/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
PREFERENCE = "median"
DISTANCE = "auto"
n = len(rows)
if n > 3000:
raise ValueError("Affinity propagation keeps three n × n message matrices; use it on at most 3,000 rows.")
if DISTANCE == "auto":
DISTANCE = "gower" if any(KINDS[f] != "numeric" for f in FEATURES) else "euclidean"
if DISTANCE == "gower":
D = csc.gower(frame, FEATURES, KINDS) # = cluster::daisy(metric = "gower")
S = -(D * D)
elif DISTANCE == "manhattan":
D = np.zeros((n, n))
for c in range(X.shape[1]):
D += np.abs(X[:, c][:, None] - X[:, c][None, :])
S = -(D * D)
else:
S = -cpart.pairwise_sq(X) # similarity = minus the squared Euclidean distance (Frey & Dueck)
off = S[np.triu_indices(n, 1)]
if not np.any(off < 0):
cs.cs_error("CS_E_CONSTANT", column=", ".join(FEATURES))
pref = float(np.median(off)) if PREFERENCE == "median" else float(np.min(off))
fit = cpart.affinity_propagation(S, pref, damping=float(0.5), max_iter=200, convergence_iter=15)
if len(fit["exemplars"]) == 0:
cs.cs_error("CS_E_NO_CONVERGENCE", what="Affinity propagation (no exemplar emerged; raise the damping or the iteration limit)")
if not fit["converged"]:
warnings.append("The messages were still changing at the iteration limit; the exemplars may not be final (raise the damping).")
raw = fit["labels"]
ex = fit["exemplars"]
centers = X[ex]
values["preference_value"] = pref
values["iterations"] = fit["iterations"]
Sp = S.copy()
Sp[np.arange(n), np.arange(n)] = pref
values["net_similarity"] = float(np.sum(Sp[np.arange(n), ex[raw]]))
canon = csc.canonical(raw)
for j, e in enumerate(ex):
values[f"exemplar_row[{int(canon[e])}]"] = int(rows[e])
extra["exemplar"] = np.isin(np.arange(n), ex)
summary = f"Affinity propagation picked {len(ex)} exemplar rows (preference {pref:.3g}, the {PREFERENCE} similarity) in {fit['iterations']} rounds."
# %% 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": "Affinity propagation",
"engine": cs.engine_info("numpy", "scipy", "numpy", "pandas"),
"n": len(rows),
"summary": summary,
"statistics": [
{"key": "k", "label": "Clusters", "value": k, "format": "integer"},
{"key": "silhouette", "label": "Mean silhouette", "value": values["silhouette"]},
],
"tables": tables,
"values": values,
"charts": charts,
"warnings": warnings,
"artifacts": [{"key": "labels", "path": path, "format": "parquet"}],
"model": {"kind": "clusterer", "features": names, "params": {
"preference": "median",
"distance": "auto",
"damping": 0.5,
"max_iter": 200,
"convergence_iter": 15,
"scale": "standard",
"missing": "drop",
}},
})
With the median preference, iris gets 9 exemplars. With the minimum preference, USArrests gets 2.
Check your understanding
CheckpointCheck yourself
Why does spectral clustering separate two concentric rings when k-means doesn't?
Show the answer
Answer: b
k-means looks for round groups around centers. Spectral clustering embeds the neighbor graph first, so connected shapes come out whole.
Check yourself
The eigenvalues are 1.00, 0.99, 0.62, 0.58, 0.55. How many clusters do they suggest?
Show the answer
Answer: b
The eigengap heuristic picks just before the largest drop: from 0.99 to 0.62.
Check yourself
Mean shift finds one big cluster where you expected three. What do you change?
Show the answer
Answer: b
Mean shift has no . A wide bandwidth smooths separate peaks into one, so a smaller one lets them show.
Check yourself
What does the noise threshold of 0.3 do in mean shift?
Show the answer
Answer: a
The threshold compares each peak's density with the densest peak, as DENCLUE does with its noise level.
Check yourself
You want fewer affinity propagation clusters. What do you change?
Show the answer
Answer: b
The preference is each row's self-similarity. Lower values make rows less eager to become exemplars, so fewer emerge. Damping only steadies the messages.
Check yourself
What is an exemplar in affinity propagation?
Show the answer
Answer: b
Like PAM's medoids, exemplars are actual rows, so you can open them and read them as typical cases.
Do it on your own data
In the appUnder Find segments, try Spectral clustering with the nearest-neighbor graph when your groups look like curved shapes, or Mean shift when you don't want to choose .
Recap
Recap- Spectral clustering follows connectivity; the eigenvalue plot's largest gap suggests .
- Mean shift climbs to density peaks: the bandwidth sets how many, and a threshold turns minor peaks into noise.
- Affinity propagation picks real rows as exemplars; the preference sets how many.
Concepts in this lesson