Checking a representation: neighborhoods, CKA and stability
A map earns trust by passing checks that don't care how it looks. Measure neighborhoods both ways, compare two representations with CKA, Procrustes and neighbor overlap, and repeat across seeds and held-out rows.
What runs in CodeSplash
- EVA058Centered kernel alignment Runs in CodeSplash
- REP034t-distributed stochastic neighbor embedding (t-SNE) Runs in CodeSplash
- REP035Uniform manifold approximation and projection (UMAP) Runs in CodeSplash
- REP001Principal component analysis (PCA) Runs in CodeSplash
- Compare two embeddings (CKA, Procrustes, kNN overlap) Verified in Python and R
- Pair-based maps (PaCMAP, TriMap) Verified in Python and R
You will be able to
- Read trustworthiness and continuity across neighborhood sizes and say what each catches
- Compute linear CKA and explain what it is and isn't invariant to
- Combine CKA, Procrustes, neighbor overlap and distance correlation to judge whether two representations agree
- Plan a stability and held-out check before trusting a representation
Two directions of neighborhood error
ReadA map can fail locally in two ways:
- It glues strangers together: rows close on the map weren't close in the data. TrustworthinessTrustworthinessA 0–1 score for whether rows that look close on a map are really close in the data. catches this.
- It tears neighbors apart: rows close in the data ended up far apart. 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. catches this.
t-SNE and UMAP usually score well on the first and can lose on the second, because pulling groups apart separates some true neighbors. Compute both over a range of neighborhood sizes, not at one : a map that's good at can be poor at .
CKA: do two representations agree?
ReadTwo embeddings of the same rows, and , may have different dimensions and arbitrary rotations. Centered kernel alignmentCentered kernel alignmentSimilarity of two embeddings of the same rows: 1 = same up to rotation and overall scale, near 0 = unrelated. compares their similarity structure. With centered columns and linear kernels,
and in general for kernel matrices , . It is 1 when the two agree up to rotation and overall scale, near 0 when unrelated. In the reference's check, a rotated copy scores 1.
What CKA ignores, and what it doesn't
ReadCKA is unchanged by rotations, reflections and overall scaling, which is what you want when two runs of PCA differ by sign or two networks' layers differ by an arbitrary basis.
It does change under stretching one direction more than another, so it isn't fooled into calling every invertible linear transformation "the same". It is also biased upward for small samples and wide representations; the debiased estimator corrects that. Choose kernel, estimator and sample consistently when comparing several pairs.
Four comparisons on iris
ReadLinear CKA 0.89, RBF CKA 0.94, Procrustes r 0.94; 70% of each row's 10 nearest neighbors agree.
- Linear CKA
- 0.8851
- Procrustes r
- 0.9420
- kNN overlap
- 69.9%
Agreement between the embeddings
| Index | Value | Reading |
|---|---|---|
| Linear CKA (RV coefficient) | 0.8851 | 1 = same up to rotation and scale |
| Debiased linear CKA | 0.8843 | corrects the upward bias with few rows or many columns |
| RBF CKA | 0.9378 | more weight on local structure |
| Procrustes disparity | 0.1126 | 0 = same up to shift, rotation and scale |
| Procrustes r | 0.9420 | √(1 − disparity) |
| kNN overlap (k = 10) | 0.6993 | share of shared nearest neighbors |
| Distance rank correlation | 0.9313 | Spearman ρ of pairwise distances |
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 fdd6e14c4d641a21
# 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("f1", "f2", "f3", "f4")
COLS_B <- c("pc1", "pc2")
SEED <- 42
K <- 10
WIDTH <- as.numeric(1)
SCALE <- "standardize"
PERMS <- 0
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
))
Linear CKA 0.89, RBF CKA 0.94, Procrustes r 0.94; 70% of each row's 10 nearest neighbors agree.
- Linear CKA
- 0.8851
- Procrustes r
- 0.9420
- kNN overlap
- 69.9%
Agreement between the embeddings
| Index | Value | Reading |
|---|---|---|
| Linear CKA (RV coefficient) | 0.8851 | 1 = same up to rotation and scale |
| Debiased linear CKA | 0.8843 | corrects the upward bias with few rows or many columns |
| RBF CKA | 0.9378 | more weight on local structure |
| Procrustes disparity | 0.1126 | 0 = same up to shift, rotation and scale |
| Procrustes r | 0.9420 | √(1 − disparity) |
| kNN overlap (k = 10) | 0.6993 | share of shared nearest neighbors |
| Distance rank correlation | 0.9313 | Spearman ρ of pairwise distances |
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 fdd6e14c4d641a21
# 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 = ["f1", "f2", "f3", "f4"]
COLS_B = ["pc1", "pc2"]
SEED = 42
K = 10
WIDTH = float(1)
SCALE = "standardize"
PERMS = 0
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.
| Pair | Linear CKA | Procrustes r | Neighbor overlap |
|---|---|---|---|
| PCA vs. a rotated copy | 1 | 1 | 100% |
| four columns vs. 2-D PCA | 0.89 | 0.94 | 70% |
| PCA vs. PCA plus noise | 0.96 | 0.98 | 32% |
| PCA vs. pure noise | 0.007 | 0.07 | 16% |
Global agreement, local disagreement
ReadThe noisy copy agrees globally: CKA near 1 and a high Procrustes correlation. But only 32% of each row's 5 nearest neighbors survive. Small perturbations reshuffle close neighbors while leaving the overall layout intact.
So no single number decides. CKA and ProcrustesProcrustes disparitySquared mismatch left after shifting, rotating, reflecting and rescaling one embedding onto the other; 0 = identical. speak about global geometry; neighbor overlapkNN overlapAverage share of each row's k nearest neighbors that both embeddings agree on: local agreement. and trustworthiness speak about local structure. Against noise, the permutation p-value (0.67) confirms there is no agreement to explain.
Stability and held-out checks
ReadA representation should survive the things that shouldn't matter:
- Seeds. Refit t-SNE, UMAP, NMF or a network with another seed and compare with CKA and neighbor overlap.
- Subsamples. Refit on 80% of rows; check the shared rows still agree.
- Held-out rows. For parametric maps, measure reconstructionHeld-out reconstructionError rebuilding rows a model didn't see; unlike in-sample error, it rises when extra components only fit noise. or neighborhood scores on rows not used to fit.
- Downstream use. A linear probeLinear probeA penalized linear or logistic model trained on a frozen encoder's vectors; how well it does shows what the vectors already encode. on held-out rows tests whether the representation carries what you need.
High CKA between two models doesn't prove they behave the same on the task, or that either is "disentangled".
In CodeSplash
In the appDiscover → Compare two embeddings takes two sets of coordinates for the same rows (two saved maps, two seeds, or the original columns against a map) and reports linear, debiased and RBF CKA, Procrustes, neighbor overlap, distance correlation and, if you ask for permutations, a p-value. The map methods' Validity tab draws trustworthiness and continuity across neighborhood sizes.
Check: checking representations
CheckpointCheck yourself
A map has high trustworthiness but low continuity. What went wrong?
Show the answer
Answer: a
Trustworthiness guards against false neighbors on the map; continuity against lost neighbors.
Check yourself · choose all that apply
Which changes to one embedding leave its linear CKA with another unchanged? Pick all that apply.
Show the answer
Answer: a, b, d
CKA is invariant to orthogonal transformations and isotropic scaling, not to arbitrary invertible linear maps.
Check yourself
You compare two 500-dimensional layers on 60 inputs and get linear CKA 0.7. What should you check before reading it?
Show the answer
Answer: a
The debiased estimator removes the small-sample inflation. Use the same estimator for every comparison.
Check yourself
Two networks' final layers have CKA 0.95. What can you conclude?
Show the answer
Answer: a
Similar geometry can coexist with different decisions. Test behavior directly, with probes or ablations.
Check yourself
A UMAP map and a t-SNE map of the same data both score high trustworthiness but have very different global layouts. Which is right?
Show the answer
Answer: a
Trustworthiness is local. Compare global structure with CKA, distance correlation or a Shepard diagram, and expect neighbor embeddings to differ there.
Check yourself
How do you check that a 3-component PCA isn't fitting noise in its third component?
Show the answer
Answer: a
On the fitted rows, more components always explain more. Held-out reconstruction stops improving when a component is noise.
Recap
Recap- Trustworthiness catches false neighbors, continuity lost ones; read both across neighborhood sizes.
- CKA compares similarity structure up to rotation and scale; use the debiased version for small samples.
- Combine global (CKA, Procrustes) and local (neighbor overlap) checks with seeds, subsamples, held-out rows and probes.
Concepts in this lesson