Skip to content

Checking maps, mixtures and learned representations

Four checks for unsupervised structure. Trustworthiness and continuity for maps, BIC and ICL for mixtures, held-out reconstruction and log score for latent models, and CKA for comparing two representations of the same rows.

Advanced ~16 min11 steps

What runs in CodeSplash

You will be able to

  • Read trustworthiness and continuity across neighborhood sizes
  • Explain when BIC and ICL pick different numbers of components
  • Score a latent model on held-out data and name a bound as a bound
  • Read CKA beside local neighbor agreement

Read first

01

Two kinds of map error

Read

A 2-D map can fail in two directions. It can put strangers side by side (false neighbors), or tear real neighbors apart. TrustworthinessTrustworthinessA 0–1 score for whether rows that look close on a map are really close in the data. penalizes the first: points among a row's kk map neighbors that weren't near it in the data, weighted by how far away they really were. ContinuityContinuity (map quality)A 0–1 score for whether rows that are close in the data stay close on the map: trustworthiness checks the other direction. reverses the roles and penalizes the second.

In the reference's ten-point example, where a line embedded in 3-D is projected onto one axis, both are 1: nothing was lost. Plot both over several kk (keep kk well below n/2n/2), compare with a PCA baseline, and don't pick the kk that favors your method.

Reference · EVA013 · Partly runs in CodeSplashTrustworthiness and continuityEvaluate local-neighbor distortions introduced by dimensionality reduction.
02

High trust in a bad distance

Explore
Manifold maps (Isomap, LLE, diffusion maps, PHATE)Recorded · Python and R agreeRecorded 2026-11-25 · 16 values compared
R

Isomap map of 240 rows in 2 dimensions (10 neighbors): trustworthiness 0.931. Residual variance 0.112.

Trustworthiness (k = 10)
0.9309
Neighbors kept
75.5%
Residual variance
0.1123

Eigenvalues behind the map

