Skip to content

CDiscover · discover.pam

k-medoids (PAM)

Which rows fall into k groups around representative rows?

Partitioning Around Medoids (Kaufman & Rousseeuw): BUILD then SWAP until no exchange of a medoid with another row lowers the total dissimilarity. Every cluster is centered on a real row (its medoid), dissimilarities can be Gower's for mixed numeric and categorical data, and the result is deterministic — Python (kmedoids) and R (cluster::pam) find the same medoids. For large data, CLARA runs PAM on samples and keeps the medoids that serve all rows best; CLARANS searches random medoid swaps. Both draw from the shared random stream, so the two engines agree.

Verified in Python and R Python and R agree to 10 decimals

A real result

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

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

PAM with k = 3 on euclidean dissimilarities: average dissimilarity to the medoid 0.879.

Clusters
3
Mean silhouette
0.4566

Plots

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

First 60 of 153 rows.

Silhouette widthsHow well does each row fit its cluster compared with the next-nearest cluster?
View data
ClusterSilhouette width
10.5827
10.5787
10.5772
10.5746
10.5745
10.5681
10.5586
10.5568
10.5523
10.5495
10.5480
10.5452
10.5431
10.5311
10.5149
10.5074
10.4678
10.4630
10.4629
10.4570
10.4540
10.4364
10.4277
10.4256
10.4212
10.4204
10.4114
10.4038
10.3992
10.3986
10.3970
10.3907
10.3860
10.3756
10.3643
10.3620
10.3574
10.3543
10.3395
10.3392
10.3392
10.3209
10.2825
10.2435
10.2117
10.2098
10.1877
10.1756
10.1464
10.1460
10.1405
10.0627
10.0477
10.0073
1−0.0679
20.7323
20.7315
20.7293
20.7268
20.7264

First 60 of 150 rows.

Clusters

ClusterSizeSharesepal_lengthsepal_widthpetal_lengthpetal_width
15536.7%5.8132.7004.3761.413
25033.3%5.0063.4281.4620.2460
34530.0%6.8113.0825.5531.998
Python

PAM with k = 3 on euclidean dissimilarities: average dissimilarity to the medoid 0.879.

Clusters
3
Mean silhouette
0.4566

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

Clusters

ClusterSizeSharesepal_lengthsepal_widthpetal_lengthpetal_width
15536.7%5.8132.7004.3761.413
25033.3%5.0063.4281.4620.2460
34530.0%6.8113.0825.5531.998

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

  • Regress k not below rowsml_iris · features: sepal_length, sepal_width, petal_length, petal_width
  • Iris euclideanml_iris · features: sepal_length, sepal_width, petal_length, petal_width · label: species
  • Penguins gowerml_penguins · features: bill_len, flipper_len, island, sex · label: species
  • Usarrests manhattanml_usarrests · features: Murder, Assault, UrbanPop, Rape · id: state
  • Iris claraml_iris · features: sepal_length, sepal_width, petal_length, petal_width · label: species
  • Penguins clara gowerml_penguins · features: bill_len, flipper_len, island, sex · label: species
  • Usarrests claransml_usarrests · features: Murder, Assault, UrbanPop, Rape · id: state
  • Iris clara whole sampleml_iris · features: sepal_length, sepal_width, petal_length, petal_width · label: species

In the guides

Where it sits in the decision guides

  • Clustering (k-means, hierarchical) · DS & ML Decision Guide · Discover — find structure without labels

What you need

Featuresnumeric / categorical / boolean · 1–200 columns
Variables that define similarity.
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

Clusters (k)default 3

Number of clusters (medoids).

Algorithmdefault pam

PAM swaps medoids over all rows; CLARA and CLARANS trade a little fit for much less work on large data.

  • PAM (all rows)(default) — BUILD then SWAP on every pairwise dissimilarity; the exact original method, up to 5,000 rows.
  • CLARA (samples, large data) — Runs PAM on several random samples and keeps the medoids with the lowest average dissimilarity over all rows; no row limit.
  • CLARANS (random swaps) — Tries random medoid swaps and keeps those that help, from a few random starts; up to 5,000 rows.
