Skip to content

CDiscover · discover.meanshift

Mean shift

Where are the peaks of density, and which rows climb to each one?

Mean shift moves every row uphill on a kernel density estimate until it reaches a peak (mode); rows that reach the same peak form a cluster, so the number of clusters comes from the data and the bandwidth rather than from a chosen k. A Gaussian or flat kernel sets how the neighborhood is weighed. A DENCLUE-style threshold can mark rows that climb to minor, low-density peaks as noise. Both engines run the same written-out climb from every row.

Verified in Python and R Python and R agree to 6 decimals Also called mean-shift, mode seeking, DENCLUE…

A real result

Example “Faithful gaussian”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

Mean shiftRecorded · Python and R agreeRecorded 2026-11-25 · 22 values compared
R

Mean shift (gaussian kernel, bandwidth 0.6) found 2 density peaks.

Clusters
2
Mean silhouette
0.7460

Plots

ClustersWhich rows group together, and how well separated are the groups?
View data
CenterClustereruptionswaiting
false10.09850.5971
false2−1.481−1.245
false1−0.13590.2287
false2−1.058−0.6556
false10.91741.039
false2−0.5309−1.171
false11.0641.260
false10.09851.039
false2−1.350−1.466
false10.75681.039
false2−1.452−1.245
false10.37670.9656
false10.62520.5234
false2−1.525−1.761
false11.0640.8919
false2−1.159−1.393
false2−1.525−0.6556
false11.1520.9656
false2−1.657−1.393
false10.66900.5971
false2−1.481−1.466
false2−1.525−1.761
false1−0.03320.5234
false1−0.3693−0.1398
false10.91740.2287
false10.09850.8919
false2−1.335−1.171
false10.52250.3760
false10.31790.5234
false10.82970.5971
false10.71290.1550
false10.85950.4497
false1−0.1060−0.3609
false10.47860.6708
false10.30300.2287
false2−1.291−1.393
false2−1.423−1.687
false11.1810.6708
false2−1.452−0.8767
false11.1371.408
false10.75680.6708
false2−1.409−0.9504
false10.94730.9656
false2−1.525−0.9504
false10.91740.1550
false1−0.14990.8919
false10.3030−0.5083
false2−1.218−1.319
false11.0050.8182
false2−1.306−0.8767
false11.1520.3024
false11.0781.408
false2−1.452−1.245
false11.1810.6708
false2−1.540−1.245
false11.2250.8919
false10.20120.0076
false2−1.598−0.5083
false10.94730.4497
false10.72780.7445

First 60 of 274 rows.

Silhouette widthsHow well does each row fit its cluster compared with the next-nearest cluster?
View data
ClusterSilhouette width
10.8239
10.8236
10.8234
10.8234
10.8231
10.8228
10.8227
10.8224
10.8219
10.8213
10.8207
10.8204
10.8204
10.8203
10.8194
10.8194
10.8185
10.8181
10.8180
10.8176
10.8169
10.8169
10.8165
10.8149
10.8144
10.8141
10.8137
10.8132
10.8130
10.8130
10.8127
10.8122
10.8112
10.8106
10.8099
10.8098
10.8058
10.8053
10.8052
10.8047
10.8044
10.8041
10.8035
10.8034
10.8031
10.8030
10.8020
10.8011
10.8005
10.7983
10.7982
10.7979
10.7978
10.7970
10.7958
10.7958
10.7956
10.7944
10.7944
10.7939

First 60 of 272 rows.

Clusters

ClusterSizeShareeruptionswaiting
117564.3%4.29179.989
29735.7%2.03854.495
Python

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

ClusterSizeShareeruptionswaiting
117564.3%4.29179.989
29735.7%2.03854.495

Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.

Worked examples in the app

  • Faithful gaussianh_faithful · features: eruptions, waiting
  • Iris auto flatml_iris · features: sepal_length, sepal_width, petal_length, petal_width · label: species
  • Usarrests noiseml_usarrests · features: Murder, Assault, UrbanPop, Rape · id: state
  • Rings narrowclu2_rings · features: x, y · label: ring
  • Degenerate n3h_faithful · features: eruptions, waiting

In the guides

Where it sits in the decision guides

  • Density-based clustering (DBSCAN, HDBSCAN) · DS & ML Decision Guide · Discover — find structure without labels