DimensionEigenvalue
11227.06
2254.63
The exact R script · R R version 4.5.1 (2025-06-13)
# Manifold maps (Isomap, LLE, diffusion maps, PHATE)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.manifold 1.0.0 · spec ed55bb1c2ebf4969
# Dataset: rep3_scurve (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data
IMPUTE <- "median"
SCALE <- "standard"
cs_check_finite_columns(as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/rep3_scurve.parquet", col_select = c("x", "y", "z"))), c("x", "y", "z"))
FEATURES <- c("x", "y", "z")
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/rep3_scurve.parquet", col_select = FEATURES))
warnings <- list()
design <- cs_ml_design(
  df, FEATURES,
  kinds = list(
    x = "numeric",
    y = "numeric",
    z = "numeric"
  ),
  levels = list(
  ),
  impute = IMPUTE,
  scale = SCALE
)
fitted <- cs_ml_design_fit(design, df)
X <- unname(cs_ml_design_apply(fitted, df))  # numbers imputed / scaled; categories one-hot (missing -> all zero)
rows <- seq_len(nrow(df)) - 1L
LABEL <- "band"
if (!is.null(LABEL)) df[[LABEL]] <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/rep3_scurve.parquet", col_select = LABEL))[[LABEL]]
METHOD <- "isomap"
METHOD_LABEL <- c(isomap = "Isomap", lle = "LLE", hlle = "Hessian LLE", ltsa = "LTSA",
                  laplacian = "Laplacian eigenmaps", diffusion = "Diffusion map", phate = "PHATE")[[METHOD]]
keep <- cs_ml_sample_rows(length(rows), 1000)
if (length(keep) < length(rows)) {
  warnings <- c(warnings, sprintf("%s maps %s evenly spaced rows of %s (the work grows with the square of the rows).",
                                  METHOD_LABEL, format(length(keep), big.mark = ","), format(length(rows), big.mark = ",")))
}
X <- X[keep, , drop = FALSE]
rows <- rows[keep]
D_REQ <- 2L
k <- cs_ml_mf_check(METHOD, length(rows), ncol(X), 10L, D_REQ)
if (k < 10L) warnings <- c(warnings, sprintf("Only %d rows: the graph uses %d neighbors instead of 10.", length(rows), k))

# %% Map
fit <- cs_ml_mf_fit(
  X, METHOD, k, D_REQ,
  reg = 0.001,
  affinity = "connectivity",
  alpha = 1,
  t = 1,
  epsilon = NULL,
  decay = 40,
  phate_t = NULL,
  max_iter = 300
)
Y <- fit$coords
K <- ncol(Y)
num_or_nan <- function(v) if (is.null(v)) NaN else as.numeric(v)
values <- list(
  n = length(rows),
  n_features = length(FEATURES),
  n_components = K,
  neighbors = k,
  residual_variance = num_or_nan(fit$residual_variance),
  recon_error = num_or_nan(fit$recon_error),
  bandwidth = num_or_nan(fit$bandwidth),
  epsilon = num_or_nan(fit$epsilon),
  phate_t = if (METHOD == "phate") as.numeric(fit$t) else NaN,
  stress = num_or_nan(fit$stress)
)
if (!is.null(fit$eigen)) for (j in seq_along(fit$eigen)) values[[sprintf("eigen[%d]", j)]] <- fit$eigen[j]
for (j in seq_len(K)) values[[sprintf("coord_check[%d]", j)]] <- cs_ml_checksum(Y[, j], rows)

# %% Neighborhood preservation (same rows in both engines)
sample <- cs_ml_sample_rows(length(rows))
k_eval <- min(10L, length(sample) - 2L)
ok_eval <- k_eval >= 1L && 2 * length(sample) - 3 * k_eval - 1 > 0
trust_knn <- if (ok_eval) cs_ml_mf_neighborhood(X[sample, , drop = FALSE], Y[sample, , drop = FALSE], k_eval) else c(NaN, NaN)
values$trustworthiness <- unname(trust_knn[1])
values$knn_preservation <- unname(trust_knn[2])

# %% Artifacts
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.manifold/scurve_isomap/out-r")
emb <- data.frame(row = as.integer(rows))
for (j in seq_len(K)) emb[[sprintf("dim_%d", j)]] <- Y[, j]
nanoparquet::write_parquet(emb, file.path(out, "embedding.parquet"))

# %% Charts
pick <- cs_ml_sample_rows(length(rows), 5000)
groups <- if (is.null(LABEL)) rep("All rows", length(pick)) else {
  g <- as.character(df[[LABEL]][rows[pick] + 1L]); g[is.na(g)] <- "(missing)"; g
}
charts <- list(cs_chart("map", "cluster-scatter", paste(METHOD_LABEL, "map"), list(
  x = cs_col(paste(METHOD_LABEL, 1), Y[pick, 1], "numeric"),
  y = cs_col(paste(METHOD_LABEL, 2), Y[pick, 2], "numeric"),
  cluster = cs_col(if (is.null(LABEL)) "Group" else LABEL, groups, "categorical")
), note = if (length(pick) == length(rows)) NULL else sprintf("%s of %s rows shown.", format(length(pick), big.mark = ","), format(length(rows), big.mark = ","))))
if (METHOD == "isomap") {
  show <- cs_ml_even_sample(length(fit$geodesic), 2000) + 1L
  note <- sprintf("Residual variance %.3f", values$residual_variance)
  if (length(show) < length(fit$geodesic)) note <- paste0(note, sprintf("; %s of %s pairs shown", format(length(show), big.mark = ","), format(length(fit$geodesic), big.mark = ",")))
  charts[[length(charts) + 1L]] <- cs_chart("shepard", "shepard-diagram", "Graph distance against map distance", list(
    dissimilarity = cs_col("Graph (geodesic) distance", fit$geodesic[show], "numeric"),
    distance = cs_col("Map distance", fit$map_distance[show], "numeric")
  ), note = note)
}
if (METHOD == "phate") {
  ts <- seq_along(fit$vne)
  charts[[length(charts) + 1L]] <- cs_chart("vne", "elbow-plot", "Choosing the diffusion time", list(
    k = cs_col("Diffusion time t", as.numeric(ts), "numeric"),
    score = cs_col("Von Neumann entropy", fit$vne, "numeric"),
    criterion = cs_col("Criterion", rep("Von Neumann entropy", length(ts)), "categorical"),
    chosen = cs_col("Chosen t", ts == fit$t, "boolean")
  ), note = sprintf("t = %d%s", as.integer(fit$t), if (is.null(NULL)) " (knee of the entropy curve)" else " (set)"))
}

# %% Result
tables <- list()
if (!is.null(fit$eigen)) {
  tables[[1]] <- list(
    key = "eigen",
    title = "Eigenvalues behind the map",
    columns = list(list(key = "dimension", label = "Dimension", type = "integer"), list(key = "eigen", label = "Eigenvalue", type = "number")),
    rows = lapply(seq_along(fit$eigen), function(j) list(dimension = j, eigen = fit$eigen[j]))
  )
}
summary <- sprintf("%s map of %d rows in %d dimensions (%d neighbors): trustworthiness %.3f.", METHOD_LABEL, length(rows), K, k, values$trustworthiness)
if (METHOD == "isomap") summary <- paste(summary, sprintf("Residual variance %.3f.", values$residual_variance))
statistics <- list(
  list(key = "trustworthiness", label = sprintf("Trustworthiness (k = %d)", k_eval), value = values$trustworthiness),
  list(key = "knn_preservation", label = "Neighbors kept", value = values$knn_preservation, format = "percent")
)
if (METHOD == "isomap") statistics[[length(statistics) + 1L]] <- list(key = "residual_variance", label = "Residual variance", value = values$residual_variance)
if (METHOD == "phate") statistics[[length(statistics) + 1L]] <- list(key = "phate_t", label = "Diffusion time t", value = values$phate_t)
cs_publish(list(
  title = "Manifold maps (Isomap, LLE, diffusion maps, PHATE)",
  engine = cs_engine_info("codesplashr", "nanoparquet"),
  n = length(rows),
  summary = summary,
  statistics = statistics,
  tables = tables,
  charts = charts,
  values = values,
  warnings = warnings,
  artifacts = list(list(key = "embedding", path = file.path(out, "embedding.parquet"), format = "parquet"))
))
Python

Isomap map of 240 rows in 2 dimensions (10 neighbors): trustworthiness 0.931. Residual variance 0.112.

Trustworthiness (k = 10)
0.9309
Neighbors kept
75.5%
Residual variance
0.1123

Eigenvalues behind the map

DimensionEigenvalue
11227.06
2254.63
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Manifold maps (Isomap, LLE, diffusion maps, PHATE)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.manifold 1.0.0 · spec ed55bb1c2ebf4969
# Dataset: rep3_scurve (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os

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.ml import embed as csembed
from codesplash.ml import manifold as csman

# %% Data
IMPUTE = "median"
SCALE = "standard"
cs.check_finite_columns(pd.read_parquet("tests/parity/fixtures/rep3_scurve.parquet", columns=["x", "y", "z"]), ["x", "y", "z"])
FEATURES = ["x", "y", "z"]
df = pd.read_parquet("tests/parity/fixtures/rep3_scurve.parquet", columns=FEATURES)
warnings = []
design = csml.Design.for_frame(
    df,
    FEATURES,
    kinds={
        "x": "numeric",
        "y": "numeric",
        "z": "numeric",
    },
    levels={
    },
    impute=IMPUTE,
    scale=SCALE,
)
fitted = design.fit(df)
X = fitted.transform(df)  # numbers imputed / scaled; categories one-hot (missing → all zero)
rows = np.arange(len(df))
LABEL = "band"
if LABEL:
    df[LABEL] = pd.read_parquet("tests/parity/fixtures/rep3_scurve.parquet", columns=[LABEL])[LABEL]
METHOD = "isomap"
METHOD_LABEL = csman.METHOD_LABELS[METHOD]
keep = csembed.sample_rows(len(rows), 1000)
if len(keep) < len(rows):
    warnings.append(f"{METHOD_LABEL} maps {len(keep):,} evenly spaced rows of {len(rows):,} (the work grows with the square of the rows).")
X = X[keep]
rows = rows[keep]
D_REQ = 2
k = csman.check_setup(METHOD, len(rows), X.shape[1], 10, D_REQ)
if k < 10:
    warnings.append(f"Only {len(rows)} rows: the graph uses {k} neighbors instead of 10.")

# %% Map
fit = csman.fit(
    X,
    METHOD,
    k,
    D_REQ,
    reg=0.001,
    affinity="connectivity",
    alpha=1,
    t=1,
    epsilon=None,
    decay=40,
    phate_t=None,
    max_iter=300,
)
Y = fit["coords"]
K = Y.shape[1]
NAN = float("nan")
values = {
    "n": len(rows),
    "n_features": len(FEATURES),
    "n_components": K,
    "neighbors": k,
    "residual_variance": float(fit.get("residual_variance", NAN)),
    "recon_error": float(fit.get("recon_error", NAN)),
    "bandwidth": float(fit.get("bandwidth", NAN)),
    "epsilon": float(fit.get("epsilon", NAN)),
    "phate_t": float(fit["t"]) if METHOD == "phate" else NAN,
    "stress": float(fit.get("stress", NAN)),
}
eigen = fit.get("eigen")
if eigen is not None:
    for j, v in enumerate(eigen):
        values[f"eigen[{j + 1}]"] = float(v)
for j in range(K):
    values[f"coord_check[{j + 1}]"] = csembed.checksum(Y[:, j], rows)

# %% Neighborhood preservation (same rows in both engines)
sample = csembed.sample_rows(len(rows))
k_eval = min(10, len(sample) - 2)
ok_eval = k_eval >= 1 and 2 * len(sample) - 3 * k_eval - 1 > 0
trust_knn = csman.neighborhood_scores(X[sample], Y[sample], k_eval) if ok_eval else (NAN, NAN)
values["trustworthiness"], values["knn_preservation"] = float(trust_knn[0]), float(trust_knn[1])

# %% Artifacts
out = csml.out_dir("target/academy-parity/run-8142/discover.manifold/scurve_isomap/out-python")
emb = pd.DataFrame({"row": rows.astype(np.int64)})
for j in range(K):
    emb[f"dim_{j + 1}"] = Y[:, j]
emb.to_parquet(os.path.join(out, "embedding.parquet"), index=False)

# %% Charts
pick = csembed.sample_rows(len(rows), 5000)
groups = [("All rows" if LABEL is None else ("(missing)" if pd.isna(v) else str(v))) for v in (df[LABEL].iloc[rows[pick]] if LABEL else [None] * len(pick))]
charts = [cs.chart("map", "cluster-scatter", f"{METHOD_LABEL} map", {
    "x": cs.col(f"{METHOD_LABEL} 1", Y[pick, 0], "numeric"),
    "y": cs.col(f"{METHOD_LABEL} 2", Y[pick, 1], "numeric"),
    "cluster": cs.col(LABEL or "Group", groups, "categorical"),
}, note=None if len(pick) == len(rows) else f"{len(pick):,} of {len(rows):,} rows shown.")]
if METHOD == "isomap":
    show = csc.even_sample(len(fit["geodesic"]), 2000)
    charts.append(cs.chart("shepard", "shepard-diagram", "Graph distance against map distance", {
        "dissimilarity": cs.col("Graph (geodesic) distance", fit["geodesic"][show], "numeric"),
        "distance": cs.col("Map distance", fit["map_distance"][show], "numeric"),
    }, note=f"Residual variance {values['residual_variance']:.3f}" + ("" if len(show) == len(fit["geodesic"]) else f"; {len(show):,} of {len(fit['geodesic']):,} pairs shown")))
if METHOD == "phate":
    vne = fit["vne"]
    ts = np.arange(1, len(vne) + 1)
    charts.append(cs.chart("vne", "elbow-plot", "Choosing the diffusion time", {
        "k": cs.col("Diffusion time t", ts.astype(float), "numeric"),
        "score": cs.col("Von Neumann entropy", vne, "numeric"),
        "criterion": cs.col("Criterion", ["Von Neumann entropy"] * len(vne), "categorical"),
        "chosen": cs.col("Chosen t", [bool(t == fit["t"]) for t in ts], "boolean"),
    }, note=f"t = {fit['t']}" + (" (knee of the entropy curve)" if None is None else " (set)")))

# %% Result
tables = []
if eigen is not None:
    tables.append({
        "key": "eigen",
        "title": "Eigenvalues behind the map",
        "columns": [{"key": "dimension", "label": "Dimension", "type": "integer"}, {"key": "eigen", "label": "Eigenvalue", "type": "number"}],
        "rows": [{"dimension": j + 1, "eigen": float(v)} for j, v in enumerate(eigen)],
    })
trust = values["trustworthiness"]
summary = f"{METHOD_LABEL} map of {len(rows)} rows in {K} dimensions ({k} neighbors): trustworthiness {trust:.3f}."
if METHOD == "isomap":
    summary += f" Residual variance {values['residual_variance']:.3f}."
statistics = [
    {"key": "trustworthiness", "label": f"Trustworthiness (k = {k_eval})", "value": values["trustworthiness"]},
    {"key": "knn_preservation", "label": "Neighbors kept", "value": values["knn_preservation"], "format": "percent"},
]
if METHOD == "isomap":
    statistics.append({"key": "residual_variance", "label": "Residual variance", "value": values["residual_variance"]})
if METHOD == "phate":
    statistics.append({"key": "phate_t", "label": "Diffusion time t", "value": values["phate_t"]})
cs.publish({
    "title": "Manifold maps (Isomap, LLE, diffusion maps, PHATE)",
    "engine": cs.engine_info("numpy", "scipy", "pandas"),
    "n": len(rows),
    "summary": summary,
    "statistics": statistics,
    "tables": tables,
    "charts": charts,
    "values": values,
    "warnings": warnings,
    "artifacts": [{"key": "embedding", "path": os.path.join(out, "embedding.parquet"), "format": "parquet"}],
})

Shortened for the Academy: 2 chart(s) dropped to stay under 100 KB; 2 chart(s) dropped to stay under 100 KB.

An Isomap map of an S-shaped surface keeps trustworthiness 0.931 and 75% of each row's 10 nearest neighbors.

A UMAP map of five unscaled diabetes columns scores trustworthiness 0.980. That is faithfulness to the input distance, which unscaled glucose and blood pressure dominate. A trustworthy map of a meaningless distance is still meaningless, and local fidelity says nothing about global distances or densities.

03

BIC and ICL

Read

For mixtures fitted to the same rows, with pp free parameters and fitted log-likelihood ℓ^\hat\ell:

BIC=−2ℓ^+plog⁡n,ICLMAP≈BIC−2∑i,gz^iglog⁡τig.\mathrm{BIC} = -2\hat\ell + p \log n, \qquad \mathrm{ICL}^{\text{MAP}} \approx \mathrm{BIC} - 2\sum_{i,g} \hat z_{ig} \log \tau_{ig}.

ICLIntegrated completed likelihoodBIC plus a penalty for fuzzy assignments; lower is better, and it prefers components that form well-separated clusters. adds a penalty for fuzzy assignments (τ\tau are the responsibilities, z^\hat z the most likely component), so it prefers well-separated groups. In the reference's example (lower is better here), BIC is 276.8, MAP ICL 338.5 and the soft-entropy variant 376.7: the two ICL forms are different numbers.

Reference · EVA014 · Partly runs in CodeSplashBIC and ICL for mixture-model selectionCompare fitted likelihood models while accounting for complexity; ICL additionally penalizes uncertain classification under a common approximation.
04

Density or partition?

Explore
Choose the number of clustersRecorded · Python and R agreeRecorded 2026-11-25 · 67 values compared
R

Comparing k = 2–5 with a Gaussian mixture, the ICL (MAP) recommends k = 3 (4 of 6 criteria agree).

Clusters
3
Mean silhouette
0.4952

Plots

ClustersWhich rows group together, and how well separated are the groups?
View data
CenterClusterPC1 (67%)PC2 (26%)
false1−1.824−0.0411
false1−1.211−0.4764
false1−0.8641−0.1277
false1−1.660−0.0704
false1−1.8750.7317
false1−1.610−0.4089
false1−1.3910.3507
false1−1.610−0.8420
false1−1.4990.9044
false1−1.305−0.7959
false1−1.638−0.7350
false1−1.289−0.2175
false1−2.0550.8790
false1−2.1050.3767
false1−1.655−0.6758
false1−1.2860.0613
false1−1.2501.174
false1−2.080−0.7144
false1−1.2451.893
false1−2.180−0.3686
false1−2.012−0.2125
false1−1.902−0.2153
false1−1.571−0.3684
false1−1.511−0.6526
false1−1.979−0.4073
false1−1.5530.1066
false1−1.193−0.1624
false1−2.342−0.2472
false1−1.7810.2014
false1−1.405−0.7643
false1−2.001−0.5070
false1−1.221−0.3185
false1−1.5530.2599
false1−0.9984−0.9796
false1−1.7340.9260
false1−1.7700.4423
false1−1.5060.2536
false1−2.1320.0072
false1−1.7170.2037
false1−1.858−0.6192
false1−0.91750.0853
false1−1.851−0.4783
false1−0.87500.9820
false1−1.381−0.9712
false1−1.3770.0805
false1−1.6530.3171
false1−2.132−0.1628
false1−1.507−0.6970
false1−1.6811.325
false1−1.279−0.3498
false1−1.4470.1738
false1−1.608−0.8176
false1−0.84760.6629
false1−1.852−0.8092
false1−1.0970.2237
false1−1.288−0.4985
false1−1.1360.2088
false1−1.541−1.156
false1−1.470−0.0357
false1−1.512−1.128

First 60 of 345 rows.

Criteria by number of clustersHow many clusters does the data support?

Recommended k = 3 by the ICL (MAP).

View data
RecommendedCriterionClusters (k)Score
falseWithin-cluster SS2452.66
trueWithin-cluster SS3277.19
falseWithin-cluster SS4285.40
falseWithin-cluster SS5259.08
trueMean silhouette20.5196
falseMean silhouette30.4952
falseMean silhouette40.4679
falseMean silhouette50.3114
falseCalinski–Harabasz2430.65
trueCalinski–Harabasz3457.89
falseCalinski–Harabasz4292.37
falseCalinski–Harabasz5249.40
trueDavies–Bouldin20.7225
falseDavies–Bouldin30.7918
falseDavies–Bouldin41.542
falseDavies–Bouldin51.305
falseBIC22181.92
trueBIC32148.92
falseBIC42174.47
falseBIC52212.28
falseICL22182.03
trueICL32159.44
falseICL42188.99
falseICL52231.30
Silhouette widthsHow well does each row fit its cluster compared with the next-nearest cluster?
View data
ClusterSilhouette width
10.6248
10.6222
10.6198
10.6193
10.6166
10.6160
10.6154
10.6135
10.6118
10.6095
10.6075
10.6068
10.6066
10.6050
10.6043
10.6043
10.6022
10.6017
10.6013
10.6003
10.6001
10.5983
10.5966
10.5910
10.5910
10.5904
10.5864
10.5845
10.5822
10.5820
10.5815
10.5808
10.5805
10.5802
10.5791
10.5783
10.5779
10.5756
10.5730
10.5726
10.5709
10.5704
10.5693
10.5691
10.5686
10.5675
10.5671
10.5654
10.5640
10.5636
10.5636
10.5614
10.5594
10.5563
10.5552
10.5547
10.5510
10.5501
10.5489
10.5487

First 60 of 342 rows.

Clusters

ClusterSizeSharebill_lenbill_depflipper_len
115645.6%38.91318.317189.76
212336.0%47.50514.982217.19
36318.4%49.33018.498196.78

Criteria by k

kWithin-cluster SSMean silhouetteCalinski–HarabaszDavies–BouldinBICICL
2452.660.5196430.650.72252181.922182.03
3277.190.4952457.890.79182148.922159.44
4285.400.4679292.371.5422174.472188.99
5259.080.3114249.401.3052212.282231.30
  • 2 of 344 rows were left out because a feature was missing.
The exact R script · R R version 4.5.1 (2025-06-13)
# Choose the number of clusters
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.choose_k 1.1.0 · spec be1aafab9df31696
# Dataset: ml_penguins (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("bill_len", "bill_dep", "flipper_len")
LABEL <- "species"  # known groups (external validation only)
ROW_ID <- NULL  # row labels for charts
SEED <- 42
KINDS <- list(
  bill_len = "numeric",
  bill_dep = "numeric",
  flipper_len = "numeric"
)
LEVELS <- list(
)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_penguins.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.choose_k/penguins_gmm_icl/out-r")
values <- list(n_used = length(rows))
centers <- NULL
center_ids <- NULL
D <- NULL
extra <- list()
tables <- list()
charts <- list()
summary <- NULL

# %% Clustering
ALGORITHM <- "gmm"
CRITERION <- "icl"
N_INIT <- 2
if (ALGORITHM != "kmeans" && CRITERION == "gap") stop("The gap statistic is computed for k-means; choose k-means or another criterion.")
if (ALGORITHM != "gmm" && CRITERION == "bic") stop("BIC needs the Gaussian mixture; choose that method or another criterion.")
if (ALGORITHM != "gmm") stop("ICL needs the Gaussian mixture; choose that method or another criterion.")
ks <- seq.int(2, min(5, length(rows) - 1))
if (length(ks) < 2) cs_error("CS_E_TOO_FEW_ROWS", what = "Comparing k = 2 to 5", min = 2 + 2L, n = length(rows))
values$k_min <- ks[1]; values$k_max <- ks[length(ks)]
D_choose <- NULL
if (ALGORITHM == "pam") {
  dist_ <- "auto"
  if (dist_ == "auto") dist_ <- if (any(unlist(KINDS[FEATURES]) != "numeric")) "gower" else "euclidean"
  D_choose <- if (dist_ == "gower") cs_ml_gower(frame, FEATURES, KINDS) else as.matrix(stats::dist(X))
  dimnames(D_choose) <- NULL
}
rng <- cs_rng(SEED)  # shared stream: the same starts in Python and R
fits <- list()
crit <- list(within = numeric(0), silhouette = numeric(0), calinski_harabasz = numeric(0), davies_bouldin = numeric(0))
if (ALGORITHM == "gmm") crit$bic <- numeric(0)
if (ALGORITHM == "gmm") crit$icl <- numeric(0)
for (kk in ks) {
  if (ALGORITHM == "kmeans") {
    f <- cs_ml_kmeans_fit(X, kk, rng, N_INIT)
    raw_k <- f$labels; centers_k <- f$centers
  } else if (ALGORITHM == "pam") {
    res <- cluster::pam(stats::as.dist(D_choose), kk, diss = TRUE, pamonce = 0)
    raw_k <- res$clustering - 1L; centers_k <- X[res$id.med, , drop = FALSE]
  } else {
    f <- cs_ml_gmm_fit(X, kk, "full", rng, N_INIT)
    raw_k <- f$labels; centers_k <- f$means
    crit$bic <- c(crit$bic, f$bic)
    crit$icl <- c(crit$icl, cs_cp_gmm_icl(f$bic, f$fit$resp, "map"))
  }
  fits[[as.character(kk)]] <- list(raw = raw_k, centers = centers_k)
  lab <- cs_ml_canonical(raw_k)
  crit$within <- c(crit$within, cs_ml_within_ss(X, lab))
  crit$silhouette <- c(crit$silhouette, cs_ml_silhouette(lab, X = if (is.null(D_choose)) X else NULL, D = D_choose, seed = SEED)$mean)
  crit$calinski_harabasz <- c(crit$calinski_harabasz, cs_ml_calinski_harabasz(X, lab))
  crit$davies_bouldin <- c(crit$davies_bouldin, cs_ml_davies_bouldin(X, lab))
}
best <- list(
  elbow = ks[cs_ml_kneedle(ks, crit$within) + 1L],
  silhouette = ks[which.max(crit$silhouette)],
  calinski_harabasz = ks[which.max(crit$calinski_harabasz)],
  davies_bouldin = ks[which.min(crit$davies_bouldin)]
)
if (ALGORITHM == "gmm") best$bic <- ks[which.min(crit$bic)]
if (ALGORITHM == "gmm") best$icl <- ks[which.min(crit$icl)]
if (CRITERION == "gap") {
  rng_gap <- cs_rng(SEED + 1)  # a second shared stream for the reference sets and their starts
  refs <- lapply(seq_len(10), function(b) cs_ml_reference_set(X, rng_gap))
  gap <- numeric(0); se <- numeric(0)
  for (i in seq_along(ks)) {
    logw <- vapply(refs, function(ref) log(max(cs_ml_kmeans_fit(ref, ks[i], rng_gap, 1)$inertia, 1e-300)), numeric(1))
    gap <- c(gap, mean(logw) - log(max(crit$within[i], 1e-300)))
    se <- c(se, stats::sd(logw) * sqrt(1 + 1 / length(refs)))
  }
  crit$gap <- gap; crit$gap_se <- se
  best$gap <- cs_ml_gap_choice(ks, gap, se)
}
for (nm in names(crit)) for (i in seq_along(ks)) values[[sprintf("score[%s,%d]", nm, ks[i])]] <- crit[[nm]][i]
for (nm in names(best)) values[[sprintf("best_k[%s]", nm)]] <- best[[nm]]
K_BEST <- best[[CRITERION]]
values$recommended_k <- K_BEST
values$agree <- sum(unlist(best) == K_BEST)
values$n_criteria <- length(best)
LABELS <- c(elbow = "elbow (kneedle)", silhouette = "mean silhouette", gap = "gap statistic (first-SE rule)",
            calinski_harabasz = "Calinski–Harabasz index", davies_bouldin = "Davies–Bouldin index", bic = "BIC")
LABELS[["icl"]] <- "ICL (MAP)"
values$criterion_label <- LABELS[[CRITERION]]
values$algorithm_label <- switch(ALGORITHM, kmeans = "k-means", pam = "PAM", gmm = "a Gaussian mixture")
raw <- fits[[as.character(K_BEST)]]$raw
centers <- fits[[as.character(K_BEST)]]$centers
D <- D_choose
NAMES <- c(within = "Within-cluster SS", silhouette = "Mean silhouette", calinski_harabasz = "Calinski–Harabasz",
           davies_bouldin = "Davies–Bouldin", gap = "Gap", bic = "BIC", gap_se = "Gap SE")
NAMES[["icl"]] <- "ICL"
pk <- numeric(0); ps <- numeric(0); pc <- character(0); pch <- logical(0)
for (nm in intersect(c("within", "silhouette", "gap", "calinski_harabasz", "davies_bouldin", "bic", "icl"), names(crit))) {
  chosen_k <- best[[if (nm == "within") "elbow" else nm]]
  pk <- c(pk, ks); ps <- c(ps, crit[[nm]]); pc <- c(pc, rep(NAMES[[nm]], length(ks))); pch <- c(pch, ks == chosen_k)
}
charts[[length(charts) + 1L]] <- cs_chart(
  "choose_k", "elbow-plot", "Criteria by number of clusters",
  list(k = cs_col("Clusters (k)", pk, "numeric"), score = cs_col("Score", ps, "numeric"),
       criterion = cs_col("Criterion", pc, "categorical"), chosen = cs_col("Recommended", pch, "boolean")),
  note = sprintf("Recommended k = %d by the %s.", K_BEST, LABELS[[CRITERION]])
)
tables[[length(tables) + 1L]] <- list(
  key = "choose_k", title = "Criteria by k",
  columns = c(list(list(key = "k", label = "k", type = "integer")),
              lapply(names(crit), function(nm) list(key = nm, label = NAMES[[nm]], type = "number"))),
  rows = lapply(seq_along(ks), function(i) c(list(k = ks[i]), lapply(crit, function(v) v[i])))
)
summary <- sprintf("Comparing k = %d–%d with %s, the %s recommends k = %d (%d of %d criteria agree).",
                   ks[1], ks[length(ks)], values$algorithm_label, LABELS[[CRITERION]], K_BEST, values$agree, values$n_criteria)

# %% 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 = "Choose the number of clusters",
  engine = cs_engine_info("stats", "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(
    algorithm = "gmm",
    k_min = 2,
    k_max = 5,
    criterion = "icl",
    n_init = 2,
    references = 10,
    gap_reference = "uniform",
    gap_starts = 1,
    gap_rule = "tibshirani",
    ps_splits = 20,
    ps_cutoff = 0.8,
    icl_variant = "map",
    covariance = "full",
    distance = "auto",
    scale = "standard",
    missing = "drop"
  ))
))
Python

