Skip to content

PaCMAP, TriMap and checking a map on rows it hasn't seen

Pair-based maps keep neighbors like UMAP while holding on to more of the overall layout. Then two checks every map deserves - neighborhood curves over many sizes, and a held-out test of how many components are real.

Advanced ~12 min7 steps

What runs in CodeSplash

You will be able to

  • Say what PaCMAP's three kinds of pairs and TriMap's triplets each do
  • Read trustworthiness and continuity across neighborhood sizes
  • Use held-out reconstruction to choose how many PCA components to keep

Read first

01

Neighbors plus a sense of the whole

Read

t-SNE and UMAP keep each row near its neighbors and let the overall layout drift. Pair-based maps add pairs that carry the layout.

  • PaCMAPPaCMAPA map trained on near, mid-near and far pairs in three phases, balancing local neighbors and global layout. uses three kinds of pairs: neighbors (pulled together), mid-near rows (pulled gently, so groups keep their places) and random far rows (pushed apart). It weights them in three phases: first the global layout, then everything, then the neighbors alone.
  • TriMapTriMapA map trained on triplets (row, a near row, a far row) so near rows end up closer than far ones; keeps more global layout. uses triplets: a row, one of its neighbors and a far row. The map is trained so the neighbor ends up closer than the far row, with more weight on clear-cut triplets.

On the S-curve fixture PaCMAP keeps trustworthiness 0.994 and 80% of each row's 10 nearest neighbors. TriMap scores 0.991 from 12,720 triplets.

Pair-based maps (PaCMAP, TriMap)Recorded · Python and R agreeRecorded 2026-11-25 · 9 values compared
R

PaCMAP map of 240 rows from 8,400 pairs: trustworthiness 0.994, 80% of each row's 10 nearest neighbors kept.

Trustworthiness (k = 10)
0.9936
Neighbors kept
80.0%

Plots

PaCMAP mapWhich rows group together, and how well separated are the groups?
View data
bandPaCMAP 1PaCMAP 2
D−10.681−3.957
C−8.2083.879
C−8.0383.551
A15.131−2.853
A16.939−0.4180
D−10.762−3.256
C−3.8250.0678
A15.027−2.592
B2.668−1.693
D−12.6450.3287
B4.511−0.1764
C−2.058−0.2425
A16.7230.8235
D−8.966−3.462
B2.4912.761
D−8.8491.388
C−7.9823.638
C−8.2114.061
D−5.489−0.4282
C1.3350.8854
C−2.669−0.2419
D−10.404−3.628
A14.995−0.9071
A16.231−3.074
B4.2010.1139
D−12.6670.2498
C−7.8403.387
C−1.259−0.1811
B3.1403.063
C−8.5022.799
D−13.369−0.4565
C−3.8450.1916
D−8.5131.927
B5.2644.128
C1.3101.079
A16.343−3.216
C−8.1083.469
B2.7472.912
D−11.0270.3260
D−7.8910.2365
D−10.418−3.896
C−8.0643.865
B5.4193.778
C−8.4633.163
C−5.5250.8202
A16.841−1.342
A16.260−3.114
A4.989−1.297
C2.6253.169
D−7.2870.0398
D−10.2300.4442
C−7.8983.849
B4.974−1.353
A5.114−1.388
B5.5343.453
B5.0963.989
C−1.582−0.2675
C−6.076−0.0068
C−3.899−0.1193
D−9.2631.866

First 60 of 240 rows.

