Density peaks and exemplars: DBSCAN to affinity propagation
DBSCAN, OPTICS and HDBSCAN find dense regions, DENCLUE and mean shift climb density peaks, and affinity propagation elects exemplars. Which setting really picks the cluster count, and what noise means.
What runs in CodeSplash
- UCL021DBSCAN Runs in CodeSplash
- UCL022OPTICS Runs in CodeSplash
- UCL023HDBSCAN Runs in CodeSplash
- UCL024DENCLUE Runs in CodeSplash
- UCL025Mean shift Runs in CodeSplash
- UCL026Affinity propagation Runs in CodeSplash
- DBSCAN Verified in Python and R
- OPTICS Verified in Python and R
- HDBSCAN Verified in Python and R
- Mean shift Verified in Python and R
- Affinity propagation Verified in Python and R
You will be able to
- Define core points, reachability and mutual reachability
- Explain why OPTICS gives an ordering, not one partition, and how extraction rules differ
- Name the setting that controls the cluster count in mean shift, DENCLUE and affinity propagation
- Report noise honestly instead of dropping it to flatter a score
Clusters as dense regions
ReadPartition methods put a center in every group. Density methods ask a different question: where are rows packed closely together, with sparse space between? That lets clusters take any shape and leaves room for noise, rows that belong to no dense region.
There's no to set. Instead, every method here has one setting that quietly decides how many clusters you get. Knowing which setting that is, and checking the answer across a range of it, is most of the skill.
DBSCAN: one radius for everyone
ReadDBSCANDBSCANGrows clusters from rows with enough neighbors inside a radius, and labels everything left over as noise. calls a row core when at least min_samples rows lie within radius : . Clusters are core rows linked through each other's neighborhoods, plus border rows they reach; everything else is noise.
DBSCAN with eps = 0.6 and at least 5 neighbors: 2 clusters, 26 noise rows.
- Clusters
- 2
- Mean silhouette
- 0.6419
Plots
View data
| Cluster | PC1 (73%) | PC2 (23%) |
|---|---|---|
| 2 | −2.265 | 0.4800 |
| 2 | −2.081 | −0.6741 |
| 2 | −2.364 | −0.3419 |
| 2 | −2.299 | −0.5974 |
| 2 | −2.390 | 0.6468 |
| 2 | −2.076 | 1.489 |
| 2 | −2.444 | 0.0476 |
| 2 | −2.233 | 0.2231 |
| 2 | −2.335 | −1.115 |
| 2 | −2.184 | −0.4690 |
| 2 | −2.166 | 1.044 |
| 2 | −2.326 | 0.1331 |
| 2 | −2.218 | −0.7287 |
| 2 | −2.633 | −0.9615 |
| 2 | −2.199 | 1.860 |
| -1 | −2.262 | 2.686 |
| 2 | −2.208 | 1.484 |
| 2 | −2.190 | 0.4888 |
| 2 | −1.899 | 1.405 |
| 2 | −2.343 | 1.128 |
| 2 | −1.914 | 0.4089 |
| 2 | −2.207 | 0.9241 |
| 2 | −2.774 | 0.4583 |
| 2 | −1.819 | 0.0856 |
| 2 | −2.227 | 0.1373 |
| 2 | −1.952 | −0.6256 |
| 2 | −2.051 | 0.2422 |
| 2 | −2.169 | 0.5271 |
| 2 | −2.140 | 0.3132 |
| 2 | −2.265 | −0.3377 |
| 2 | −2.140 | −0.5045 |
| 2 | −1.832 | 0.4237 |
| -1 | −2.615 | 1.794 |
| -1 | −2.446 | 2.151 |
| 2 | −2.110 | −0.4602 |
| 2 | −2.208 | −0.2061 |
| 2 | −2.045 | 0.6616 |
| 2 | −2.527 | 0.5923 |
| 2 | −2.430 | −0.9042 |
| 2 | −2.170 | 0.2689 |
| 2 | −2.286 | 0.4417 |
| -1 | −1.858 | −2.337 |
| 2 | −2.554 | −0.4791 |
| 2 | −1.964 | 0.4723 |
| 2 | −2.137 | 1.142 |
| 2 | −2.070 | −0.7111 |
| 2 | −2.385 | 1.120 |
| 2 | −2.394 | −0.3862 |
| 2 | −2.229 | 0.9980 |
| 2 | −2.204 | 0.0092 |
| 1 | 1.102 | 0.8630 |
| 1 | 0.7313 | 0.5946 |
| 1 | 1.241 | 0.6163 |
| 1 | 0.4075 | −1.754 |
| 1 | 1.075 | −0.2084 |
| 1 | 0.3887 | −0.5933 |
| 1 | 0.7465 | 0.7730 |
| -1 | −0.4873 | −1.852 |
| 1 | 0.9279 | 0.0322 |
| 1 | 0.0114 | −1.034 |
First 60 of 150 rows.
eps = 0.6
View data
| eps | k-distance | Rows (sorted) |
|---|---|---|
| false | 0.2371 | 1 |
| false | 0.2371 | 2 |
| false | 0.2489 | 3 |
| false | 0.2489 | 4 |
| false | 0.2601 | 5 |
| false | 0.2601 | 6 |
| false | 0.2601 | 7 |
| false | 0.2601 | 8 |
| false | 0.2663 | 9 |
| false | 0.2663 | 10 |
| false | 0.2712 | 11 |
| false | 0.2712 | 12 |
| false | 0.2839 | 13 |
| false | 0.2865 | 14 |
| false | 0.2885 | 15 |
| false | 0.2885 | 16 |
| false | 0.2915 | 17 |
| false | 0.2970 | 18 |
| false | 0.2983 | 19 |
| false | 0.3110 | 20 |
| false | 0.3129 | 21 |
| false | 0.3129 | 22 |
| false | 0.3242 | 23 |
| false | 0.3242 | 24 |
| false | 0.3342 | 25 |
| false | 0.3377 | 26 |
| false | 0.3497 | 27 |
| false | 0.3530 | 28 |
| false | 0.3530 | 29 |
| false | 0.3543 | 30 |
| false | 0.3574 | 31 |
| false | 0.3578 | 32 |
| false | 0.3592 | 33 |
| false | 0.3592 | 34 |
| false | 0.3637 | 35 |
| false | 0.3637 | 36 |
| false | 0.3657 | 37 |
| false | 0.3677 | 38 |
| false | 0.3679 | 39 |
| false | 0.3754 | 40 |
| false | 0.3768 | 41 |
| false | 0.3768 | 42 |
| false | 0.3872 | 43 |
| false | 0.3891 | 44 |
| false | 0.3960 | 45 |
| false | 0.3960 | 46 |
| false | 0.3964 | 47 |
| false | 0.4015 | 48 |
| false | 0.4075 | 49 |
| false | 0.4075 | 50 |
| false | 0.4075 | 51 |
| false | 0.4114 | 52 |
| false | 0.4114 | 53 |
| false | 0.4225 | 54 |
| false | 0.4255 | 55 |
| false | 0.4255 | 56 |
| false | 0.4255 | 57 |
| false | 0.4287 | 58 |
| false | 0.4293 | 59 |
| false | 0.4308 | 60 |
First 60 of 150 rows.
View data
| Cluster | Silhouette width |
|---|---|
| 1 | 0.7116 |
| 1 | 0.7087 |
| 1 | 0.7065 |
| 1 | 0.7063 |
| 1 | 0.6992 |
| 1 | 0.6992 |
| 1 | 0.6980 |
| 1 | 0.6973 |
| 1 | 0.6971 |
| 1 | 0.6900 |
| 1 | 0.6891 |
| 1 | 0.6889 |
| 1 | 0.6845 |
| 1 | 0.6833 |
| 1 | 0.6813 |
| 1 | 0.6800 |
| 1 | 0.6792 |
| 1 | 0.6749 |
| 1 | 0.6718 |
| 1 | 0.6672 |
| 1 | 0.6633 |
| 1 | 0.6620 |
| 1 | 0.6615 |
| 1 | 0.6615 |
| 1 | 0.6598 |
| 1 | 0.6507 |
| 1 | 0.6504 |
| 1 | 0.6455 |
| 1 | 0.6448 |
| 1 | 0.6446 |
| 1 | 0.6430 |
| 1 | 0.6407 |
| 1 | 0.6400 |
| 1 | 0.6391 |
| 1 | 0.6383 |
| 1 | 0.6355 |
| 1 | 0.6324 |
| 1 | 0.6289 |
| 1 | 0.6281 |
| 1 | 0.6261 |
| 1 | 0.6261 |
| 1 | 0.6245 |
| 1 | 0.6230 |
| 1 | 0.6226 |
| 1 | 0.6064 |
| 1 | 0.6051 |
| 1 | 0.6048 |
| 1 | 0.6033 |
| 1 | 0.6030 |
| 1 | 0.6025 |
| 1 | 0.5973 |
| 1 | 0.5947 |
| 1 | 0.5910 |
| 1 | 0.5803 |
| 1 | 0.5781 |
| 1 | 0.5717 |
| 1 | 0.5701 |
| 1 | 0.5635 |
| 1 | 0.5591 |
| 1 | 0.5433 |
First 60 of 124 rows.
Clusters
| Cluster | Size | Share | sepal_length | sepal_width | petal_length | petal_width |
|---|---|---|---|---|---|---|
| 1 | 78 | 52.0% | 6.188 | 2.913 | 4.819 | 1.668 |
| 2 | 46 | 30.7% | 4.987 | 3.400 | 1.465 | 0.2457 |
The exact R script · R R version 4.5.1 (2025-06-13)
# DBSCAN
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.dbscan 1.1.1 · spec 330194e9d70a77c6
# 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.dbscan/iris_fixed_eps/out-r")
values <- list(n_used = length(rows))
centers <- NULL
center_ids <- NULL
D <- NULL
extra <- list()
tables <- list()
charts <- list()
summary <- NULL
# %% Clustering
MIN_SAMPLES <- 5
EPS <- 0.6
if (MIN_SAMPLES > length(rows)) cs_error("CS_E_TOO_FEW_ROWS", what = sprintf("min_samples = %d", MIN_SAMPLES), min = MIN_SAMPLES, n = length(rows))
# k-distance: distance to the min_samples-th nearest row, the row itself included
kdist <- sort(dbscan::kNNdist(X, k = MIN_SAMPLES - 1))
if (is.null(EPS)) {
EPS <- kdist[cs_ml_kneedle(seq_along(kdist), kdist) + 1L]
if (EPS <= 0) EPS <- if (any(kdist > 0)) kdist[kdist > 0][1] else 1
# The knee is a real k-distance: widen by 1e-9 (relative) so the boundary is inclusive in both engines.
EPS <- EPS * (1 + 1e-9)
warnings <- c(warnings, sprintf("eps chosen automatically at the knee of the k-distance curve: %s.", formatC(EPS, digits = 4, format = "g")))
}
values$eps <- EPS
values$min_samples <- MIN_SAMPLES
fit <- dbscan::dbscan(X, eps = EPS, minPts = MIN_SAMPLES)
raw <- ifelse(fit$cluster == 0L, -1L, fit$cluster - 1L)
show <- cs_ml_even_sample(length(kdist))
charts[[length(charts) + 1L]] <- cs_chart(
"kdistance", "k-distance", sprintf("Distance to the %dth neighbor", MIN_SAMPLES),
list(rank = cs_col("Rows (sorted)", show + 1, "numeric"), distance = cs_col("k-distance", kdist[show + 1L], "numeric"),
chosen = cs_col("eps", abs(kdist[show + 1L] - EPS) <= 1e-8 * EPS, "boolean")),
note = sprintf("eps = %s", formatC(EPS, digits = 4, format = "g"))
)
summary <- sprintf("DBSCAN with eps = %s and at least %d neighbors: %d clusters, %d noise rows.",
formatC(EPS, digits = 4, format = "g"), MIN_SAMPLES, length(setdiff(unique(raw), -1L)), sum(raw == -1L))
# %% 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 = "DBSCAN",
engine = cs_engine_info("dbscan", "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(
eps = 0.6,
min_samples = 5,
scale = "standard",
missing = "drop"
))
))
DBSCAN with eps = 0.6 and at least 5 neighbors: 2 clusters, 26 noise rows.
- Clusters
- 2
- Mean silhouette
- 0.6419
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 | 78 | 52.0% | 6.188 | 2.913 | 4.819 | 1.668 |
| 2 | 46 | 30.7% | 4.987 | 3.400 | 1.465 | 0.2457 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# DBSCAN
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.dbscan 1.1.1 · spec 330194e9d70a77c6
# 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 DBSCAN
from sklearn.neighbors import NearestNeighbors
# %% 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.dbscan/iris_fixed_eps/out-python")
values = {"n_used": len(rows)}
centers = None
center_ids = None
D = None
extra = {}
tables = []
charts = []
summary = None
# %% Clustering
MIN_SAMPLES = 5
EPS = 0.6
if MIN_SAMPLES > len(rows):
cs.cs_error("CS_E_TOO_FEW_ROWS", what=f"min_samples = {MIN_SAMPLES}", min=MIN_SAMPLES, n=len(rows))
# k-distance: distance to the min_samples-th nearest row, the row itself included (= dbscan::kNNdist(k = min_samples - 1))
kdist = np.sort(NearestNeighbors(n_neighbors=MIN_SAMPLES).fit(X).kneighbors(X)[0][:, -1])
if EPS is None:
EPS = float(kdist[csc.kneedle(np.arange(1, len(kdist) + 1), kdist)])
if EPS <= 0:
EPS = float(kdist[kdist > 0][0]) if np.any(kdist > 0) else 1.0
# The knee is a real k-distance, so some pair sits exactly at eps; widen by 1e-9 (relative)
# so the boundary is inclusive in both engines whatever their distance rounding.
EPS *= 1 + 1e-9
warnings.append(f"eps chosen automatically at the knee of the k-distance curve: {EPS:.4g}.")
values["eps"] = EPS
values["min_samples"] = MIN_SAMPLES
raw = DBSCAN(eps=EPS, min_samples=MIN_SAMPLES).fit(X).labels_.astype(np.int64)
show = csc.even_sample(len(kdist))
charts.append(cs.chart(
"kdistance", "k-distance", f"Distance to the {MIN_SAMPLES}th neighbor",
{"rank": cs.col("Rows (sorted)", list(show + 1), "numeric"),
"distance": cs.col("k-distance", list(kdist[show]), "numeric"),
"chosen": cs.col("eps", [bool(abs(kdist[i] - EPS) <= 1e-8 * EPS) for i in show], "boolean")},
note=f"eps = {EPS:.4g}",
))
summary = (
f"DBSCAN with eps = {EPS:.4g} and at least {MIN_SAMPLES} neighbors: {len(set(raw.tolist()) - {-1})} clusters, "
f"{int(np.sum(raw == -1))} noise rows."
)
# %% 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": "DBSCAN",
"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": {
"eps": 0.6,
"min_samples": 5,
"scale": "standard",
"missing": "drop",
}},
})
One radius assumes one density scale. Groups of very different density can't all be found with the same , and in many dimensions distances bunch together so the radius loses its grip.
A silhouette that looks too good
PredictPredict first
On iris, a fixed radius labels many rows noise and reaches a higher silhouette than the automatic radius, which labels few rows noise. Which result is better?
Reveal
You can't tell from silhouette. The fixed radius left out 26 rows and scored 0.642; the automatic one left out 5 and scored 0.600. Silhouette is computed on clustered rows, so dropping hard rows raises it. Always report the noise share beside it.
OPTICS: an ordering, then a rule
ReadOPTICSOPTICSOrders rows so dense regions sit together and records reachability distances — every DBSCAN radius at once. sorts the rows so that dense neighbors come together. Each row gets a reachability , where the core distance is the radius needs to have neighbors. Valleys in the reachability plot are clusters.
The ordering is not a partition. An extraction rule turns it into one, and rules disagree: on iris, one cut gives 2 clusters and 4 noise rows, while the Xi rule gives 4 clusters and 77 noise rows. Compare rules, not algorithm names.
HDBSCAN: keep the clusters that last
ReadHDBSCANHDBSCANTries every density level and keeps the clusters that persist longest, so groups may differ in density. replaces the single radius with a hierarchy. It uses the mutual reachability distance , which pushes sparse rows away from everything, builds a minimum spanning tree, and watches clusters appear and dissolve as the density level rises. It keeps the clusters that persist longest.
HDBSCAN with minimum cluster size 8: 2 clusters, 2 noise rows.
- Clusters
- 2
- Mean silhouette
- 0.5899
Plots
View data
| Cluster | PC1 (73%) | PC2 (23%) |
|---|---|---|
| 2 | −2.265 | 0.4800 |
| 2 | −2.081 | −0.6741 |
| 2 | −2.364 | −0.3419 |
| 2 | −2.299 | −0.5974 |
| 2 | −2.390 | 0.6468 |
| 2 | −2.076 | 1.489 |
| 2 | −2.444 | 0.0476 |
| 2 | −2.233 | 0.2231 |
| 2 | −2.335 | −1.115 |
| 2 | −2.184 | −0.4690 |
| 2 | −2.166 | 1.044 |
| 2 | −2.326 | 0.1331 |
| 2 | −2.218 | −0.7287 |
| 2 | −2.633 | −0.9615 |
| 2 | −2.199 | 1.860 |
| 2 | −2.262 | 2.686 |
| 2 | −2.208 | 1.484 |
| 2 | −2.190 | 0.4888 |
| 2 | −1.899 | 1.405 |
| 2 | −2.343 | 1.128 |
| 2 | −1.914 | 0.4089 |
| 2 | −2.207 | 0.9241 |
| 2 | −2.774 | 0.4583 |
| 2 | −1.819 | 0.0856 |
| 2 | −2.227 | 0.1373 |
| 2 | −1.952 | −0.6256 |
| 2 | −2.051 | 0.2422 |
| 2 | −2.169 | 0.5271 |
| 2 | −2.140 | 0.3132 |
| 2 | −2.265 | −0.3377 |
| 2 | −2.140 | −0.5045 |
| 2 | −1.832 | 0.4237 |
| 2 | −2.615 | 1.794 |
| 2 | −2.446 | 2.151 |
| 2 | −2.110 | −0.4602 |
| 2 | −2.208 | −0.2061 |
| 2 | −2.045 | 0.6616 |
| 2 | −2.527 | 0.5923 |
| 2 | −2.430 | −0.9042 |
| 2 | −2.170 | 0.2689 |
| 2 | −2.286 | 0.4417 |
| 2 | −1.858 | −2.337 |
| 2 | −2.554 | −0.4791 |
| 2 | −1.964 | 0.4723 |
| 2 | −2.137 | 1.142 |
| 2 | −2.070 | −0.7111 |
| 2 | −2.385 | 1.120 |
| 2 | −2.394 | −0.3862 |
| 2 | −2.229 | 0.9980 |
| 2 | −2.204 | 0.0092 |
| 1 | 1.102 | 0.8630 |
| 1 | 0.7313 | 0.5946 |
| 1 | 1.241 | 0.6163 |
| 1 | 0.4075 | −1.754 |
| 1 | 1.075 | −0.2084 |
| 1 | 0.3887 | −0.5933 |
| 1 | 0.7465 | 0.7730 |
| 1 | −0.4873 | −1.852 |
| 1 | 0.9279 | 0.0322 |
| 1 | 0.0114 | −1.034 |
First 60 of 150 rows.
View data
| Cluster | Silhouette width |
|---|---|
| 1 | 0.6756 |
| 1 | 0.6743 |
| 1 | 0.6721 |
| 1 | 0.6705 |
| 1 | 0.6694 |
| 1 | 0.6672 |
| 1 | 0.6670 |
| 1 | 0.6647 |
| 1 | 0.6599 |
| 1 | 0.6542 |
| 1 | 0.6540 |
| 1 | 0.6504 |
| 1 | 0.6476 |
| 1 | 0.6448 |
| 1 | 0.6440 |
| 1 | 0.6434 |
| 1 | 0.6428 |
| 1 | 0.6395 |
| 1 | 0.6322 |
| 1 | 0.6316 |
| 1 | 0.6313 |
| 1 | 0.6313 |
| 1 | 0.6286 |
| 1 | 0.6265 |
| 1 | 0.6227 |
| 1 | 0.6226 |
| 1 | 0.6215 |
| 1 | 0.6202 |
| 1 | 0.6191 |
| 1 | 0.6159 |
| 1 | 0.6155 |
| 1 | 0.6147 |
| 1 | 0.6087 |
| 1 | 0.6054 |
| 1 | 0.6050 |
| 1 | 0.6028 |
| 1 | 0.6021 |
| 1 | 0.6001 |
| 1 | 0.6001 |
| 1 | 0.5995 |
| 1 | 0.5972 |
| 1 | 0.5942 |
| 1 | 0.5897 |
| 1 | 0.5890 |
| 1 | 0.5889 |
| 1 | 0.5886 |
| 1 | 0.5877 |
| 1 | 0.5854 |
| 1 | 0.5819 |
| 1 | 0.5806 |
| 1 | 0.5763 |
| 1 | 0.5741 |
| 1 | 0.5680 |
| 1 | 0.5622 |
| 1 | 0.5577 |
| 1 | 0.5576 |
| 1 | 0.5575 |
| 1 | 0.5540 |
| 1 | 0.5499 |
| 1 | 0.5456 |
First 60 of 148 rows.
Clusters
| Cluster | Size | Share | sepal_length | sepal_width | petal_length | petal_width |
|---|---|---|---|---|---|---|
| 1 | 98 | 65.3% | 6.231 | 2.853 | 4.872 | 1.667 |
| 2 | 50 | 33.3% | 5.006 | 3.428 | 1.462 | 0.2460 |
The exact R script · R R version 4.5.1 (2025-06-13)
# HDBSCAN
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.hdbscan 1.0.1 · spec 062c1c69cdc13ddc
# 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.hdbscan/iris_min8/out-r")
values <- list(n_used = length(rows))
centers <- NULL
center_ids <- NULL
D <- NULL
extra <- list()
tables <- list()
charts <- list()
summary <- NULL
# %% Clustering
MIN_SIZE <- 8
if (MIN_SIZE >= length(rows)) cs_error("CS_E_TOO_FEW_ROWS", what = sprintf("A minimum cluster size of %d", MIN_SIZE), min = MIN_SIZE + 1L, n = length(rows))
values$min_cluster_size <- MIN_SIZE
# minPts = minimum cluster size and the core-distance neighborhood (the row itself included)
hd <- dbscan::hdbscan(X, minPts = MIN_SIZE)
raw <- ifelse(hd$cluster == 0L, -1L, hd$cluster - 1L)
extra$probability <- hd$membership_prob
summary <- sprintf("HDBSCAN with minimum cluster size %d: %d clusters, %d noise rows.",
MIN_SIZE, length(setdiff(unique(raw), -1L)), sum(raw == -1L))
# %% 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 = "HDBSCAN",
engine = cs_engine_info("dbscan", "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(
min_cluster_size = 8,
scale = "standard",
missing = "drop"
))
))
HDBSCAN with minimum cluster size 8: 2 clusters, 2 noise rows.
- Clusters
- 2
- Mean silhouette
- 0.5853
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 | 99 | 66.0% | 6.213 | 2.847 | 4.836 | 1.654 |
| 2 | 49 | 32.7% | 5.016 | 3.451 | 1.465 | 0.2449 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# HDBSCAN
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.hdbscan 1.0.1 · spec 062c1c69cdc13ddc
# 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 HDBSCAN
# %% 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.hdbscan/iris_min8/out-python")
values = {"n_used": len(rows)}
centers = None
center_ids = None
D = None
extra = {}
tables = []
charts = []
summary = None
# %% Clustering
MIN_SIZE = 8
if MIN_SIZE >= len(rows):
cs.cs_error("CS_E_TOO_FEW_ROWS", what=f"A minimum cluster size of {MIN_SIZE}", min=MIN_SIZE + 1, n=len(rows))
values["min_cluster_size"] = MIN_SIZE
# min_samples = min_cluster_size, the row itself included (= dbscan::hdbscan(minPts))
hd = HDBSCAN(min_cluster_size=MIN_SIZE, min_samples=MIN_SIZE, cluster_selection_method="eom", copy=True).fit(X)
raw = hd.labels_.astype(np.int64)
extra["probability"] = hd.probabilities_
summary = (
f"HDBSCAN with minimum cluster size {MIN_SIZE}: {len(set(raw.tolist()) - {-1})} clusters, "
f"{int(np.sum(raw == -1))} noise rows."
)
# %% 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": "HDBSCAN",
"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": {
"min_cluster_size": 8,
"scale": "standard",
"missing": "drop",
}},
})
Membership strength is how long a row stayed in its cluster, not a calibrated probability. Neighbor-count conventions differ between libraries, so the same number may mean slightly different settings elsewhere.
Every radius at once
ExploreAExplorable · HDBSCAN: every radius at once
How can a density method find a tight cluster and a loose one without a single radius?
Can HDBSCAN beat the best single DBSCAN radius on this data?
Data
Also the neighbor count behind each point's core distance.
Commit your prediction above to see the result
Make your prediction to see the result.
Two tight clusters sit beside a loose one, and no single DBSCAN radius suits all three. HDBSCAN builds the whole tree of radii and keeps the clusters that persist longest.
Climbing peaks: mean shift and DENCLUE
ReadMean shiftMean shiftMoves every row uphill on a kernel density estimate; rows that reach the same peak form a cluster. moves each point to the weighted mean of its neighbors, with Gaussian weights . Each step climbs the kernel density estimate; rows that reach the same peak (mode) form a cluster. The bandwidth decides the count: on two rings, a narrow bandwidth found 15 modes.
DENCLUEDENCLUE noise levelPeaks whose density is below a threshold are not clusters; rows that climb to them become noise. adds a noise threshold : peaks whose density is too low are not clusters. With a threshold on the arrests data, 2 of 4 peaks were dropped and their 8 rows became noise. A peak is a feature of the density estimate, not proof of a population.
Affinity propagation: rows vote for exemplars
ReadAffinity propagationAffinity propagationRows exchange messages until some emerge as exemplars; every row joins its most similar exemplar. passes two kinds of messages between rows. The responsibility says how well suits compared with other candidates; the availability collects support for from other rows. Rows with positive become exemplars.
The preference (each row's self-similarity) sets the count: the median similarity gave 9 clusters on iris, while the minimum gave 2 on the arrests data. Messages cost memory for every pair of rows, and hitting the iteration limit is not convergence.
Where each idea stands in CodeSplash
Read| Entry | In CodeSplash |
|---|---|
| DBSCAN (UCL021) | Runs in CodeSplash: DBSCAN |
| OPTICS (UCL022) | Runs in CodeSplash: OPTICS, two extraction rules |
| HDBSCAN (UCL023) | Runs in CodeSplash: HDBSCAN |
| DENCLUE (UCL024) | Runs in CodeSplash: Mean shift with Noise below (share of the top peak) |
| Mean shift (UCL025) | Runs in CodeSplash: Mean shift, Gaussian or flat kernel |
| Affinity propagation (UCL026) | Runs in CodeSplash: Affinity propagation |
DENCLUE and mean shift share the climb but differ in details, such as how attractors connect; the app's version is mean shift plus DENCLUE's noise threshold.
Check your understanding
CheckpointCheck yourself
In DBSCAN, what makes a row a core point?
Show the answer
Answer: b
Core points anchor clusters; border points are reachable from a core point but don't have enough neighbors themselves; the rest are noise.
Check yourself
A dense city cluster and a sparse rural cluster sit in the same data. Why can DBSCAN struggle?
Show the answer
Answer: a
A single ε assumes one density scale. OPTICS and HDBSCAN were built for clusters of different density.
Check yourself
Two reports both say "OPTICS" but give different numbers of clusters on the same data. What should you check first?
Show the answer
Answer: b
OPTICS produces an ordering and a reachability plot; a cut or the Xi rule then picks clusters. Different rules give different partitions from the same ordering.
Check yourself
Row sits very close to core point , closer than 's core distance. What is 's reachability from ?
Show the answer
Answer: b
smooths out tiny distances inside dense regions, so valleys in the plot reflect density rather than chance closeness.
Check yourself
What does HDBSCAN's mutual reachability distance do to a row in a sparse region?
Show the answer
Answer: a
: a sparse row has a large core distance, so it joins clusters late or ends as noise.
Check yourself
An HDBSCAN row has membership strength 0.9. What can you say?
Show the answer
Answer: b
Strength measures persistence in the density hierarchy. Treat it as a ranking of how typical a row is.
Check yourself
What does DENCLUE's threshold ξ add to mode seeking?
Show the answer
Answer: b
Mean shift turns every peak into a cluster, however faint. DENCLUE's threshold drops low-density peaks.
Check yourself
Why must columns be scaled thoughtfully before DENCLUE or mean shift?
Show the answer
Answer: a
A kernel measures distance in the units you give it. Stretch one column and you reshape the density landscape and its peaks.
Check yourself
Mean shift doesn't ask for . What controls how many clusters it finds?
Show the answer
Answer: b
Each cluster is a peak of the kernel density estimate, and the bandwidth decides how smooth that estimate is.
Check yourself
Mean shift finds two clear modes. What have you learned?
Show the answer
Answer: b
A mode is a feature of an estimate. Check how the count changes with bandwidth and whether the groups make sense in the original columns.
Check yourself
You want fewer clusters from affinity propagation. What do you change?
Show the answer
Answer: b
The preference says how much each row wants to be its own exemplar. Lower preferences mean fewer exemplars, but no setting guarantees an exact count.
Check yourself
Affinity propagation stopped at its maximum number of iterations. Is the result converged?
Show the answer
Answer: b
The app stops when the exemplars stay the same for a number of rounds. Hitting the iteration cap means that didn't happen.
Do it on your own data
In the appUnder Find segments, run HDBSCAN first for clusters of any shape with noise; use OPTICS to see the reachability plot and compare extraction rules; try Mean shift with two bandwidths; set the Preference in Affinity propagation to change how many exemplars it elects.
Concepts in this lesson