Comparing k = 2–5 with a Gaussian mixture, the ICL (MAP) recommends k = 3 (4 of 6 criteria agree).

Clusters
3
Mean silhouette
0.4952

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

Clusters

ClusterSizeSharebill_lenbill_depflipper_len
115645.6%38.91318.317189.76
212336.0%47.50514.982217.19
36318.4%49.33018.498196.78

Criteria by k

kWithin-cluster SSMean silhouetteCalinski–HarabaszDavies–BouldinBICICL
2452.660.5196430.650.72252181.922182.03
3277.190.4952457.890.79182148.922159.44
4285.400.4679292.371.5422174.472188.99
5259.080.3114249.401.3052212.282231.30
  • 2 of 344 rows were left out because a feature was missing.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Choose the number of clusters
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.choose_k 1.1.0 · spec be1aafab9df31696
# Dataset: ml_penguins (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 math

from scipy.spatial.distance import cdist
from codesplash.ml import cluster_partition as cpart

# %% Data
FEATURES = ["bill_len", "bill_dep", "flipper_len"]
LABEL = "species"  # known groups (external validation only)
ROW_ID = None  # row labels for charts
SEED = 42
KINDS = {
    "bill_len": "numeric",
    "bill_dep": "numeric",
    "flipper_len": "numeric",
}
LEVELS = {
}
df = pd.read_parquet("tests/parity/fixtures/ml_penguins.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.choose_k/penguins_gmm_icl/out-python")
values = {"n_used": len(rows)}
centers = None
center_ids = None
D = None
extra = {}
tables = []
charts = []
summary = None

# %% Clustering
ALGORITHM = "gmm"
CRITERION = "icl"
N_INIT = 2
if ALGORITHM != "kmeans" and CRITERION == "gap":
    raise ValueError("The gap statistic is computed for k-means; choose k-means or another criterion.")
if ALGORITHM != "gmm" and CRITERION == "bic":
    raise ValueError("BIC needs the Gaussian mixture; choose that method or another criterion.")
if ALGORITHM != "gmm":
    raise ValueError("ICL needs the Gaussian mixture; choose that method or another criterion.")
ks = list(range(2, min(5, len(rows) - 1) + 1))
if len(ks) < 2:
    cs.cs_error("CS_E_TOO_FEW_ROWS", what=f"Comparing k = 2 to 5", min=2 + 2, n=len(rows))
values["k_min"], values["k_max"] = ks[0], ks[-1]
D_choose = None
if ALGORITHM == "pam":
    import kmedoids  # GPL and opt-in (advanced tier), so k-means and Gaussian mixtures run without it

    dist = "auto"
    if dist == "auto":
        dist = "gower" if any(KINDS[f] != "numeric" for f in FEATURES) else "euclidean"
    D_choose = csc.gower(frame, FEATURES, KINDS) if dist == "gower" else cdist(X, X)
rng = Rng(SEED)  # shared stream: the same starts in Python and R
fits = {}
crit = {"within": [], "silhouette": [], "calinski_harabasz": [], "davies_bouldin": []}
if ALGORITHM == "gmm":
    crit["bic"] = []
    crit["icl"] = []
for kk in ks:
    if ALGORITHM == "kmeans":
        raw_k, centers_k, _ = csc.kmeans_fit(X, kk, rng, N_INIT)
    elif ALGORITHM == "pam":
        res = kmedoids.pam(D_choose, kk, init="build")
        raw_k = np.asarray(res.labels, dtype=np.int64)
        centers_k = X[np.asarray(res.medoids, dtype=np.int64)]
    else:
        raw_k, centers_k, bic, gm_k = csc.gmm_fit(X, kk, "full", rng, N_INIT, seed=SEED)
        crit["icl"].append(cpart.gmm_icl(bic, gm_k.predict_proba(X), "map"))
        crit["bic"].append(bic)
    fits[kk] = (raw_k, centers_k)
    lab = csc.canonical(raw_k)
    crit["within"].append(csc.within_ss(X, lab))
    crit["silhouette"].append(csc.silhouette(lab, X=None if D_choose is not None else X, D=D_choose, seed=SEED)[0])
    crit["calinski_harabasz"].append(csc.calinski_harabasz(X, lab))
    crit["davies_bouldin"].append(csc.davies_bouldin(X, lab))
best = {
    "elbow": ks[csc.kneedle(ks, crit["within"])],
    "silhouette": ks[int(np.nanargmax(crit["silhouette"]))],
    "calinski_harabasz": ks[int(np.nanargmax(crit["calinski_harabasz"]))],
    "davies_bouldin": ks[int(np.nanargmin(crit["davies_bouldin"]))],
}
if ALGORITHM == "gmm":
    best["bic"] = ks[int(np.argmin(crit["bic"]))]
    best["icl"] = ks[int(np.argmin(crit["icl"]))]