Samplesdefault 5

Random samples CLARA clusters; the one whose medoids fit all rows best wins.

Rows per sampledefault 0

Rows in each CLARA sample; 0 uses 40 + 2k (Kaufman and Rousseeuw's default).

Local searchesdefault 2

Independent CLARANS searches from random medoids; the lowest-cost result wins.

Dissimilaritydefault auto

Dissimilarity between rows: Gower handles mixed types; Euclidean and Manhattan suit numbers.

  • Automatic (Gower when there are categories, else Euclidean)(default) — Uses Gower when any column is categorical and Euclidean otherwise; the usual choice.
  • Euclidean on the scaled design — Straight-line distance on scaled numbers; the standard for numeric data, but sensitive to outliers.
  • Manhattan on the scaled design — Sums absolute differences on scaled numbers; less sensitive to outliers than Euclidean.
  • Gower (mixed types) — Averages a per-column difference across numbers and categories; pick it for mixed data.

Advanced

Failed swaps before stoppingdefault 0

A search stops after this many random swaps in a row fail to help; 0 uses max(250, 1.25% of k(n − k)).

Maximum swap roundsdefault 100

Upper limit on swap rounds when improving the medoids.

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 wide-ranging columns dominate distances; 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.
cost
A number for how unlike two rows are; distance-based tests ask their question of this matrix of all pairs.
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>], medoid_row[<cluster>], center[<cluster>,<design column>], mean[<cluster>,<feature>], ari, ami, nmi, sample_size, best_sample, maxneighbor

Python and R

Python and R agree to 10 decimals (relative tolerance 1e-9). Python uses kmedoids, scipy; R uses cluster.

Default traps between the two languages

  • CLARA and CLARANS draw their samples and swaps from the shared stream and are written-out twins (CLARA runs the same PAM on each sample), so the medoids agree exactly.
  • Both run the original PAM (BUILD + best-improvement SWAP) on the same dissimilarity matrix (Gower from the codesplash twin in both engines), so the medoids agree; exactly tied swap gains could resolve differently.
Python

The exact script CodeSplash ran for example “Iris euclidean” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0

# k-medoids (PAM)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.pam 1.1.0 · spec 895c8174e064ca7b
# Dataset: ml_iris (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd

import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import cluster as csc
from codesplash.stats.rng import Rng
import kmedoids
from scipy.spatial.distance import cdist

# %% Data
FEATURES = ["sepal_length", "sepal_width", "petal_length", "petal_width"]
LABEL = "species"  # known groups (external validation only)
ROW_ID = None  # row labels for charts
SEED = 42
KINDS = {
    "sepal_length": "numeric",
    "sepal_width": "numeric",
    "petal_length": "numeric",
    "petal_width": "numeric",
}
LEVELS = {
}
df = pd.read_parquet("tests/parity/fixtures/ml_iris.parquet", columns=list(dict.fromkeys(FEATURES + [c for c in (LABEL, ROW_ID) if c])))
n_input = len(df)
X, rows, names, frame = csc.prepare(df, FEATURES, KINDS, LEVELS, missing="drop", scale="standard")
warnings = []
if len(rows) < n_input:
    warnings.append(f"{n_input - len(rows)} of {n_input} rows were left out because a feature was missing.")
if len(rows) < 3:
    raise ValueError("Clustering needs at least three rows with every feature present.")
truth = frame[LABEL].astype("object").to_numpy() if LABEL else None
out = csml.out_dir("target/academy-parity/run-8142/discover.pam/iris_euclidean/out-python")
values = {"n_used": len(rows)}
centers = None
center_ids = None
D = None
extra = {}
tables = []
charts = []
summary = None

# %% Clustering
K = 3
if K >= len(rows):
    cs.cs_error("CS_E_TOO_FEW_ROWS", what=f"PAM with k = {K}", min=K + 1, n=len(rows))
if len(rows) > 5000:
    raise ValueError("PAM keeps a full dissimilarity matrix; use it on at most 5,000 rows (or k-means).")
