Skip to content

CDiscover · discover.spectral

Spectral clustering

Which groups are there when clusters are connected shapes rather than round blobs?

Spectral clustering (Ng, Jordan & Weiss) builds a similarity graph between rows (a Gaussian RBF kernel or k nearest neighbors), takes the leading eigenvectors of its normalized form and runs k-means on them, so rings, moons and other connected shapes come out whole. The eigenvalues also suggest k (the largest gap). Kernel k-means, its close relative, runs k-means directly in the RBF kernel's feature space. Both engines build the same graph and draw the same k-means++ starts.

Verified in Python and R Python and R agree to 6 decimals Also called spectral, normalized cut, NJW…

A real result

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

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

Spectral clustering with k = 2 on a nearest-neighbor graph; the largest eigenvalue gap suggests k = 8.

Clusters
2
Mean silhouette
0.1181

Plots

ClustersWhich rows group together, and how well separated are the groups?
View data
Clusterxy
1−1.786−0.4692
2−0.21030.7162
10.62831.552
2−0.45210.6855
20.30240.2584
10.4395−1.697
20.4331−0.0558
20.4492−0.3593
2−0.4941−0.0709
2−0.4685−0.5394
2−0.05960.7036
2−0.7429−0.0588
1−1.062−1.517
1−0.31271.659
2−0.4611−0.2223
20.02350.5129
1−1.301−1.196
2−0.2439−0.6075
2−0.6338−0.1665
10.6791−1.553
2−0.6788−0.0244
10.56191.673
1−1.808−0.5330
2−0.54960.3045
2−0.2780−0.6040
2−0.25500.7943
1−1.273−1.445
10.0430−1.968
2−0.0387−0.6561
20.35720.2670
2−0.5418−0.2096
1−1.222−1.386
10.0128−1.606
1−1.266−1.102
11.488−0.5147
11.7220.3375
2−0.2139−0.5705
10.4204−1.897
2−0.4659−0.4211
1−1.8540.4413
11.7420.0514
1−0.2564−1.645
10.7345−1.555
10.34941.599
10.9373−1.515
2−0.50040.4092
2−0.4703−0.6429
2−0.3817−0.5890
1−1.078−1.501
20.40950.1630
2−0.5402−0.4220
11.534−1.208
10.81121.521
20.2235−0.5717
10.6529−1.479
10.9315−1.534
11.3060.9765
11.2711.018
11.4160.9223
10.4963−1.663

First 60 of 300 rows.

Eigenvalues of the normalized similarity matrixHow many clusters does the data support?

The largest gap after eigenvalue 8 suggests k = 8.

View data
Largest gapEigenvalue (rank)Eigenvalue
false11
false21
false30.9940
false40.9936
false50.9825
false60.9816
false70.9777
true80.9734
false90.9506
false100.9430
Silhouette widthsHow well does each row fit its cluster compared with the next-nearest cluster?
View data
ClusterSilhouette width
1−0.1058
1−0.1103
1−0.1161
1−0.1178
1−0.1204
1−0.1207
1−0.1213
1−0.1218
1−0.1242
1−0.1270
1−0.1278
1−0.1282
1−0.1297
1−0.1299
1−0.1308
1−0.1308
1−0.1315
1−0.1325
1−0.1332
1−0.1339
1−0.1346
1−0.1354
1−0.1362
1−0.1366
1−0.1381
1−0.1384
1−0.1399
1−0.1400
1−0.1419
1−0.1426
1−0.1438
1−0.1449
1−0.1451
1−0.1452
1−0.1456
1−0.1474
1−0.1475
1−0.1481
1−0.1493
1−0.1495
1−0.1510
1−0.1513
1−0.1518
1−0.1518
1−0.1538
1−0.1539
1−0.1543
1−0.1544
1−0.1546
1−0.1548
1−0.1556
1−0.1559
1−0.1562
1−0.1584
1−0.1586
1−0.1588
1−0.1602
1−0.1607
1−0.1607
1−0.1608

First 60 of 300 rows.

Clusters

ClusterSizeSharexy
118060.0%0.27470.0557
212040.0%−0.03340.0052
  • The similarity graph falls into 2 disconnected parts; each part needs at least one cluster.
Python

Spectral clustering with k = 2 on a nearest-neighbor graph; the largest eigenvalue gap suggests k = 8.

Clusters
2
Mean silhouette
0.1181

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

Clusters

ClusterSizeSharexy
118060.0%0.27470.0557
212040.0%−0.03340.0052
  • The similarity graph falls into 2 disconnected parts; each part needs at least one cluster.

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

  • Rings knnclu2_rings · features: x, y · label: ring
  • Iris rbfml_iris · features: sepal_length, sepal_width, petal_length, petal_width · label: species
  • Usarrests gammaml_usarrests · features: Murder, Assault, UrbanPop, Rape · id: state
  • Iris kernel kmeansml_iris · features: sepal_length, sepal_width, petal_length, petal_width · label: species
  • Degenerate n3clu2_rings · features: x, y · label: ring
  • Degenerate tiesclu2_rings · features: x, y · label: ring

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. 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

Clusters (k)default 3