The exact R script · R R version 4.5.1 (2025-06-13)
# Pair-based maps (PaCMAP, TriMap)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.pairmap 1.0.0 · spec ba5b07b4a6083d62
# 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 <- "pacmap"
METHOD_LABEL <- c(pacmap = "PaCMAP", trimap = "TriMap")[[METHOD]]
keep <- cs_ml_sample_rows(length(rows), 3000)
if (length(keep) < length(rows)) {
  warnings <- c(warnings, sprintf("%s maps %s evenly spaced rows of %s (the exact neighbor search 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]
k <- cs_ml_pm_check(METHOD, length(rows), 10L)
if (k < 10L) warnings <- c(warnings, sprintf("Only %d rows: the map uses %d neighbors instead of 10.", length(rows), k))

# %% Map (pairs from the shared Wichmann–Hill stream, seed 42)
fit <- cs_ml_pm_fit(X, METHOD, k, 42, NULL)
Y <- fit$coords
values <- list(
  n = length(rows),
  n_features = length(FEATURES),
  neighbors = k,
  n_pairs = if (!is.null(fit$n_pairs)) fit$n_pairs else fit$n_triplets,
  loss = fit$loss
)
for (j in 1:2) 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)
tk <- cs_ml_mf_neighborhood(X[sample, , drop = FALSE], Y[sample, , drop = FALSE], k_eval)
values$trustworthiness <- unname(tk[1])
values$knn_preservation <- unname(tk[2])

# %% Artifacts
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.pairmap/scurve_pacmap/out-r")
nanoparquet::write_parquet(data.frame(row = as.integer(rows), dim_1 = Y[, 1], dim_2 = Y[, 2]), file.path(out, "embedding.parquet"))

# %% Result
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
}
what <- if (METHOD == "pacmap") "pairs" else "triplets"
cs_publish(list(
  title = "Pair-based maps (PaCMAP, TriMap)",
  engine = cs_engine_info("codesplashr", "nanoparquet"),
  n = length(rows),
  summary = sprintf("%s map of %d rows from %s %s: trustworthiness %.3f, %.0f%% of each row's %d nearest neighbors kept.",
                    METHOD_LABEL, length(rows), format(values$n_pairs, big.mark = ","), what, values$trustworthiness,
                    100 * values$knn_preservation, k_eval),
  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")),
  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 = ",")))),
  values = values,
  warnings = warnings,
  artifacts = list(list(key = "embedding", path = file.path(out, "embedding.parquet"), format = "parquet"))
))
Python

PaCMAP map of 240 rows from 8,400 pairs: trustworthiness 0.994, 80% of each row's 10 nearest neighbors kept.

Trustworthiness (k = 10)
0.9936
Neighbors kept
80.0%

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

The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Pair-based maps (PaCMAP, TriMap)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.pairmap 1.0.0 · spec ba5b07b4a6083d62
# 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 embed as csembed
from codesplash.ml import manifold as csman
from codesplash.ml import pairmap as cspair

# %% 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 = "pacmap"
METHOD_LABEL = cspair.METHOD_LABELS[METHOD]
keep = csembed.sample_rows(len(rows), 3000)
if len(keep) < len(rows):
    warnings.append(f"{METHOD_LABEL} maps {len(keep):,} evenly spaced rows of {len(rows):,} (the exact neighbor search grows with the square of the rows).")
X = X[keep]
rows = rows[keep]
k = cspair.check_setup(METHOD, len(rows), 10)
if k < 10:
    warnings.append(f"Only {len(rows)} rows: the map uses {k} neighbors instead of 10.")

# %% Map (pairs from the shared Wichmann–Hill stream, seed 42)
fit = cspair.fit(X, METHOD, k, 42, None)
Y = fit["coords"]
values = {
    "n": len(rows),
    "n_features": len(FEATURES),
    "neighbors": k,
    "n_pairs": int(fit.get("n_pairs", fit.get("n_triplets", 0))),
    "loss": float(fit["loss"]),
}
for j in range(2):
    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)
trust, keep_nn = csman.neighborhood_scores(X[sample], Y[sample], k_eval)
values["trustworthiness"] = float(trust)
values["knn_preservation"] = float(keep_nn)

# %% Artifacts
out = csml.out_dir("target/academy-parity/run-8142/discover.pairmap/scurve_pacmap/out-python")
emb = pd.DataFrame({"row": rows.astype(np.int64), "dim_1": Y[:, 0], "dim_2": Y[:, 1]})
emb.to_parquet(os.path.join(out, "embedding.parquet"), index=False)

# %% Result
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))]
what = "pairs" if METHOD == "pacmap" else "triplets"
cs.publish({
    "title": "Pair-based maps (PaCMAP, TriMap)",
    "engine": cs.engine_info("numpy", "pandas"),
    "n": len(rows),
    "summary": f"{METHOD_LABEL} map of {len(rows)} rows from {values['n_pairs']:,} {what}: trustworthiness {trust:.3f}, {keep_nn:.0%} of each row's {k_eval} nearest neighbors kept.",
    "statistics": [
        {"key": "trustworthiness", "label": f"Trustworthiness (k = {k_eval})", "value": values["trustworthiness"]},
        {"key": "knn_preservation", "label": "Neighbors kept", "value": values["knn_preservation"], "format": "percent"},
    ],
    "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.")],
    "values": values,
    "warnings": warnings,
    "artifacts": [{"key": "embedding", "path": os.path.join(out, "embedding.parquet"), "format": "parquet"}],
})
02