if CRITERION == "gap":
    rng_gap = Rng(SEED + 1)  # a second shared stream for the reference sets and their starts
    refs = list(csc.reference_sets(X, 10, rng_gap))
    gap, se = [], []
    for i, kk in enumerate(ks):
        logw = np.array([math.log(max(csc.kmeans_fit(ref, kk, rng_gap, 1)[2], 1e-300)) for ref in refs])
        gap.append(float(np.mean(logw) - math.log(max(crit["within"][i], 1e-300))))
        se.append(float(np.std(logw, ddof=1) * math.sqrt(1 + 1 / len(refs))))
    crit["gap"], crit["gap_se"] = gap, se
    best["gap"] = csc.gap_choice(ks, gap, se)
for name, scores in crit.items():
    for kk, v in zip(ks, scores):
        values[f"score[{name},{kk}]"] = float(v)
for name, kk in best.items():
    values[f"best_k[{name}]"] = int(kk)
K_BEST = best[CRITERION]
values["recommended_k"] = int(K_BEST)
values["agree"] = sum(1 for v in best.values() if v == K_BEST)
values["n_criteria"] = len(best)
LABELS = {"elbow": "elbow (kneedle)", "silhouette": "mean silhouette", "gap": "gap statistic (first-SE rule)",
          "calinski_harabasz": "Calinski–Harabasz index", "davies_bouldin": "Davies–Bouldin index", "bic": "BIC"}
LABELS["icl"] = "ICL (MAP)"
values["criterion_label"] = LABELS[CRITERION]
values["algorithm_label"] = {"kmeans": "k-means", "pam": "PAM", "gmm": "a Gaussian mixture"}[ALGORITHM]
raw, centers = fits[K_BEST]
D = D_choose
NAMES = {"within": "Within-cluster SS", "silhouette": "Mean silhouette", "calinski_harabasz": "Calinski–Harabasz",
         "davies_bouldin": "Davies–Bouldin", "gap": "Gap", "bic": "BIC"}
NAMES["icl"] = "ICL"
plot_k, plot_s, plot_c, plot_ch = [], [], [], []
for name in [c for c in ["within", "silhouette", "gap", "calinski_harabasz", "davies_bouldin", "bic", "icl"] if c in crit]:
    chosen_k = best["elbow" if name == "within" else name]
    for kk, v in zip(ks, crit[name]):
        plot_k.append(kk)
        plot_s.append(float(v))
        plot_c.append(NAMES[name])
        plot_ch.append(bool(kk == chosen_k))
charts.append(cs.chart(
    "choose_k", "elbow-plot", "Criteria by number of clusters",
    {"k": cs.col("Clusters (k)", plot_k, "numeric"), "score": cs.col("Score", plot_s, "numeric"),
     "criterion": cs.col("Criterion", plot_c, "categorical"), "chosen": cs.col("Recommended", plot_ch, "boolean")},
    note=f"Recommended k = {K_BEST} by the {LABELS[CRITERION]}.",
))
cols = [{"key": "k", "label": "k", "type": "integer"}] + [
    {"key": n, "label": NAMES.get(n, "Gap SE" if n == "gap_se" else n), "type": "number"} for n in crit
]
tables.append({
    "key": "choose_k", "title": "Criteria by k", "columns": cols,
    "rows": [{"k": kk, **{n: float(crit[n][i]) for n in crit}} for i, kk in enumerate(ks)],
})
summary = (
    f"Comparing k = {ks[0]}–{ks[-1]} with {values['algorithm_label']}, the {LABELS[CRITERION]} recommends k = {K_BEST} "
    f"({values['agree']} of {values['n_criteria']} criteria agree)."
)

# %% 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": "Choose the number of clusters",
    "engine": cs.engine_info("scikit-learn", "kmedoids", "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": {
        "algorithm": "gmm",
        "k_min": 2,
        "k_max": 5,
        "criterion": "icl",
        "n_init": 2,
        "references": 10,
        "gap_reference": "uniform",
        "gap_starts": 1,
        "gap_rule": "tibshirani",
        "ps_splits": 20,
        "ps_cutoff": 0.8,
        "icl_variant": "map",
        "covariance": "full",
        "distance": "auto",
        "scale": "standard",
        "missing": "drop",
    }},
})

On three penguin measurements, BIC at three components is 2148.9 and ICL 2159.4; both pick three, and the groups match the species with ARI 0.93.

They don't always agree. The best density estimate and the best partition can need different numbers of components, and an extra component may model skewness rather than a new population. Fit each candidate with several starts and reject degenerate fits.

05

Held-out reconstruction and log score

Read

A representation earns trust by predicting data it didn't fit. Two checks, both on held-out entries or rows:

MSE=1∣Ω∣∑(i,j)∈Ω(xij−x^ij)2,NLL=−1n∑ilog⁡pθ(xi).\mathrm{MSE} = \frac{1}{|\Omega|}\sum_{(i,j)\in\Omega} (x_{ij} - \hat x_{ij})^2, \qquad \mathrm{NLL} = -\frac{1}{n}\sum_i \log p_\theta(x_i).

In the reference's toy example they are 0.03 and 1.167. For imputation, hide known values and score only those. An identity map reconstructs perfectly and learns nothing, so pair reconstruction with a bottleneck or a downstream check. The held-out log scoreHeld-out log-likelihoodThe mean log-likelihood a fitted model gives rows it never trained on; higher is better. needs a tractable likelihood; otherwise name the approximation.

Reference · EVA015 · Partly runs in CodeSplashHeld-out reconstruction and predictive log scoreChecks whether a representation reconstructs withheld information and whether a probabilistic model predicts genuinely unseen observations.
06

A bound is a bound

Read
Variational autoencoder (latent map, anomalies and generated rows)Recorded · Python and R agreeRecorded 2026-11-25 · 43 values compared
R

A variational autoencoder mapped 532 rows into 2 latent coordinates (2 in use); the mean squared reconstruction error is 0.492 per standardized column and the mean KL is 1.26 nats; 27 rows with a loss of at least 11 are flagged as anomalies. The importance-weighted bound with 50 draws is -9.442 nats per row (0.0661 above the ELBO estimate).

Mean reconstruction error
0.4918
Mean KL (nats per row)
1.262
Active latent dimensions
2
Trustworthiness (k = 10)
0.8356
Anomalies
27
Log-likelihood bound (IWAE, 50 draws)
−9.442

Assumptions

  • Latent dimensions in use — 2 of 2 latent dimensions vary across rows (variance of μ > 0.01).

Rows the model finds least typical

RankRowPer-row lossnpregglubpskinbmipedage
115741.5002197709934.7000.575062
239836.1730180786359.4002.42025
31133.5480137403543.1002.28833
429629.8984197703936.7002.32931
536222.1643173824838.4002.13725
627920.47901291104667.1000.319026
725719.6381883042550.496026
822218.12201806639421.89325
946015.515282522228.5001.69925
104815.056292762024.2001.69828
1120814.2221103303843.3000.183033
1240312.8669134743325.9000.460081
131312.5721189602330.1000.398059
1441712.5190173783246.5001.15958
1537512.3022127582427.7001.60025
1649112.30110681062335.5000.285047
1727212.25217163724140.9000.817047
1811112.11241891103128.5000.680037
1935812.04951031083739.2000.305065
2039612.04601891042534.3000.435041

Latent dimensions

DimensionMean KL (nats)Variance of μActive
10.53170.6583yes
20.72990.8052yes
The exact R script · R R version 4.5.1 (2025-06-13)
# Variational autoencoder (latent map, anomalies and generated rows)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.vae 1.2.0 · spec 4fb7211679042758
# Dataset: ml_pima (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)  # cs_deep_fit_vae: torch VAE with shared initial weights (twin of codesplash.deep.generative)