DISTANCE = "auto"
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")
else:
    D = cdist(X, X, metric="cityblock" if DISTANCE == "manhattan" else "euclidean")
# Original PAM: BUILD initialization, then best-improvement SWAP (= cluster::pam(pamonce = 0)).
res = kmedoids.pam(D, K, max_iter=100, init="build")
raw = np.asarray(res.labels, dtype=np.int64)
medoids = np.asarray(res.medoids, dtype=np.int64)
centers = X[medoids]
values["cost"] = float(D[np.arange(len(rows)), medoids[raw]].sum()) / len(rows)  # average dissimilarity to the medoid
canon = csc.canonical(raw)
for m in medoids:
    values[f"medoid_row[{int(canon[m])}]"] = int(rows[m])
extra["distance"] = D[np.arange(len(rows)), medoids[raw]]
summary = f"PAM with k = {K} on {DISTANCE} dissimilarities: average dissimilarity to the medoid {values['cost']:.3f}."

# %% Canonical labels and validation
labels = csc.canonical(raw)
ids = [int(c) for c in sorted(set(labels.tolist())) if c != -1]
k = len(ids)
values["k"] = k
values["n_noise"] = int(np.sum(labels == -1))
if centers is not None:
    # reorder centers to canonical ids: the raw id of each canonical cluster
    raw_of = {c: raw[np.flatnonzero(labels == c)[0]] for c in ids}
    pos = {int(r): i for i, r in enumerate(center_ids if center_ids is not None else range(len(centers)))}
    centers = np.array([centers[pos[int(raw_of[c])]] for c in ids])
    for c, row in zip(ids, centers):
        for name, v in zip(names, row):
            values[f"center[{c},{name}]"] = float(v)
for c, m in csc.sizes(labels).items():
    values[f"size[{c}]"] = m
check = csc.validation(X, labels, truth, D=D, cap=3000, seed=SEED)
widths, picked = check.pop("_widths")
values.update(check)
# per-cluster means of numeric features in their own units (interpretation)
profile_rows = []
for c in ids:
    member = labels == c
    row = {"cluster": c, "size": int(member.sum()), "share": float(member.mean())}
    for f in FEATURES:
        if KINDS[f] == "numeric":
            m = float(np.nanmean(pd.to_numeric(frame[f], errors="coerce").to_numpy(dtype=np.float64)[member]))
            row[f] = m
            values[f"mean[{c},{f}]"] = m
        else:
            top = pd.Series(frame[f].astype("object").to_numpy()[member]).dropna().astype(str).value_counts()
            row[f] = f"{top.index[0]} ({top.iloc[0] / member.sum():.0%})" if len(top) else ""
    profile_rows.append(row)
tables.insert(0, {
    "key": "clusters",
    "title": "Clusters",
    "columns": [
        {"key": "cluster", "label": "Cluster", "type": "integer"},
        {"key": "size", "label": "Size", "type": "integer"},
        {"key": "share", "label": "Share", "type": "percent"},
    ]
    + [{"key": f, "label": f, "type": "number" if KINDS[f] == "numeric" else "string"} for f in FEATURES],
    "rows": profile_rows,
})

# %% Labels file and charts
path = csc.write_labels(out, rows, labels, **extra)
name_of = lambda c: str(c)  # noqa: E731  — noise stays "-1" (drawn gray, listed last)
P, C, axes = csc.project2(X, centers, names)
show = csc.even_sample(len(rows))
point_labels = [str(v) for v in frame[ROW_ID].astype("object").to_numpy()[show]] if ROW_ID else None
xs, ys = list(P[show, 0]), list(P[show, 1])
cl = [name_of(c) for c in labels[show]]
cent = [False] * len(show)
lab = point_labels
if C is not None:
    xs += list(C[:, 0])
    ys += list(C[:, 1])
    cl += [name_of(c) for c in ids]
    cent += [True] * len(ids)
    lab = None if lab is None else lab + [f"center {c}" for c in ids]