What you need

Featuresnumeric / categorical / boolean · 1–50 columns
Variables that define similarity (best with a few numbers). Categories enter as 0/1 indicator columns.
Known groupscategorical / boolean · 0–1 column
Optional — compared with the clusters (adjusted Rand index, AMI, NMI); never used to fit.
Row labelscategorical / numeric · 0–1 column
Optional names shown on the chart points.

Choices you make

model

Bandwidthdefault —

Kernel radius in the (scaled) feature units: smaller finds more, narrower peaks. The default is the mean distance to the 30% nearest rows.

Kerneldefault gaussian

How neighbors are weighed while climbing.

  • Gaussian(default) — Weights fall off smoothly with distance (SD = bandwidth); smooth density, the usual choice.
  • Flat (within the bandwidth) — Every row within the bandwidth counts equally, farther rows not at all; scikit-learn's MeanShift kernel.
Noise below (share of the top peak)default 0

DENCLUE's noise level ξ as a share of the highest peak's density: rows that climb to a lower peak become noise. 0 keeps every peak.

Advanced

Maximum stepsdefault 500

Upper limit on climbing steps per row.

preprocess

Scale numbersdefault standard

Standardize numbers so each counts equally in distances; turn off only when columns already share one unit.

  • Standardize (population SD)(default) — Rescales each number to mean 0 and SD 1 so every column counts equally in distances; the safe choice.
  • No scaling — Keeps raw values, so the bandwidth is in the columns' own units; pick it only when columns share one unit.
Missing valuesdefault drop

Rows with missing values are left out, or filled with the column median (categories get none).

  • Leave the row out(default) — Leaves out rows with a missing value; the clean choice when few are missing.
  • Fill with the median (categories → none) — Fills numeric gaps with the median and leaves category gaps as no category; keeps every row, at some cost to the shape.

What it reports

k
How many groups, studies or clusters the analysis used. Many methods are less reliable when k is small.
n_used
How many independent units the analysis used; it sets precision and power.
n_noise
How many independent units the analysis used; it sets precision and power.
bandwidth
Moves every row uphill on a kernel density estimate; rows that reach the same peak form a cluster.
n_modes
Moves every row uphill on a kernel density estimate; rows that reach the same peak form a cluster.
n_noise_modes
Peaks whose density is below a threshold are not clusters; rows that climb to them become noise.
iterations
Moves every row uphill on a kernel density estimate; rows that reach the same peak form a cluster.
silhouette
How well each point sits in its cluster compared with the nearest other cluster, from −1 to 1.
calinski_harabasz
Between-cluster spread over within-cluster spread. Higher means tighter, better-separated clusters.
davies_bouldin
How much each cluster overlaps its most similar neighbor, on average. Lower is better; 0 is the floor.

Per group, level or term: size[<cluster>], center[<cluster>,<design column>], mean[<cluster>,<feature>], density[<cluster>], ari, ami, nmi

Python and R

Python and R agree to 6 decimals (relative tolerance 1e-6). Python uses numpy; R uses codesplashr.

Default traps between the two languages

  • Both engines climb from every row with the same updates until a step is shorter than 1e-8 × the bandwidth, merge end points within half a bandwidth of a denser one, and place each mode at the mean of its rows' end points, so the modes agree to the climbing tolerance. scikit-learn's MeanShift (flat kernel only) stops at 1e-3 × the bandwidth, merges within a full bandwidth and assigns rows to the nearest mode instead of the mode they climb to.
Python

The exact script CodeSplash ran for example “Faithful gaussian” · 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",
    }},
})
R

The exact script CodeSplash ran for example “Faithful gaussian” · 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"
  ))
))

Sources

  • Comaniciu D, Meer P (2002). Mean shift: a robust approach toward feature space analysis. IEEE TPAMI 24(5):603–619.
  • Fukunaga K, Hostetler L (1975). The estimation of the gradient of a density function. IEEE Transactions on Information Theory 21(1):32–40.
  • Hinneburg A, Keim DA (1998). An efficient approach to clustering in large multimedia databases with noise (DENCLUE). Proc. KDD, 58–65.

From the CodeSplash method registry · discover.meanshift v1.0.0.