# %% Data — standardized numbers (median-imputed), one-hot categories
IMPUTE <- "median"
SCALE <- "standard"
cs_check_finite_columns(as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_pima.parquet", col_select = c("npreg", "glu", "bp", "skin", "bmi", "ped", "age"))), c("npreg", "glu", "bp", "skin", "bmi", "ped", "age"))
# Training options, live progress and checkpoints (twin: codesplash.deep.trainer.configure).
cs_deep_trainer_configure(list(
  optimizer = "default",
  lr_schedule = "none",
  warmup_epochs = 0,
  grad_clip = 0,
  ema_decay = 0,
  swa_start = 0,
  history_every_step = FALSE,
  profile = "parity",
  checkpoint_every = NULL
), out_dir = "target/academy-parity/run-8142/discover.vae/pima_iwae_normal/out-r")
FEATURES <- c("npreg", "glu", "bp", "skin", "bmi", "ped", "age")
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_pima.parquet", col_select = FEATURES))
warnings <- list()
design <- cs_ml_design(
  df, FEATURES,
  kinds = list(
    npreg = "numeric",
    glu = "numeric",
    bp = "numeric",
    skin = "numeric",
    bmi = "numeric",
    ped = "numeric",
    age = "numeric"
  ),
  levels = list(
  ),
  impute = IMPUTE,
  scale = SCALE
)
fitted <- cs_ml_design_fit(design, df)
X <- unname(cs_ml_design_apply(fitted, df))  # numbers imputed / scaled; categories one-hot (missing -> all zero)
rows <- seq_len(nrow(df)) - 1L
LABEL <- NULL
if (!is.null(LABEL)) df[[LABEL]] <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_pima.parquet", col_select = LABEL))[[LABEL]]

# %% Variational autoencoder (torch for R, float64, one thread): encoder -> (mu, log sigma^2) -> z = mu + sigma * eps -> decoder
HIDDEN <- as.integer(unlist(c(12)))
LATENT <- as.integer(2)
BETA <- 1
N_SAMPLES <- as.integer(0)
PRIOR <- "normal"  # N(0, I), or a learned Gaussian mixture (VaDE)
IWAE <- as.integer(50)
if (PRIOR == "mixture" && length(rows) <= 3) {
  cs_error("CS_E_TOO_FEW_ROWS", what = "A 3-component mixture prior", min = 3 + 1, n = length(rows))
}
fit <- if (PRIOR == "mixture") {
  cs_deep_fit_vade(
    X, HIDDEN, LATENT, as.integer(3),
    activation = "tanh",
    beta = BETA,
    epochs = as.integer(100),
    lr = 0.005,
    batch_size = 128,
    weight_decay = 0,
    n_samples = N_SAMPLES,
    pretrain_epochs = as.integer(100),
    seed = 42
  )
} else {
  cs_deep_fit_vae(
    X, HIDDEN, LATENT,
    activation = "tanh",
    beta = BETA,
    epochs = as.integer(100),
    lr = 0.005,
    batch_size = 128,
    weight_decay = 0,
    n_samples = N_SAMPLES,
    seed = 42
  )
}
if (any(!is.finite(fit$score))) cs_error("CS_E_NO_CONVERGENCE", what = "Variational autoencoder training")
Z <- fit$embedding  # posterior means mu (n x LATENT)
scores <- fit$score  # squared reconstruction error at z = mu plus beta x KL, per row
errors <- fit$error  # mean squared reconstruction error per standardized column

# %% Anomalies by the per-row loss
RULE <- "share"
flagged <- cs_ml_flag(scores, RULE, 0.05, 10)
flags <- flagged$flag
threshold <- flagged$threshold
ord <- order(-scores, rows)  # largest loss first, ties by row

# %% Neighborhood preservation of the map (same rows in both engines)
sample <- cs_ml_sample_rows(length(rows))
k_eval <- min(10L, length(sample) - 2L)
trust <- if (k_eval >= 1L) cs_ml_trustworthiness(X[sample, , drop = FALSE], Z[sample, , drop = FALSE], k_eval) else NaN  # undefined with fewer than 3 rows

# %% Mixture prior: each row's component at z = mu (canonical ids 1..k by size)
clusters <- NULL
if (PRIOR == "mixture") {
  clusters <- cs_ml_canonical(fit$cluster)
  comp_of <- integer(0)
  for (j in seq_along(fit$pi)) {
    members <- which(fit$cluster == j - 1L)
    if (length(members)) comp_of[as.character(j)] <- clusters[members[1]]
  }
}

# %% Importance-weighted bound on log p(x) (and the ELBO from the same draws)
bound <- if (IWAE > 0L) cs_deep_iwae_bound(X, fit, LATENT, "tanh", IWAE, 42) else NULL

# %% Generated rows: decode prior draws back to the columns' units
gen_cols <- if (N_SAMPLES > 0L) cs_deep_decode_design(fitted, fit$samples) else list()
NUMERIC <- Filter(function(f) identical(design$kinds[[f]], "numeric"), FEATURES)
sample_ks <- list()
if (N_SAMPLES > 0L) for (f in NUMERIC) sample_ks[[f]] <- cs_deep_ks(suppressWarnings(as.numeric(df[[f]])), gen_cols[[f]])

# %% Artifacts
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.vae/pima_iwae_normal/out-r")
emb <- data.frame(row = as.integer(rows))
for (j in seq_len(LATENT)) emb[[paste0("dim_", j)]] <- Z[, j]
nanoparquet::write_parquet(emb, file.path(out, "embedding.parquet"))
labels_df <- data.frame(row = as.integer(rows), score = scores, anomaly = flags)
if (!is.null(clusters)) labels_df$cluster <- as.integer(clusters)
nanoparquet::write_parquet(labels_df, file.path(out, "labels.parquet"))
hist <- data.frame(
  epoch = vapply(fit$history, function(h) as.numeric(h$epoch), numeric(1)),
  loss = vapply(fit$history, function(h) h$loss, numeric(1)),
  reconstruction = vapply(fit$history, function(h) h$recon, numeric(1)),
  kl = vapply(fit$history, function(h) h$kl, numeric(1))
)
nanoparquet::write_parquet(hist, file.path(out, "history.parquet"))
artifacts <- list(
  list(key = "embedding", path = file.path(out, "embedding.parquet"), format = "parquet"),
  list(key = "labels", path = file.path(out, "labels.parquet"), format = "parquet"),
  list(key = "history", path = file.path(out, "history.parquet"), format = "parquet")
)
if (N_SAMPLES > 0L) {
  nanoparquet::write_parquet(as.data.frame(gen_cols[FEATURES], check.names = FALSE), file.path(out, "samples.parquet"))
  artifacts[[length(artifacts) + 1L]] <- list(key = "samples", path = file.path(out, "samples.parquet"), format = "parquet",
                                              title = "Rows generated from the prior")
}

# %% Result
active <- as.integer(fit$active)
values <- list(
  n = length(rows), n_features = ncol(X), latent_dim = LATENT, recon_mse = mean(errors), kl = mean(fit$kl_row),
  elbo_loss = mean(scores), active_dims = active, error_check = cs_ml_checksum(scores, rows), n_flagged = sum(flags),
  threshold = threshold, final_loss = hist$loss[nrow(hist)], epochs_run = fit$epochs_run, trustworthiness = trust,
  n_samples = N_SAMPLES, sample_ks_mean = if (length(sample_ks)) mean(unlist(sample_ks)) else NaN
)
for (j in seq_len(LATENT)) {
  values[[sprintf("emb_check[%d]", j)]] <- cs_ml_checksum(Z[, j], rows)
  values[[sprintf("kl_dim[%d]", j)]] <- fit$kl_dim[j]
}
for (f in names(sample_ks)) values[[sprintf("sample_ks[%s]", f)]] <- sample_ks[[f]]
if (!is.null(clusters)) {
  values$components <- length(fit$pi)
  values$n_clusters <- length(comp_of)
  for (j in names(comp_of)) {
    values[[sprintf("pi[%d]", comp_of[[j]])]] <- fit$pi[as.integer(j)]
    values[[sprintf("cluster_size[%d]", comp_of[[j]])]] <- sum(clusters == comp_of[[j]])
  }
}
if (!is.null(bound)) {
  values$iwae_samples <- IWAE
  values$iwae_bound <- mean(bound$iwae)
  values$elbo_estimate <- mean(bound$elbo)
  values$iwae_gap <- values$iwae_bound - values$elbo_estimate
}
for (rank in seq_len(min(10L, length(ord)))) {
  values[[sprintf("top_row[%d]", rank)]] <- rows[ord[rank]]
  values[[sprintf("top_score[%d]", rank)]] <- scores[ord[rank]]
}
top <- utils::head(ord, 20L)
table_rows <- lapply(seq_along(top), function(rank) {
  i <- top[rank]
  r <- list(rank = rank, row = rows[i] + 1L, score = scores[i])
  for (f in FEATURES) {
    v <- df[[f]][rows[i] + 1L]
    r[[f]] <- if (is.na(v)) NULL else if (is.numeric(v)) v else as.character(v)
  }
  r
})
dim_rows <- lapply(seq_len(LATENT), function(j) list(dim = j, kl = fit$kl_dim[j], var_mu = fit$mu_var[j], active = fit$mu_var[j] > 0.01))
pick <- cs_ml_sample_rows(length(rows), 5000)
groups <- if (is.null(LABEL)) rep("All rows", length(pick)) else {
  g <- df[[LABEL]][rows[pick] + 1L]
  ifelse(is.na(g), "(missing)", as.character(g))
}
charts <- list()
if (LATENT >= 2L && !is.null(clusters)) {
  cent_ <- as.integer(names(comp_of))[order(comp_of)]
  charts[[length(charts) + 1L]] <- cs_chart("latent", "cluster-scatter", "Latent means by mixture component (component means marked)", list(
    x = cs_col("Latent 1 (μ)", c(Z[pick, 1], fit$mu_c[cent_, 1]), "numeric"),
    y = cs_col("Latent 2 (μ)", c(Z[pick, 2], fit$mu_c[cent_, 2]), "numeric"),
    cluster = cs_col("Component", c(as.character(clusters[pick]), as.character(comp_of[as.character(cent_)])), "categorical",
                     levels = as.character(sort(as.integer(comp_of)))),
    centroid = cs_col("Component mean", c(rep(FALSE, length(pick)), rep(TRUE, length(cent_))), "boolean")
  ), note = if (length(pick) == length(rows)) NULL else sprintf("%s of %s rows shown.", format(length(pick), big.mark = ","), format(length(rows), big.mark = ",")))
} else if (LATENT >= 2L) {
  charts[[length(charts) + 1L]] <- cs_chart("latent", "latent-prior", "Latent means against the N(0, I) prior", list(
    x = cs_col("Latent 1 (μ)", Z[pick, 1], "numeric"),
    y = cs_col("Latent 2 (μ)", Z[pick, 2], "numeric"),
    group = cs_col(if (is.null(LABEL)) "Group" else LABEL, groups, "categorical")
  ), note = if (length(pick) == length(rows)) NULL else sprintf("%s of %s rows shown.", format(length(pick), big.mark = ","), format(length(rows), big.mark = ",")))
}
charts[[length(charts) + 1L]] <- cs_chart("errors", "anomaly-scores", "Per-row loss (reconstruction + β·KL) distribution", list(
  score = cs_col("Per-row loss", scores, "numeric"),
  anomaly = cs_col("Anomaly", flags, "boolean")
), controls = list(threshold = threshold))
ne <- nrow(hist)
charts[[length(charts) + 1L]] <- cs_chart("training", "training-components", "Training loss and its parts by epoch", list(
  x = cs_col("Epoch", rep(hist$epoch, 3), "numeric"),
  value = cs_col("Loss per row", c(hist$loss, hist$reconstruction, hist$kl), "numeric"),
  component = cs_col("Part", rep(c("total", "reconstruction", "KL"), each = ne), "categorical", levels = c("total", "reconstruction", "KL"))
))
if (length(sample_ks)) {
  f0 <- NUMERIC[1]
  d <- cs_synth_density_rows(suppressWarnings(as.numeric(df[[f0]])), as.numeric(gen_cols[[f0]]))
  if (!is.null(d)) {
    charts[[length(charts) + 1L]] <- cs_chart("samples", "density-compare", sprintf("%s: data vs rows generated from the prior", f0), list(
      x = cs_col(f0, d$x, "numeric"), density = cs_col("Density", d$density, "numeric"),
      source = cs_col("Source", d$source, "categorical", levels = c("real", "synthetic"))))
  }
}
assumptions <- list(list(
  key = "active_units", label = "Latent dimensions in use",
  status = if (active == LATENT) "pass" else if (active == 0L) "fail" else "warn",
  detail = paste0(sprintf("%d of %d latent dimension%s vary across rows (variance of μ > 0.01)", active, LATENT, if (LATENT != 1L) "s" else ""),
                  if (active == LATENT) "." else "; the rest collapsed onto the prior and carry no information about the rows.")
))
if (active < LATENT) {
  warnings <- c(warnings, sprintf("Posterior collapse: %d latent dimension%s carry no information (KL ≈ 0). Lower β, shrink the bottleneck, or train longer.",
                                  LATENT - active, if (LATENT - active != 1L) "s" else ""))
}
summary <- sprintf("A variational autoencoder mapped %d rows into %d latent coordinate%s (%d in use); the mean squared reconstruction error is %s per standardized column and the mean KL is %s nats; %d rows with a loss of at least %s are flagged as anomalies.",
                   length(rows), LATENT, if (LATENT != 1L) "s" else "", active, format(signif(mean(errors), 3)), format(signif(mean(fit$kl_row), 3)),
                   sum(flags), format(signif(threshold, 3)))
if (length(sample_ks)) summary <- paste0(summary, sprintf(" %d rows generated from the prior differ from the data by a mean KS distance of %.3f.", N_SAMPLES, values$sample_ks_mean))
if (!is.null(clusters)) summary <- paste0(summary, sprintf(" The mixture prior's %d components hold %d cluster%s of rows.", length(fit$pi), length(comp_of), if (length(comp_of) != 1L) "s" else ""))
if (!is.null(bound)) summary <- paste0(summary, sprintf(" The importance-weighted bound with %d draws is %s nats per row (%s above the ELBO estimate).", IWAE,
                                                       format(signif(values$iwae_bound, 4)), format(signif(values$iwae_gap, 3))))
extra_stats <- list()
if (!is.null(bound)) extra_stats[[1]] <- list(key = "iwae_bound", label = sprintf("Log-likelihood bound (IWAE, %d draws)", IWAE), value = values$iwae_bound)
extra_tables <- list()
if (!is.null(clusters)) {
  ordj <- as.integer(names(comp_of))[order(comp_of)]
  extra_tables[[1]] <- list(
    key = "components", title = "Mixture prior components",
    columns = c(list(list(key = "cluster", label = "Component", type = "integer"), list(key = "size", label = "Rows", type = "integer"),
                     list(key = "weight", label = "Prior weight", type = "number")),
                lapply(seq_len(LATENT), function(d) list(key = sprintf("mu_%d", d), label = sprintf("Mean %d", d), type = "number"))),
    rows = lapply(ordj, function(j) {
      cc <- comp_of[[as.character(j)]]
      r <- list(cluster = cc, size = sum(clusters == cc), weight = fit$pi[j])
      for (d in seq_len(LATENT)) r[[sprintf("mu_%d", d)]] <- fit$mu_c[j, d]
      r
    })
  )
}
cs_publish(list(
  title = "Variational autoencoder (latent map, anomalies and generated rows)",
  engine = cs_engine_info("torch", "nanoparquet"),
  n = length(rows),
  summary = summary,
  statistics = c(list(
    list(key = "recon_mse", label = "Mean reconstruction error", value = mean(errors)),
    list(key = "kl", label = "Mean KL (nats per row)", value = mean(fit$kl_row)),
    list(key = "active_dims", label = "Active latent dimensions", value = active, format = "integer"),
    list(key = "trustworthiness", label = sprintf("Trustworthiness (k = %d)", k_eval), value = trust),
    list(key = "n_flagged", label = "Anomalies", value = sum(flags), format = "integer")
  ), extra_stats),
  tables = c(list(
    list(
      key = "top", title = "Rows the model finds least typical",
      columns = c(list(list(key = "rank", label = "Rank", type = "integer"), list(key = "row", label = "Row", type = "integer"),
                       list(key = "score", label = "Per-row loss", type = "number")),
                  lapply(FEATURES, function(f) list(key = f, label = f))),
      rows = table_rows
    ),
    list(
      key = "latent", title = "Latent dimensions",
      columns = list(list(key = "dim", label = "Dimension", type = "integer"), list(key = "kl", label = "Mean KL (nats)", type = "number"),
                     list(key = "var_mu", label = "Variance of μ", type = "number"), list(key = "active", label = "Active", type = "boolean")),
      rows = dim_rows
    )
  ), extra_tables),
  charts = charts,
  assumptions = assumptions,
  values = values,
  warnings = warnings,
  artifacts = artifacts
))
Python

A variational autoencoder mapped 532 rows into 2 latent coordinates (2 in use); the mean squared reconstruction error is 0.492 per standardized column and the mean KL is 1.26 nats; 27 rows with a loss of at least 11 are flagged as anomalies. The importance-weighted bound with 50 draws is -9.442 nats per row (0.0661 above the ELBO estimate).

Mean reconstruction error
0.4918
Mean KL (nats per row)
1.262
Active latent dimensions
2
Trustworthiness (k = 10)
0.8356
Anomalies
27
Log-likelihood bound (IWAE, 50 draws)
−9.442

Assumptions

  • Latent dimensions in use — 2 of 2 latent dimensions vary across rows (variance of μ > 0.01).

Rows the model finds least typical

RankRowPer-row lossnpregglubpskinbmipedage
115741.5002197709934.7000.575062
239836.1730180786359.4002.42025
31133.5480137403543.1002.28833
429629.8984197703936.7002.32931
536222.1643173824838.4002.13725
627920.47901291104667.1000.319026
725719.6381883042550.496026
822218.12201806639421.89325
946015.515282522228.5001.69925
104815.056292762024.2001.69828
1120814.2221103303843.3000.183033
1240312.8669134743325.9000.460081
131312.5721189602330.1000.398059
1441712.5190173783246.5001.15958
1537512.3022127582427.7001.60025
1649112.30110681062335.5000.285047
1727212.25217163724140.9000.817047
1811112.11241891103128.5000.680037
1935812.04951031083739.2000.305065
2039612.04601891042534.3000.435041

Latent dimensions

DimensionMean KL (nats)Variance of μActive
10.53170.6583yes
20.72990.8052yes
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Variational autoencoder (latent map, anomalies and generated rows)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.vae 1.2.0 · spec 4fb7211679042758
# Dataset: ml_pima (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os

import numpy as np
import pandas as pd

import codesplash as cs
from codesplash import ml as csml
from codesplash.deep import generative as gen  # twin of codesplashr::cs_deep_fit_vae (shared initial weights, Adam written out)
from codesplash.deep import unsupervised as du  # VaDE prior and the importance-weighted bound (twin of codesplashr::cs_deep_fit_vade)
from codesplash.ml import anomaly as csanom
from codesplash.ml import embed as csembed
from codesplash.synth import common as sy

# %% Data — standardized numbers (median-imputed), one-hot categories
IMPUTE = "median"
SCALE = "standard"
cs.check_finite_columns(pd.read_parquet("tests/parity/fixtures/ml_pima.parquet", columns=["npreg", "glu", "bp", "skin", "bmi", "ped", "age"]), ["npreg", "glu", "bp", "skin", "bmi", "ped", "age"])
from codesplash.deep import trainer as deep_trainer  # training options, live progress, checkpoints (twin: cs_deep_trainer_*)

deep_trainer.configure(
    {
        "optimizer": "default",
        "lr_schedule": "none",
        "warmup_epochs": 0,
        "grad_clip": 0,
        "ema_decay": 0,
        "swa_start": 0,
        "history_every_step": False,
        "profile": "parity",
        "checkpoint_every": None,
    },
    out_dir="target/academy-parity/run-8142/discover.vae/pima_iwae_normal/out-python",
)
FEATURES = ["npreg", "glu", "bp", "skin", "bmi", "ped", "age"]
df = pd.read_parquet("tests/parity/fixtures/ml_pima.parquet", columns=FEATURES)
warnings = []
design = csml.Design.for_frame(
    df,
    FEATURES,
    kinds={
        "npreg": "numeric",
        "glu": "numeric",
        "bp": "numeric",
        "skin": "numeric",
        "bmi": "numeric",
        "ped": "numeric",
        "age": "numeric",
    },
    levels={
    },
    impute=IMPUTE,
    scale=SCALE,
)
fitted = design.fit(df)
X = fitted.transform(df)  # numbers imputed / scaled; categories one-hot (missing → all zero)
rows = np.arange(len(df))
LABEL = None
if LABEL:
    df[LABEL] = pd.read_parquet("tests/parity/fixtures/ml_pima.parquet", columns=[LABEL])[LABEL]

# %% Variational autoencoder (PyTorch, float64, one thread): encoder → (μ, log σ²) → z = μ + σ·ε → decoder
HIDDEN = [int(u) for u in [12]]
LATENT = 2
BETA = 1
N_SAMPLES = 0
PRIOR = "normal"  # N(0, I), or a learned Gaussian mixture (VaDE)
IWAE = 50
if PRIOR == "mixture" and len(rows) <= 3:
    cs.cs_error("CS_E_TOO_FEW_ROWS", what="A 3-component mixture prior", min=3 + 1, n=len(rows))
if PRIOR == "mixture":
    fit = du.fit_vade(
        X, HIDDEN, LATENT, 3,
        activation="tanh",
        beta=BETA,
        epochs=100,
        lr=0.005,
        batch_size=128,
        weight_decay=0,
        n_samples=N_SAMPLES,
        pretrain_epochs=100,
        seed=42,
    )
else:
    fit = gen.fit_vae(
        X, HIDDEN, LATENT,
        activation="tanh",
        beta=BETA,
        epochs=100,
        lr=0.005,
        batch_size=128,
        weight_decay=0,
        n_samples=N_SAMPLES,
        seed=42,
    )
if not np.all(np.isfinite(fit["score"])):
    cs.cs_error("CS_E_NO_CONVERGENCE", what="Variational autoencoder training")
Z = fit["embedding"]  # posterior means μ (n × LATENT)
scores = fit["score"]  # squared reconstruction error at z = μ plus β × KL, per row
errors = fit["error"]  # mean squared reconstruction error per standardized column

# %% Anomalies by the per-row loss
RULE = "share"
flags, threshold = csanom.flag(scores, RULE, 0.05, 10)
order = np.lexsort((rows, -scores))  # largest loss first, ties by row

# %% Neighborhood preservation of the map (same rows in both engines)
sample = csembed.sample_rows(len(rows))
k_eval = min(10, len(sample) - 2)
trust = csembed.trustworthiness(X[sample], Z[sample], k_eval) if k_eval >= 1 else float("nan")  # undefined with fewer than 3 rows

# %% Mixture prior: each row's component at z = μ (canonical ids 1…k by size)
clusters = None
if PRIOR == "mixture":
    from codesplash.ml import cluster as csc

    clusters = csc.canonical(fit["cluster"])
    comp_of = {}
    for j in range(len(fit["pi"])):
        members = np.flatnonzero(fit["cluster"] == j)
        if len(members):
            comp_of[j] = int(clusters[members[0]])

# %% Importance-weighted bound on log p(x) (and the ELBO from the same draws)
bound = du.iwae_bound(X, fit, LATENT, "tanh", IWAE, 42) if IWAE > 0 else None

# %% Generated rows: decode prior draws back to the columns' units
gen_cols = gen.decode_design(fitted, fit["samples"]) if N_SAMPLES > 0 else {}
NUMERIC = [f for f in FEATURES if design.kinds[f] == "numeric"]
sample_ks = {}
for f in NUMERIC if N_SAMPLES > 0 else []:
    real = pd.to_numeric(df[f], errors="coerce").to_numpy(dtype=np.float64)
    sample_ks[f] = gen.ks_distance(real, gen_cols[f])

# %% Artifacts
out = csml.out_dir("target/academy-parity/run-8142/discover.vae/pima_iwae_normal/out-python")
emb = pd.DataFrame({"row": rows.astype(np.int64), **{f"dim_{j + 1}": Z[:, j] for j in range(LATENT)}})
emb.to_parquet(os.path.join(out, "embedding.parquet"), index=False)
pd.DataFrame({"row": rows.astype(np.int64), "score": scores, "anomaly": flags, **({"cluster": clusters} if clusters is not None else {})}).to_parquet(
    os.path.join(out, "labels.parquet"), index=False
)
history = pd.DataFrame({
    "epoch": [h["epoch"] for h in fit["history"]],
    "loss": [h["loss"] for h in fit["history"]],
    "reconstruction": [h["recon"] for h in fit["history"]],
    "kl": [h["kl"] for h in fit["history"]],
})
history.to_parquet(os.path.join(out, "history.parquet"), index=False)
artifacts = [
    {"key": "embedding", "path": os.path.join(out, "embedding.parquet"), "format": "parquet"},
    {"key": "labels", "path": os.path.join(out, "labels.parquet"), "format": "parquet"},
    {"key": "history", "path": os.path.join(out, "history.parquet"), "format": "parquet"},
]
if N_SAMPLES > 0:
    pd.DataFrame({f: gen_cols[f] for f in FEATURES}).to_parquet(os.path.join(out, "samples.parquet"), index=False)
    artifacts.append({"key": "samples", "path": os.path.join(out, "samples.parquet"), "format": "parquet", "title": "Rows generated from the prior"})

# %% Result
active = int(fit["active"])
values = {
    "n": len(rows),
    "n_features": int(X.shape[1]),
    "latent_dim": LATENT,
    "recon_mse": float(np.mean(errors)),
    "kl": float(np.mean(fit["kl_row"])),
    "elbo_loss": float(np.mean(scores)),
    "active_dims": active,
    "error_check": csembed.checksum(scores, rows),
    "n_flagged": int(flags.sum()),
    "threshold": float(threshold),
    "final_loss": float(fit["history"][-1]["loss"]),
    "epochs_run": int(fit["epochs_run"]),
    "trustworthiness": trust,
    "n_samples": N_SAMPLES,
    "sample_ks_mean": float(np.mean(list(sample_ks.values()))) if sample_ks else float("nan"),
}
for j in range(LATENT):
    values[f"emb_check[{j + 1}]"] = csembed.checksum(Z[:, j], rows)
    values[f"kl_dim[{j + 1}]"] = float(fit["kl_dim"][j])
for f, v in sample_ks.items():
    values[f"sample_ks[{f}]"] = v
if clusters is not None:
    values["components"] = int(len(fit["pi"]))
    values["n_clusters"] = len(comp_of)
    for j, c in comp_of.items():
        values[f"pi[{c}]"] = float(fit["pi"][j])
        values[f"cluster_size[{c}]"] = int(np.sum(clusters == c))
if bound is not None:
    values["iwae_samples"] = IWAE
    values["iwae_bound"] = float(np.mean(bound["iwae"]))
    values["elbo_estimate"] = float(np.mean(bound["elbo"]))
    values["iwae_gap"] = values["iwae_bound"] - values["elbo_estimate"]
for rank, i in enumerate(order[:10], start=1):
    values[f"top_row[{rank}]"] = int(rows[i])
    values[f"top_score[{rank}]"] = float(scores[i])
table_rows = []
for rank, i in enumerate(order[:20], start=1):
    r = {"rank": rank, "row": int(rows[i]) + 1, "score": float(scores[i])}
    for f in FEATURES:
        v = df[f].iloc[rows[i]]
        r[f] = None if pd.isna(v) else (v if isinstance(v, (int, float)) else str(v))  # None, NaN, pd.NA, NaT
    table_rows.append(r)
dim_rows = [{"dim": j + 1, "kl": float(fit["kl_dim"][j]), "var_mu": float(fit["mu_var"][j]), "active": bool(fit["mu_var"][j] > 0.01)} for j in range(LATENT)]
pick = csembed.sample_rows(len(rows), 5000)
groups = [("All rows" if LABEL is None else ("(missing)" if pd.isna(v) else str(v))) for v in (df[LABEL].iloc[rows[pick]] if LABEL else [None] * len(pick))]
charts = []
if LATENT >= 2 and clusters is not None:
    _cent = sorted(comp_of, key=lambda j: comp_of[j])
    charts.append(cs.chart("latent", "cluster-scatter", "Latent means by mixture component (component means marked)", {
        "x": cs.col("Latent 1 (μ)", list(Z[pick, 0]) + [float(fit["mu_c"][j, 0]) for j in _cent], "numeric"),
        "y": cs.col("Latent 2 (μ)", list(Z[pick, 1]) + [float(fit["mu_c"][j, 1]) for j in _cent], "numeric"),
        "cluster": cs.col("Component", [str(c) for c in clusters[pick]] + [str(comp_of[j]) for j in _cent], "categorical",
                          levels=[str(c) for c in sorted(comp_of.values())]),
        "centroid": cs.col("Component mean", [False] * len(pick) + [True] * len(_cent), "boolean"),
    }, note=None if len(pick) == len(rows) else f"{len(pick):,} of {len(rows):,} rows shown."))
elif LATENT >= 2:
    charts.append(cs.chart("latent", "latent-prior", "Latent means against the N(0, I) prior", {
        "x": cs.col("Latent 1 (μ)", Z[pick, 0], "numeric"),
        "y": cs.col("Latent 2 (μ)", Z[pick, 1], "numeric"),
        "group": cs.col(LABEL or "Group", groups, "categorical"),
    }, note=None if len(pick) == len(rows) else f"{len(pick):,} of {len(rows):,} rows shown."))
charts.append(cs.chart("errors", "anomaly-scores", "Per-row loss (reconstruction + β·KL) distribution", {
    "score": cs.col("Per-row loss", scores, "numeric"),
    "anomaly": cs.col("Anomaly", [bool(x) for x in flags], "boolean"),
}, controls={"threshold": float(threshold)}))
ep = [h["epoch"] for h in fit["history"]]
charts.append(cs.chart("training", "training-components", "Training loss and its parts by epoch", {
    "x": cs.col("Epoch", ep * 3, "numeric"),
    "value": cs.col("Loss per row", [h["loss"] for h in fit["history"]] + [h["recon"] for h in fit["history"]] + [h["kl"] for h in fit["history"]], "numeric"),
    "component": cs.col("Part", ["total"] * len(ep) + ["reconstruction"] * len(ep) + ["KL"] * len(ep), "categorical", levels=["total", "reconstruction", "KL"]),
}))
if sample_ks:
    f0 = NUMERIC[0]
    xs, dens, src = sy.density_rows(pd.to_numeric(df[f0], errors="coerce").to_numpy(dtype=np.float64), np.asarray(gen_cols[f0], dtype=np.float64))
    if xs:
        charts.append(cs.chart("samples", "density-compare", f"{f0}: data vs rows generated from the prior", {
            "x": cs.col(f0, xs, "numeric"),
            "density": cs.col("Density", dens, "numeric"),
            "source": cs.col("Source", src, "categorical", levels=["real", "synthetic"]),
        }))
assumptions = [{
    "key": "active_units",
    "label": "Latent dimensions in use",
    "status": "pass" if active == LATENT else ("fail" if active == 0 else "warn"),
    "detail": f"{active} of {LATENT} latent dimension{'s' if LATENT != 1 else ''} vary across rows (variance of μ > 0.01)"
              + ("." if active == LATENT else "; the rest collapsed onto the prior and carry no information about the rows."),
}]
if active < LATENT:
    warnings.append(f"Posterior collapse: {LATENT - active} latent dimension{'s' if LATENT - active != 1 else ''} carry no information (KL ≈ 0). Lower β, shrink the bottleneck, or train longer.")
summary = (
    f"A variational autoencoder mapped {len(rows)} rows into {LATENT} latent coordinate{'s' if LATENT != 1 else ''} "
    f"({active} in use); the mean squared reconstruction error is {np.mean(errors):.3g} per standardized column and the mean KL is "
    f"{np.mean(fit['kl_row']):.3g} nats; {int(flags.sum())} rows with a loss of at least {threshold:.3g} are flagged as anomalies."
)
if sample_ks:
    summary += f" {N_SAMPLES} rows generated from the prior differ from the data by a mean KS distance of {values['sample_ks_mean']:.3f}."
if clusters is not None:
    summary += f" The mixture prior's {len(fit['pi'])} components hold {len(comp_of)} cluster{'s' if len(comp_of) != 1 else ''} of rows."
if bound is not None:
    summary += f" The importance-weighted bound with {IWAE} draws is {values['iwae_bound']:.4g} nats per row ({values['iwae_gap']:.3g} above the ELBO estimate)."
extra_stats = []
if bound is not None:
    extra_stats.append({"key": "iwae_bound", "label": f"Log-likelihood bound (IWAE, {IWAE} draws)", "value": values["iwae_bound"]})
extra_tables = []
if clusters is not None:
    extra_tables.append({
        "key": "components",
        "title": "Mixture prior components",
        "columns": [{"key": "cluster", "label": "Component", "type": "integer"}, {"key": "size", "label": "Rows", "type": "integer"},
                    {"key": "weight", "label": "Prior weight", "type": "number"}]
                   + [{"key": f"mu_{d + 1}", "label": f"Mean {d + 1}", "type": "number"} for d in range(LATENT)],
        "rows": [{"cluster": comp_of[j], "size": int(np.sum(clusters == comp_of[j])), "weight": float(fit["pi"][j]),
                  **{f"mu_{d + 1}": float(fit["mu_c"][j, d]) for d in range(LATENT)}} for j in sorted(comp_of, key=lambda j: comp_of[j])],
    })
cs.publish({
    "title": "Variational autoencoder (latent map, anomalies and generated rows)",
    "engine": cs.engine_info("torch", "numpy", "pandas"),
    "n": len(rows),
    "summary": summary,
    "statistics": [
        {"key": "recon_mse", "label": "Mean reconstruction error", "value": float(np.mean(errors))},
        {"key": "kl", "label": "Mean KL (nats per row)", "value": float(np.mean(fit["kl_row"]))},
        {"key": "active_dims", "label": "Active latent dimensions", "value": active, "format": "integer"},
        {"key": "trustworthiness", "label": f"Trustworthiness (k = {k_eval})", "value": trust},
        {"key": "n_flagged", "label": "Anomalies", "value": int(flags.sum()), "format": "integer"},
    ] + extra_stats,
    "tables": [
        {
            "key": "top",
            "title": "Rows the model finds least typical",
            "columns": [{"key": "rank", "label": "Rank", "type": "integer"}, {"key": "row", "label": "Row", "type": "integer"},
                        {"key": "score", "label": "Per-row loss", "type": "number"}] + [{"key": f, "label": f} for f in FEATURES],
            "rows": table_rows,
        },
        {
            "key": "latent",
            "title": "Latent dimensions",
            "columns": [{"key": "dim", "label": "Dimension", "type": "integer"}, {"key": "kl", "label": "Mean KL (nats)", "type": "number"},
                        {"key": "var_mu", "label": "Variance of μ", "type": "number"}, {"key": "active", "label": "Active", "type": "boolean"}],
            "rows": dim_rows,
        },
    ] + extra_tables,
    "charts": charts,
    "assumptions": assumptions,
    "values": values,
    "warnings": warnings,
    "artifacts": artifacts,
})

Shortened for the Academy: 3 chart(s) dropped to stay under 100 KB; 3 chart(s) dropped to stay under 100 KB.

A variational autoencoder doesn't give an exact likelihood. This one reports an evidence bound of −9.51 nats per row and a tighter importance-weighted bound of −9.44, 0.066 higher. Both are lower bounds on the log-likelihood, not the log-likelihood itself. Compare models with the same estimator, and never compare a bound from one model with an exact likelihood from another.

07

Centered kernel alignment

Read

CKACentered kernel alignmentSimilarity of two embeddings of the same rows: 1 = same up to rotation and overall scale, near 0 = unrelated. compares two representations of the same rows by how similarly they arrange pairs:

CKA(K,L)=⟨HKH,HLH⟩F∥HKH∥F∥HLH∥F.\mathrm{CKA}(K, L) = \frac{\langle HKH, HLH \rangle_F}{\lVert HKH\rVert_F \lVert HLH\rVert_F}.

Linear CKA is unchanged by rotation and overall scale: in the reference's example, a rotated copy scores 1. Use it to see whether two layers, seeds or training stages arrange the inputs alike, on held-out inputs.

Reference · EVA058 · Runs in CodeSplashCentered kernel alignmentCompares representational geometry across neural layers, models, or training stages.
08

Global agreement, local disagreement

Explore
Compare two embeddings (CKA, Procrustes, kNN overlap)Recorded · Python and R agreeRecorded 2026-11-21 · 15 values compared
R

Linear CKA 0.96, RBF CKA 0.94, Procrustes r 0.98; 32% of each row's 5 nearest neighbors agree.

Linear CKA
0.9628
Procrustes r
0.9766
kNN overlap
31.5%

Agreement between the embeddings

IndexValueReading
Linear CKA (RV coefficient)0.96281 = same up to rotation and scale
Debiased linear CKA0.9627corrects the upward bias with few rows or many columns
RBF CKA0.9371more weight on local structure
Procrustes disparity0.04630 = same up to shift, rotation and scale
Procrustes r0.9766√(1 − disparity)
kNN overlap (k = 5)0.3154share of shared nearest neighbors
Distance rank correlation0.9514Spearman ρ of pairwise distances
Permutation p (linear CKA, 99 shuffles)0.0100small = more alike than unrelated rows
  • 1 of 150 rows were left out because a coordinate was missing.
The exact R script · R R version 4.5.1 (2025-06-13)
# Compare two embeddings (CKA, Procrustes, kNN overlap)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.compare_embeddings 1.0.0 · spec 8b4783d33b87c351
# Dataset: clu4_embeddings (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data
COLS_A <- c("pc1", "pc2")
COLS_B <- c("nz1", "nz2")
SEED <- 42
K <- 5
WIDTH <- as.numeric(0.5)
SCALE <- "none"
PERMS <- 99
CAP <- 2000
cols <- unique(c(COLS_A, COLS_B))
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/clu4_embeddings.parquet", col_select = cols))
n_input <- nrow(df)
cs_check_finite_columns(df, cols)  # ±Inf stops with CS_E_NOT_FINITE in both engines
rows <- cs_ml_complete_rows(df, cols)
warnings <- list()
if (length(rows) < n_input) warnings <- c(warnings, sprintf("%d of %d rows were left out because a coordinate was missing.", n_input - length(rows), n_input))
cs_check_rows(length(rows), 4, "Comparing two embeddings")
A <- cs_ml_numeric_matrix(df, COLS_A, rows)
B <- cs_ml_numeric_matrix(df, COLS_B, rows)
if (all(apply(A, 2, function(v) max(v) - min(v)) == 0)) cs_error("CS_E_CONSTANT", column = paste(COLS_A, collapse = ", "))
if (all(apply(B, 2, function(v) max(v) - min(v)) == 0)) cs_error("CS_E_CONSTANT", column = paste(COLS_B, collapse = ", "))
standardize <- function(X) {
  flat <- apply(X, 2, function(v) max(v) - min(v)) == 0
  s <- apply(X, 2, stats::sd)
  s[flat] <- 1
  X <- sweep(sweep(X, 2, colMeans(X)), 2, s, "/")
  X[, flat] <- 0  # constant columns exactly 0 in both engines
  X
}
if (SCALE == "standardize") {
  A <- standardize(A)
  B <- standardize(B)
}

# %% Agreement indices
r <- cs_ml_compare_embeddings(A, B, K, WIDTH, CAP)
p_perm <- if (PERMS > 0) cs_ml_cka_permutation_p(A, B, r$linear_cka, PERMS, cs_rng(SEED)) else NULL
keys <- c("n", "n_sub", "dims_a", "dims_b", "linear_cka", "debiased_cka", "rbf_cka", "sigma_a", "sigma_b",
          "procrustes_disparity", "procrustes_r", "knn_overlap", "k_used", "distance_spearman")
values <- r[keys]
values["p_permutation"] <- list(p_perm)
if (r$n_sub < r$n) warnings <- c(warnings, sprintf("RBF and debiased CKA, kNN overlap and the distance correlation use %s evenly spaced rows of %s.",
                                                   format(r$n_sub, big.mark = ","), format(r$n, big.mark = ",")))
idx_rows <- list(
  list(index = "Linear CKA (RV coefficient)", value = values$linear_cka, reading = "1 = same up to rotation and scale"),
  list(index = "Debiased linear CKA", value = values$debiased_cka, reading = "corrects the upward bias with few rows or many columns"),
  list(index = "RBF CKA", value = values$rbf_cka, reading = "more weight on local structure"),
  list(index = "Procrustes disparity", value = values$procrustes_disparity, reading = "0 = same up to shift, rotation and scale"),
  list(index = "Procrustes r", value = values$procrustes_r, reading = "√(1 − disparity)"),
  list(index = sprintf("kNN overlap (k = %d)", values$k_used), value = values$knn_overlap, reading = "share of shared nearest neighbors"),
  list(index = "Distance rank correlation", value = values$distance_spearman, reading = "Spearman ρ of pairwise distances")
)
if (!is.null(p_perm)) idx_rows[[length(idx_rows) + 1L]] <- list(index = sprintf("Permutation p (linear CKA, %d shuffles)", PERMS), value = p_perm, reading = "small = more alike than unrelated rows")
tables <- list(list(key = "indices", title = "Agreement between the embeddings",
                    columns = list(list(key = "index", label = "Index", type = "string"), list(key = "value", label = "Value", type = "number"),
                                   list(key = "reading", label = "Reading", type = "string")),
                    rows = idx_rows))

# %% Charts
da <- r$dist_a
db <- r$dist_b
pick <- cs_ml_even_sample(length(da), 3000) + 1L
note1 <- paste0(if (length(pick) == length(da)) "" else sprintf("%s of %s row pairs shown. ", format(length(pick), big.mark = ","), format(length(da), big.mark = ",")),
                "Points on a rising curve mean the two maps keep the same global layout.")
charts <- list(
  cs_chart("distances", "scatter", "Pairwise distances in A and B",
           list(x = cs_col("Distance in A", da[pick], "numeric"), y = cs_col("Distance in B", db[pick], "numeric")), note = note1),
  cs_chart("overlap", "histogram", sprintf("Share of each row's %d nearest neighbors shared", values$k_used),
           list(x = cs_col("kNN overlap", r$knn_rows, "numeric")), controls = list(kde = FALSE),
           note = "Rows near 0 sit in different neighborhoods in the two maps.")
)

# %% Result
cs_publish(list(
  title = "Compare two embeddings (CKA, Procrustes, kNN overlap)",
  engine = cs_engine_info("codesplashr", "nanoparquet"),
  n = values$n,
  summary = sprintf("Linear CKA %.2f, RBF CKA %.2f, Procrustes r %.2f; %.0f%% of each row's %d nearest neighbors agree.",
                    values$linear_cka, values$rbf_cka, values$procrustes_r, values$knn_overlap * 100, values$k_used),
  statistics = list(list(key = "linear_cka", label = "Linear CKA", value = values$linear_cka),
                    list(key = "procrustes_r", label = "Procrustes r", value = values$procrustes_r),
                    list(key = "knn_overlap", label = "kNN overlap", value = values$knn_overlap, format = "percent")),
  tables = tables,
  values = values,
  charts = charts,
  warnings = warnings
))
Python

Linear CKA 0.96, RBF CKA 0.94, Procrustes r 0.98; 32% of each row's 5 nearest neighbors agree.

Linear CKA
0.9628
Procrustes r
0.9766
kNN overlap
31.5%

Agreement between the embeddings

IndexValueReading
Linear CKA (RV coefficient)0.96281 = same up to rotation and scale
Debiased linear CKA0.9627corrects the upward bias with few rows or many columns
RBF CKA0.9371more weight on local structure
Procrustes disparity0.04630 = same up to shift, rotation and scale
Procrustes r0.9766√(1 − disparity)
kNN overlap (k = 5)0.3154share of shared nearest neighbors
Distance rank correlation0.9514Spearman ρ of pairwise distances
Permutation p (linear CKA, 99 shuffles)0.0100small = more alike than unrelated rows
  • 1 of 150 rows were left out because a coordinate was missing.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Compare two embeddings (CKA, Procrustes, kNN overlap)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.compare_embeddings 1.0.0 · spec 8b4783d33b87c351
# Dataset: clu4_embeddings (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.ml import cluster as csc
from codesplash.ml import cluster_compare as cc
from codesplash.ml import embed as csembed
from codesplash.stats.rng import Rng

# %% Data
COLS_A = ["pc1", "pc2"]
COLS_B = ["nz1", "nz2"]
SEED = 42
K = 5
WIDTH = float(0.5)
SCALE = "none"
PERMS = 99
CAP = 2000
cols = list(dict.fromkeys(COLS_A + COLS_B))
df = pd.read_parquet("tests/parity/fixtures/clu4_embeddings.parquet", columns=cols)
n_input = len(df)
cs.check_finite_columns(df, cols)  # ±Inf stops with CS_E_NOT_FINITE in both engines
rows = csembed.complete_rows(df, cols)
warnings = []
if len(rows) < n_input:
    warnings.append(f"{n_input - len(rows)} of {n_input} rows were left out because a coordinate was missing.")
cs.check_rows(len(rows), 4, "Comparing two embeddings")
A = csembed.numeric_matrix(df, COLS_A, rows)
B = csembed.numeric_matrix(df, COLS_B, rows)
if np.all(np.ptp(A, axis=0) == 0):
    cs.cs_error("CS_E_CONSTANT", column=", ".join(COLS_A))
if np.all(np.ptp(B, axis=0) == 0):
    cs.cs_error("CS_E_CONSTANT", column=", ".join(COLS_B))
if SCALE == "standardize":
    fa, fb = np.ptp(A, axis=0) == 0, np.ptp(B, axis=0) == 0
    A = csembed.standardize(A, ddof=1)
    B = csembed.standardize(B, ddof=1)
    A[:, fa] = 0.0  # constant columns exactly 0 in both engines
    B[:, fb] = 0.0

# %% Agreement indices
r = cc.compare_embeddings(A, B, K, WIDTH, CAP)
p_perm = cc.permutation_p(A, B, r["linear_cka"], PERMS, Rng(SEED)) if PERMS > 0 else None
keys = ["n", "n_sub", "dims_a", "dims_b", "linear_cka", "debiased_cka", "rbf_cka", "sigma_a", "sigma_b",
        "procrustes_disparity", "procrustes_r", "knn_overlap", "k_used", "distance_spearman"]
values = {k: r[k] for k in keys}
values["p_permutation"] = p_perm
if r["n_sub"] < r["n"]:
    warnings.append(f"RBF and debiased CKA, kNN overlap and the distance correlation use {r['n_sub']:,} evenly spaced rows of {r['n']:,}.")
tables = [{
    "key": "indices",
    "title": "Agreement between the embeddings",
    "columns": [{"key": "index", "label": "Index", "type": "string"}, {"key": "value", "label": "Value", "type": "number"},
                {"key": "reading", "label": "Reading", "type": "string"}],
    "rows": [
        {"index": "Linear CKA (RV coefficient)", "value": values["linear_cka"], "reading": "1 = same up to rotation and scale"},
        {"index": "Debiased linear CKA", "value": values["debiased_cka"], "reading": "corrects the upward bias with few rows or many columns"},
        {"index": "RBF CKA", "value": values["rbf_cka"], "reading": "more weight on local structure"},
        {"index": "Procrustes disparity", "value": values["procrustes_disparity"], "reading": "0 = same up to shift, rotation and scale"},
        {"index": "Procrustes r", "value": values["procrustes_r"], "reading": "√(1 − disparity)"},
        {"index": f"kNN overlap (k = {values['k_used']})", "value": values["knn_overlap"], "reading": "share of shared nearest neighbors"},
        {"index": "Distance rank correlation", "value": values["distance_spearman"], "reading": "Spearman ρ of pairwise distances"},
    ] + ([{"index": f"Permutation p (linear CKA, {PERMS} shuffles)", "value": p_perm, "reading": "small = more alike than unrelated rows"}] if p_perm is not None else []),
}]

# %% Charts
da, db = r["dist_a"], r["dist_b"]
pick = csc.even_sample(len(da), 3000)
charts = [
    cs.chart(
        "distances", "scatter", "Pairwise distances in A and B",
        {"x": cs.col("Distance in A", list(da[pick]), "numeric"), "y": cs.col("Distance in B", list(db[pick]), "numeric")},
        note=("" if len(pick) == len(da) else f"{len(pick):,} of {len(da):,} row pairs shown. ") + "Points on a rising curve mean the two maps keep the same global layout.",
    ),
    cs.chart(
        "overlap", "histogram", f"Share of each row's {values['k_used']} nearest neighbors shared",
        {"x": cs.col("kNN overlap", list(r["knn_rows"]), "numeric")},
        controls={"kde": False},
        note="Rows near 0 sit in different neighborhoods in the two maps.",
    ),
]

# %% Result
cs.publish({
    "title": "Compare two embeddings (CKA, Procrustes, kNN overlap)",
    "engine": cs.engine_info("numpy", "pandas"),
    "n": values["n"],
    "summary": (
        f"Linear CKA {values['linear_cka']:.2f}, RBF CKA {values['rbf_cka']:.2f}, Procrustes r {values['procrustes_r']:.2f}; "
        f"{values['knn_overlap'] * 100:.0f}% of each row's {values['k_used']} nearest neighbors agree."
    ),
    "statistics": [
        {"key": "linear_cka", "label": "Linear CKA", "value": values["linear_cka"]},
        {"key": "procrustes_r", "label": "Procrustes r", "value": values["procrustes_r"]},
        {"key": "knn_overlap", "label": "kNN overlap", "value": values["knn_overlap"], "format": "percent"},
    ],
    "tables": tables,
    "values": values,
    "charts": charts,
    "warnings": warnings,
})

Shortened for the Academy: 2 chart(s) dropped to stay under 100 KB; 2 chart(s) dropped to stay under 100 KB.

A PCA map against a slightly noisy copy: linear CKA 0.96, yet only 32% of each row's 5 nearest neighbors agree. CKA is dominated by the large-scale layout; local neighborhoods can still differ a lot. Against random noise, linear CKA is 0.01 with permutation p = .670.

High CKA doesn't show the same computation or behavior; probes and ablations test that.

09

In CodeSplash

In the app

Discover's maps report trustworthiness and neighbor preservation. Choose the number of clusters compares BIC and ICL (MAP or soft entropy) for Gaussian mixtures; the mixture, latent class and blockmodel methods report ICL too. VAEs report the ELBO and, optionally, an importance-weighted bound. Compare two embeddings reports linear, RBF and debiased CKA, Procrustes and kNN overlap, with a permutation p-value.

A Discover run's Validity tab extends the single trustworthiness number to every neighborhood size: trustworthiness and continuity curves read off the co-ranking matrix, with Q_NX and LCMC. For PCA and autoencoders it adds held-out reconstruction by fold, with PCA as the yardstick. Held-out log scores for every density model aren't built yet; the reference's example runs as a notebook.

10

Check: maps and latent models

Checkpoint

Check yourself

A map has high trustworthiness and low continuity. What went wrong?

Show the answer

Answer: b

Trustworthiness checks map neighbors against the data; continuity checks data neighbors against the map.

Check yourself

A UMAP of unscaled columns has trustworthiness 0.98. What does it show?

Show the answer

Answer: b

Trustworthiness is relative to the input distance. Fix the distance first (scale, choose features), then check fidelity.

Check yourself

BIC prefers four components, ICL prefers three. Why might they differ?

Show the answer

Answer: a

BIC asks which mixture describes the density best; ICL asks which gives a confident partition. Different questions, different k.

Check yourself

A Gaussian mixture picks an extra small component on one side of a skewed cluster. What is the safest reading?

Show the answer

Answer: b

Gaussian components approximate any shape by adding pieces. A component isn't a population without other evidence.

Check yourself

An autoencoder with a latent size equal to the input reconstructs held-out rows almost perfectly. What does that show?

Show the answer

Answer: b

Perfect reconstruction is easy for an identity map. Compression or a held-out task makes the score informative.

Check yourself

Model A reports a held-out ELBO, model B an exact held-out log-likelihood, and B's number is higher. Is B better?

Show the answer

Answer: b

Compare like with like: the same estimator, or tight bounds on both.

Check yourself

One embedding is another rotated by 90 degrees and scaled by 3. What is their linear CKA?

Show the answer

Answer: a

Linear CKA compares centered Gram matrices up to scale; rotation leaves them unchanged.

Check yourself

Two embeddings have linear CKA 0.96, but only a third of each row's nearest neighbors agree. How can both hold?

Show the answer

Answer: b

Read a global score (CKA) and a local one (kNN overlap) together: they answer different questions.

11

Recap

Recap
  • Trustworthiness catches false neighbors, continuity torn neighborhoods; both are relative to the input distance.
  • BIC scores the density, ICL the partition; they can disagree, and a component isn't a population.
  • Score latent models on held-out data; an identity map reconstructs well, and a bound isn't a likelihood.
  • CKA compares global geometry up to rotation; check local neighbors too, and don't read it as same behavior.

Concepts in this lesson