level_names = [str(c) for c in ids] + (["-1"] if values["n_noise"] else [])
charts.insert(0, cs.chart(
    "clusters", "cluster-scatter", "Clusters",
    {
        "x": cs.col(axes[0], xs, "numeric"),
        "y": cs.col(axes[1], ys, "numeric"),
        "cluster": cs.col("Cluster", cl, "categorical", levels=level_names),
        "centroid": cs.col("Center", cent, "boolean") if C is not None else None,
        "label": cs.col("Row", lab, "categorical") if lab is not None else None,
    },
    note=None if len(show) == len(rows) else f"{len(show):,} of {len(rows):,} rows shown.",
))
if not np.isnan(values["silhouette"]):
    wl = labels[picked]
    order = np.lexsort((-widths, wl))
    charts.append(cs.chart(
        "silhouette", "silhouette-plot", "Silhouette widths",
        {"cluster": cs.col("Cluster", [str(c) for c in wl[order]], "categorical", levels=[str(c) for c in ids]),
         "width": cs.col("Silhouette width", list(widths[order]), "numeric")},
        note=None if len(picked) == int(np.sum(labels != -1)) else f"{len(picked):,} rows sampled for the silhouette.",
    ))

# %% Result
if summary is None:
    summary = f"{k} cluster{'s' if k != 1 else ''} in {len(rows):,} rows"
    if values["n_noise"]:
        summary += f" ({values['n_noise']:,} noise points)"
    if not np.isnan(values["silhouette"]):
        summary += f"; mean silhouette {values['silhouette']:.2f}"
    summary += "."
cs.publish({
    "title": "k-medoids (PAM)",
    "engine": cs.engine_info("kmedoids", "scipy", "numpy", "pandas"),
    "n": len(rows),
    "summary": summary,
    "statistics": [
        {"key": "k", "label": "Clusters", "value": k, "format": "integer"},
        {"key": "silhouette", "label": "Mean silhouette", "value": values["silhouette"]},
    ],
    "tables": tables,
    "values": values,
    "charts": charts,
    "warnings": warnings,
    "artifacts": [{"key": "labels", "path": path, "format": "parquet"}],
    "model": {"kind": "clusterer", "features": names, "params": {
        "k": 3,
        "algorithm": "pam",
        "samples": 5,
        "sample_size": 0,
        "numlocal": 2,
        "maxneighbor": 0,
        "distance": "auto",
        "max_iter": 100,
        "scale": "standard",
        "missing": "drop",
    }},
})
R

The exact script CodeSplash ran for example “Iris euclidean” · R version 4.5.1 (2025-06-13)

# k-medoids (PAM)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.pam 1.1.0 · spec 895c8174e064ca7b
# Dataset: ml_iris (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data
FEATURES <- c("sepal_length", "sepal_width", "petal_length", "petal_width")
LABEL <- "species"  # known groups (external validation only)
ROW_ID <- NULL  # row labels for charts
SEED <- 42
KINDS <- list(
  sepal_length = "numeric",
  sepal_width = "numeric",
  petal_length = "numeric",
  petal_width = "numeric"
)
LEVELS <- list(
)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_iris.parquet", col_select = unique(c(FEATURES, LABEL, ROW_ID))))
n_input <- nrow(df)
prep <- cs_ml_cluster_prepare(df, FEATURES, KINDS, LEVELS, missing = "drop", scale = "standard")
X <- prep$X; rows <- prep$rows; names_ <- prep$names; frame <- prep$frame
warnings <- list()
if (length(rows) < n_input) {
  warnings <- c(warnings, sprintf("%d of %d rows were left out because a feature was missing.", n_input - length(rows), n_input))
}
if (length(rows) < 3) stop("Clustering needs at least three rows with every feature present.")
truth <- if (!is.null(LABEL)) as.character(frame[[LABEL]]) else NULL
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.pam/iris_euclidean/out-r")
values <- list(n_used = length(rows))
centers <- NULL
center_ids <- NULL
D <- NULL
extra <- list()
tables <- list()
charts <- list()
summary <- NULL