Number of clusters.

Algorithmdefault spectral

Spectral clustering embeds the similarity graph first; kernel k-means clusters in the kernel's feature space directly.

  • Spectral clustering (normalized)(default) — Ng–Jordan–Weiss: k-means on the leading eigenvectors of the normalized similarity matrix; the usual choice.
  • Kernel k-means (RBF) — k-means in the RBF kernel's feature space, from kernel k-means++ starts; needs the RBF similarity.
Similarity graphdefault rbf

How similar two rows are: a smooth Gaussian kernel, or a link to each row's nearest neighbors.

  • Gaussian (RBF) kernel(default) — exp(−γ × squared distance): every pair is linked, nearby pairs strongly.
  • k nearest neighbors — Links each row to its nearest neighbors (½ when only one side lists the other); robust for rings and moons. Spectral clustering only.
Kernel width (γ)default —

Larger γ = only very close rows count as similar; the default uses the median distance between rows.

Neighborsdefault 10

Nearest neighbors each row links to in the k-nearest-neighbor graph.

Advanced

Startsdefault 10

k-means runs from different k-means++ starts; the best is kept.

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.
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>], mean[<cluster>,<feature>], eigenvalue[<i>], eigengap, suggested_k, n_components, embedding_inertia, gamma, n_neighbors, objective, iterations, ari, ami, nmi

Python and R

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

Default traps between the two languages

  • Both engines build the same similarity matrix column by column and take its symmetric eigendecomposition (LAPACK in both); eigenvector signs and rotations within the leading subspace can differ, but k-means on the row-normalized embedding depends only on distances between rows, so the clusters agree. When eigenvalues k and k + 1 tie, the embedding is not unique, so both engines stop with CS_E_UNDEFINED. scikit-learn's SpectralClustering uses a different eigen solver and random k-means starts.
Python

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

# Spectral clustering
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.spectral 1.0.0 · spec 638b2a0c45f9d88a
# Dataset: clu2_rings (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd

import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import cluster as csc
from codesplash.stats.rng import Rng
from codesplash.ml import cluster_partitional as cpart

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

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

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

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

# %% Result
if summary is None:
    summary = f"{k} cluster{'s' if k != 1 else ''} in {len(rows):,} rows"
    if values["n_noise"]:
        summary += f" ({values['n_noise']:,} noise points)"
    if not np.isnan(values["silhouette"]):
        summary += f"; mean silhouette {values['silhouette']:.2f}"
    summary += "."
cs.publish({
    "title": "Spectral clustering",
    "engine": cs.engine_info("numpy", "scikit-learn", "numpy", "pandas"),
    "n": len(rows),
    "summary": summary,
    "statistics": [
        {"key": "k", "label": "Clusters", "value": k, "format": "integer"},
        {"key": "silhouette", "label": "Mean silhouette", "value": values["silhouette"]},
    ],
    "tables": tables,
    "values": values,
    "charts": charts,
    "warnings": warnings,
    "artifacts": [{"key": "labels", "path": path, "format": "parquet"}],
    "model": {"kind": "clusterer", "features": names, "params": {
        "k": 2,
        "algorithm": "spectral",
        "affinity": "knn",
        "gamma": None,
        "n_neighbors": 10,
        "n_init": 10,
        "scale": "standard",
        "missing": "drop",
    }},
})
R

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

# Spectral clustering
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.spectral 1.0.0 · spec 638b2a0c45f9d88a
# Dataset: clu2_rings (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

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

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

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

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

# %% Result
if (is.null(summary)) {
  summary <- sprintf("%d cluster%s in %s rows", k, if (k != 1) "s" else "", format(length(rows), big.mark = ","))
  if (values$n_noise > 0) summary <- paste0(summary, sprintf(" (%s noise points)", format(values$n_noise, big.mark = ",")))
  if (!is.nan(values$silhouette)) summary <- paste0(summary, sprintf("; mean silhouette %.2f", values$silhouette))
  summary <- paste0(summary, ".")
}
cs_publish(list(
  title = "Spectral clustering",
  engine = cs_engine_info("codesplashr", "nanoparquet"),
  n = length(rows),
  summary = summary,
  statistics = list(list(key = "k", label = "Clusters", value = k, format = "integer"),
                    list(key = "silhouette", label = "Mean silhouette", value = values$silhouette)),
  tables = tables,
  values = values,
  charts = charts,
  warnings = warnings,
  artifacts = list(list(key = "labels", path = path, format = "parquet")),
  model = list(kind = "clusterer", features = I(names_), params = list(
    k = 2,
    algorithm = "spectral",
    affinity = "knn",
    gamma = NULL,
    n_neighbors = 10,
    n_init = 10,
    scale = "standard",
    missing = "drop"
  ))
))

Sources

  • Ng AY, Jordan MI, Weiss Y (2002). On spectral clustering: analysis and an algorithm. NeurIPS 14.
  • von Luxburg U (2007). A tutorial on spectral clustering. Statistics and Computing 17:395–416.
  • Dhillon IS, Guan Y, Kulis B (2004). Kernel k-means, spectral clustering and normalized cuts. Proc. KDD, 551–556.

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