Make a guess

Predict

Predict first

Which PaCMAP pairs stop the whole map from collapsing into one tight ball?

Neighbors pulled togetherRandom far rows pushed apart
Reveal

Random far rows pushed apart. Pulling neighbors together alone would let everything shrink to a point. The far pairs keep space between groups; the mid-near pairs keep the groups in roughly the right places.

03

One stream of random draws

Read

Both engines draw the mid-near, far and random pairs from the same random stream and take the same optimization steps, so the Python and R maps agree. TriMap's original adaptive step sizes are left out: they react to the sign of tiny rounding differences, which would send two engines down different paths. Plain momentum draws maps of the same quality.

04

Check a map at every neighborhood size

Read

A single trustworthiness number uses 10 neighbors. The Validity tab draws trustworthiness and continuity for every neighborhood size from 1 to hundreds:

  • Trustworthiness drops when the map puts rows next to each other that are far apart in the data.
  • Continuity drops when the map tears apart rows that are close in the data.

A map that scores well at 10 but sinks at 100 keeps local neighborhoods and loses the larger layout. Compare UMAP, PaCMAP and a manifold map on the same features this way.

05

How many components are real?

Read

For PCA, the Validity tab adds a held-out reconstructionHeld-out reconstructionError rebuilding rows a model didn't see; unlike in-sample error, it rises when extra components only fit noise. check. It fits the PCA on four fifths of the rows and rebuilds the fifth it didn't see, five times over.

In-sample error always falls as you add components. Held-out error falls only while the components describe real structure. It also reports the component count with the best held-out likelihood under probabilistic PCAProbabilistic PCAPCA as a model: data = loadings × latent scores + equal-variance noise, so it has a likelihood and a BIC., a principled answer to "how many components should I keep?"

For autoencoders and VAEs the same held-out PCA error appears next to the network's own error. The network's error is in-sample, so a network that only beats PCA there may be fitting noise.

06

Check your understanding

Checkpoint

Check yourself

What does each TriMap triplet ask of the map?

Show the answer

Answer: b

A triplet is (row, near row, far row). The loss shrinks when the near row is closer than the far one, weighted by how clear-cut that triplet is.

Check yourself

In PaCMAP's last phase the mid-near weight drops to 0. What is that phase for?

Show the answer

Answer: a

Early phases lean on mid-near pairs to place the groups; the last phase keeps only neighbors and far pairs, which tidies the local structure.

Check yourself

A map's trustworthiness stays near 0.99 at every neighborhood size, but its continuity falls to 0.80 at large sizes. What is happening?

Show the answer

Answer: b

Continuity is trustworthiness with the two spaces swapped: it penalizes data neighbors that the map pulls apart.

Check yourself

In-sample PCA error keeps falling from 3 to 6 components, but held-out error stops falling after 3. How many components should you keep?

Show the answer

Answer: a

Held-out error measures what a component does for rows it wasn't fitted to. Once it stops improving, more components only describe noise.

07

Do it on your own data

In the app

Under Map the data, open Pair-based maps, try PaCMAP and TriMap on the same features, then open Validity to compare their neighborhood curves.

Python
import pacmap  # pip install pacmap (the reference implementation)
from sklearn.datasets import load_iris
from sklearn.manifold import trustworthiness
from sklearn.preprocessing import StandardScaler

X = StandardScaler().fit_transform(load_iris().data)
Y = pacmap.PaCMAP(n_components=2, n_neighbors=10, random_state=1).fit_transform(X)
print(round(trustworthiness(X, Y, n_neighbors=10), 3))
R
library(codesplashr)
X <- scale(as.matrix(iris[, 1:4]))
fit <- cs_ml_pm_fit(X, "pacmap", k = 10, seed = 1)
cs_ml_mf_neighborhood(X, fit$coords, 10)

Concepts in this lesson