# %% Clustering
K <- 3
if (K >= length(rows)) cs_error("CS_E_TOO_FEW_ROWS", what = sprintf("PAM with k = %d", K), min = K + 1L, n = length(rows))
if (length(rows) > 5000) stop("PAM keeps a full dissimilarity matrix; use it on at most 5,000 rows (or k-means).")
DISTANCE <- "auto"
if (DISTANCE == "auto") DISTANCE <- if (any(unlist(KINDS[FEATURES]) != "numeric")) "gower" else "euclidean"
D <- if (DISTANCE == "gower") {
  cs_ml_gower(frame, FEATURES, KINDS)  # = cluster::daisy(metric = "gower")
} else {
  as.matrix(stats::dist(X, method = if (DISTANCE == "manhattan") "manhattan" else "euclidean"))
}
dimnames(D) <- NULL
# Original PAM: BUILD then best-improvement SWAP (pamonce = 0).
res <- cluster::pam(stats::as.dist(D), K, diss = TRUE, pamonce = 0, do.swap = TRUE)
raw <- res$clustering - 1L
medoids <- res$id.med - 1L
centers <- X[medoids + 1L, , drop = FALSE]
own <- D[cbind(seq_along(raw), medoids[raw + 1L] + 1L)]
values$cost <- sum(own) / length(rows)
canon <- cs_ml_canonical(raw)
for (m in medoids) values[[sprintf("medoid_row[%d]", canon[m + 1L])]] <- rows[m + 1L]
extra$distance <- own
summary <- sprintf("PAM with k = %d on %s dissimilarities: average dissimilarity to the medoid %.3f.", K, DISTANCE, values$cost)

# %% Canonical labels and validation
labels <- cs_ml_canonical(raw)
ids <- sort(unique(labels[labels != -1]))
k <- length(ids)
values$k <- k
values$n_noise <- sum(labels == -1)
if (!is.null(centers)) {
  cid <- if (is.null(center_ids)) seq_len(nrow(centers)) - 1L else center_ids
  raw_of <- vapply(ids, function(c) raw[which(labels == c)[1]], numeric(1))
  centers <- centers[match(raw_of, cid), , drop = FALSE]
  for (i in seq_along(ids)) for (j in seq_along(names_)) {
    values[[sprintf("center[%d,%s]", ids[i], names_[j])]] <- centers[i, j]
  }
}
sz <- cs_ml_cluster_sizes(labels)
for (c in names(sz)) values[[sprintf("size[%s]", c)]] <- sz[[c]]
check <- cs_ml_cluster_validation(X, labels, truth, D = D, cap = 3000, seed = SEED)
widths <- check$.widths
check$.widths <- NULL
values <- c(values, check)
profile_rows <- list()
for (c in ids) {
  member <- labels == c
  row <- list(cluster = c, size = sum(member), share = mean(member))
  for (f in FEATURES) {
    if (identical(KINDS[[f]], "numeric")) {
      m <- mean(suppressWarnings(as.numeric(frame[[f]]))[member], na.rm = TRUE)
      row[[f]] <- m
      values[[sprintf("mean[%d,%s]", c, f)]] <- m
    } else {
      v <- as.character(frame[[f]])[member]
      v <- v[!is.na(v)]
      top <- if (length(v)) sort(table(v), decreasing = TRUE) else NULL
      row[[f]] <- if (length(top)) sprintf("%s (%.0f%%)", names(top)[1], 100 * top[[1]] / sum(member)) else ""
    }
  }
  profile_rows[[length(profile_rows) + 1L]] <- row
}
tables <- c(list(list(
  key = "clusters", title = "Clusters",
  columns = c(list(list(key = "cluster", label = "Cluster", type = "integer"),
                   list(key = "size", label = "Size", type = "integer"),
                   list(key = "share", label = "Share", type = "percent")),
              lapply(FEATURES, function(f) list(key = f, label = f, type = if (identical(KINDS[[f]], "numeric")) "number" else "string"))),
  rows = profile_rows
)), tables)

