Skip to content

CDiscover · discover.compare_embeddings

Compare two embeddings (CKA, Procrustes, kNN overlap)

Do two maps or embeddings of the same rows tell the same story — two methods, two seeds, or two layers?

Compares two sets of coordinates for the same rows. Centered kernel alignment (linear, debiased and RBF) is 1 when the two are the same up to rotation and overall scale and near 0 when unrelated; Procrustes disparity is 0 when one is a shifted, rotated, reflected and rescaled copy of the other; kNN overlap is the share of each row's nearest neighbors that both embeddings agree on; the rank correlation of pairwise distances checks the global layout. An optional permutation test asks whether the linear CKA is higher than for unrelated rows.

Verified in Python and R Python and R agree to 6 decimals Seeded Also called centered kernel alignment, CKA, linear CKA…

A real result

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

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

Linear CKA 1.00, RBF CKA 1.00, Procrustes r 1.00; 100% of each row's 10 nearest neighbors agree.

Linear CKA
1
Procrustes r
1
kNN overlap
100.0%

Agreement between the embeddings

IndexValueReading
Linear CKA (RV coefficient)11 = same up to rotation and scale
Debiased linear CKA1corrects the upward bias with few rows or many columns
RBF CKA1more weight on local structure
Procrustes disparity00 = same up to shift, rotation and scale
Procrustes r1√(1 − disparity)
kNN overlap (k = 10)1share of shared nearest neighbors
Distance rank correlation1Spearman ρ of pairwise distances
Python

Linear CKA 1.00, RBF CKA 1.00, Procrustes r 1.00; 100% of each row's 10 nearest neighbors agree.

Linear CKA
1.000
Procrustes r
1
kNN overlap
100.0%

Agreement between the embeddings

IndexValueReading
Linear CKA (RV coefficient)1.0001 = same up to rotation and scale
Debiased linear CKA1.0000corrects the upward bias with few rows or many columns
RBF CKA1.000more weight on local structure
Procrustes disparity00 = same up to shift, rotation and scale
Procrustes r1√(1 − disparity)
kNN overlap (k = 10)1share of shared nearest neighbors
Distance rank correlation1Spearman ρ of pairwise distances

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

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

Worked examples in the app

  • Iris pca vs rotatedclu4_embeddings · a: pc1, pc2 · b: rot1, rot2
  • Iris pca vs noisyclu4_embeddings · a: pc1, pc2 · b: nz1, nz2
  • Iris features vs pcaclu4_embeddings · a: f1, f2, f3, f4 · b: pc1, pc2
  • Iris pca vs noiseclu4_embeddings · a: pc1, pc2 · b: u1, u2
  • Degenerate constantclu4_embeddings · a: pc1, pc2 · b: rot1, rot2
  • Degenerate tiesclu4_embeddings · a: pc1, pc2 · b: rot1, rot2
  • Degenerate all naclu4_embeddings · a: pc1, pc2 · b: rot1, rot2
  • Degenerate infclu4_embeddings · a: pc1, pc2 · b: rot1, rot2

In the guides

Where it sits in the decision guides

  • Testing and comparing clusterings (SigClust, selective inference, ARI, CKA) · DS & ML Decision Guide · Discover — find structure without labels
  • Discover: cluster quality (silhouette, ARI); coherence (topics); stability and interpretability · DS & ML Decision Guide · How to evaluate — common metrics by question type

What you need

Embedding Anumeric · 1–200 columns
Coordinates of the first map (for example saved UMAP or PCA columns); rows with a missing value in either embedding are left out.
Embedding Bnumeric · 1–200 columns
Coordinates of the second map of the same rows; it may have a different number of columns.

Choices you make

model

Neighbors compareddefault 10

How many nearest neighbors of each row the kNN overlap compares.

Scale columnsdefault none

CKA and Procrustes ignore rotation and overall scale but not the scale of single columns.

  • Keep as they are(default) — Right for maps whose axes share units (PCA scores, UMAP, t-SNE).
  • Standardize each column — Gives every column of both embeddings unit SD first; use for raw features in different units.
Permutationsdefault 0

Rows of B shuffled this many times for a p-value of the linear CKA (0 = no test).

Advanced

RBF widthdefault 0.5

Kernel width for RBF CKA as a multiple of each embedding's median pairwise distance (Kornblith et al. use 0.2–0.8).

Rows for pairwise measuresdefault 2000

Evenly spaced rows used for RBF and debiased CKA, kNN overlap and distance correlation (each needs an n × n matrix).

What it reports

n
Rows compared, rows used for pairwise measures, and the number of columns in each embedding.
n_sub
Rows compared, rows used for pairwise measures, and the number of columns in each embedding.
dims_a
Rows compared, rows used for pairwise measures, and the number of columns in each embedding.
dims_b
Rows compared, rows used for pairwise measures, and the number of columns in each embedding.
linear_cka
Similarity of two embeddings of the same rows: 1 = same up to rotation and overall scale, near 0 = unrelated.
debiased_cka
Similarity of two embeddings of the same rows: 1 = same up to rotation and overall scale, near 0 = unrelated.
rbf_cka
Similarity of two embeddings of the same rows: 1 = same up to rotation and overall scale, near 0 = unrelated.
sigma_a
σ of the Gaussian kernel in RBF CKA: a multiple of the embedding's median pairwise distance.
sigma_b
σ of the Gaussian kernel in RBF CKA: a multiple of the embedding's median pairwise distance.
procrustes_disparity
Squared mismatch left after shifting, rotating, reflecting and rescaling one embedding onto the other; 0 = identical.
procrustes_r
Squared mismatch left after shifting, rotating, reflecting and rescaling one embedding onto the other; 0 = identical.
knn_overlap
Average share of each row's k nearest neighbors that both embeddings agree on: local agreement.
k_used
Average share of each row's k nearest neighbors that both embeddings agree on: local agreement.
distance_spearman
Spearman correlation between the two embeddings' pairwise distances: do far pairs stay far and near pairs near?
p_permutation
Similarity of two embeddings of the same rows: 1 = same up to rotation and overall scale, near 0 = unrelated.

Python and R

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

Default traps between the two languages

  • Both engines compute the indices with the same written-out formulas; Procrustes and the debiased CKA go through an SVD or Gram matrices, so values agree to rounding rather than exactly. Permutations come from the shared stream.
Python

The exact script CodeSplash ran for example “Iris pca vs rotated” · 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 e0b9deeefaf9ece4
# 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 = ["rot1", "rot2"]
SEED = 42
K = 10
WIDTH = float(0.5)
SCALE = "none"
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,
})
R

The exact script CodeSplash ran for example “Iris pca vs rotated” · 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 e0b9deeefaf9ece4
# 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("rot1", "rot2")
SEED <- 42
K <- 10
WIDTH <- as.numeric(0.5)
SCALE <- "none"
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
))

Sources

  • Kornblith S, Norouzi M, Lee H, Hinton G (2019). Similarity of neural network representations revisited. ICML 2019, 3519–3529.
  • Song L, Smola A, Gretton A, Bedo J, Borgwardt K (2012). Feature selection via dependence maximization. JMLR 13:1393–1434.
  • Robert P, Escoufier Y (1976). A unifying tool for linear multivariate statistical methods: the RV-coefficient. Applied Statistics 25:257–265.
  • Gower JC (1975). Generalized Procrustes analysis. Psychometrika 40:33–51.

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