# %% Labels file and charts
path <- do.call(cs_ml_write_labels, c(list(out, rows, labels), extra))
name_of <- function(c) as.character(c)  # noise stays "-1" (drawn gray, listed last)
pr <- cs_ml_project2(X, centers, names_)
show <- cs_ml_even_sample(length(rows))
xs <- pr$P[show + 1L, 1]; ys <- pr$P[show + 1L, 2]
cl <- name_of(labels[show + 1L])
cent <- rep(FALSE, length(show))
lab <- if (!is.null(ROW_ID)) as.character(frame[[ROW_ID]])[show + 1L] else NULL
if (!is.null(pr$C)) {
  xs <- c(xs, pr$C[, 1]); ys <- c(ys, pr$C[, 2])
  cl <- c(cl, name_of(ids)); cent <- c(cent, rep(TRUE, length(ids)))
  if (!is.null(lab)) lab <- c(lab, sprintf("center %d", ids))
}
level_names <- c(as.character(ids), if (values$n_noise > 0) "-1")
charts <- c(list(cs_chart(
  "clusters", "cluster-scatter", "Clusters",
  list(x = cs_col(pr$labels[1], xs, "numeric"), y = cs_col(pr$labels[2], ys, "numeric"),
       cluster = cs_col("Cluster", cl, "categorical", levels = level_names),
       centroid = if (!is.null(pr$C)) cs_col("Center", cent, "boolean"),
       label = if (!is.null(lab)) cs_col("Row", lab, "categorical")),
  note = if (length(show) == length(rows)) NULL else sprintf("%s of %s rows shown.", format(length(show), big.mark = ","), format(length(rows), big.mark = ","))
)), charts)
if (!is.nan(values$silhouette)) {
  wl <- labels[widths$pick + 1L]
  o <- order(wl, -widths$width)
  charts[[length(charts) + 1L]] <- cs_chart(
    "silhouette", "silhouette-plot", "Silhouette widths",
    list(cluster = cs_col("Cluster", as.character(wl[o]), "categorical", levels = as.character(ids)),
         width = cs_col("Silhouette width", widths$width[o], "numeric")),
    note = if (length(widths$pick) == sum(labels != -1)) NULL else sprintf("%s rows sampled for the silhouette.", format(length(widths$pick), big.mark = ","))
  )
}

# %% Result
if (is.null(summary)) {
  summary <- sprintf("%d cluster%s in %s rows", k, if (k != 1) "s" else "", format(length(rows), big.mark = ","))
  if (values$n_noise > 0) summary <- paste0(summary, sprintf(" (%s noise points)", format(values$n_noise, big.mark = ",")))
  if (!is.nan(values$silhouette)) summary <- paste0(summary, sprintf("; mean silhouette %.2f", values$silhouette))
  summary <- paste0(summary, ".")
}
cs_publish(list(
  title = "k-medoids (PAM)",
  engine = cs_engine_info("cluster", "nanoparquet"),
  n = length(rows),
  summary = summary,
  statistics = list(list(key = "k", label = "Clusters", value = k, format = "integer"),
                    list(key = "silhouette", label = "Mean silhouette", value = values$silhouette)),
  tables = tables,
  values = values,
  charts = charts,
  warnings = warnings,
  artifacts = list(list(key = "labels", path = path, format = "parquet")),
  model = list(kind = "clusterer", features = I(names_), params = list(
    k = 3,
    algorithm = "pam",
    samples = 5,
    sample_size = 0,
    numlocal = 2,
    maxneighbor = 0,
    distance = "auto",
    max_iter = 100,
    scale = "standard",
    missing = "drop"
  ))
))

Sources

  • Kaufman L, Rousseeuw PJ (1990). Finding Groups in Data. Wiley, ch. 2.
  • Kaufman L, Rousseeuw PJ (1990). Finding Groups in Data. Wiley, ch. 3 (CLARA).
  • Ng RT, Han J (2002). CLARANS: a method for clustering objects for spatial data mining. IEEE TKDE 14(5):1003–1016.
  • Gower JC (1971). A general coefficient of similarity and some of its properties. Biometrics 27:857–871.

From the CodeSplash method registry · discover.pam v1.1.0.