CDiscover · discover.pairmap
Pair-based maps (PaCMAP, TriMap)
What does the data look like as a two-dimensional map that keeps neighbors and more of the overall layout?
Two-dimensional maps trained on sampled pairs or triplets of rows. PaCMAP pulls neighbor pairs together, uses mid-near pairs to keep the overall layout and pushes random far pairs apart, in three phases; TriMap asks, for many triplets, that a row's near neighbor end up closer than a far row. Both keep local neighborhoods like UMAP and t-SNE while preserving more of the global arrangement. The pairs come from the shared random stream and the same optimizer steps run in both engines, so the maps agree.
A real result
Example “Scurve pacmap”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
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
View data
| band | PaCMAP 1 | PaCMAP 2 |
|---|---|---|
| D | −10.681 | −3.957 |
| C | −8.208 | 3.879 |
| C | −8.038 | 3.551 |
| A | 15.131 | −2.853 |
| A | 16.939 | −0.4180 |
| D | −10.762 | −3.256 |
| C | −3.825 | 0.0678 |
| A | 15.027 | −2.592 |
| B | 2.668 | −1.693 |
| D | −12.645 | 0.3287 |
| B | 4.511 | −0.1764 |
| C | −2.058 | −0.2425 |
| A | 16.723 | 0.8235 |
| D | −8.966 | −3.462 |
| B | 2.491 | 2.761 |
| D | −8.849 | 1.388 |
| C | −7.982 | 3.638 |
| C | −8.211 | 4.061 |
| D | −5.489 | −0.4282 |
| C | 1.335 | 0.8854 |
| C | −2.669 | −0.2419 |
| D | −10.404 | −3.628 |
| A | 14.995 | −0.9071 |
| A | 16.231 | −3.074 |
| B | 4.201 | 0.1139 |
| D | −12.667 | 0.2498 |
| C | −7.840 | 3.387 |
| C | −1.259 | −0.1811 |
| B | 3.140 | 3.063 |
| C | −8.502 | 2.799 |
| D | −13.369 | −0.4565 |
| C | −3.845 | 0.1916 |
| D | −8.513 | 1.927 |
| B | 5.264 | 4.128 |
| C | 1.310 | 1.079 |
| A | 16.343 | −3.216 |
| C | −8.108 | 3.469 |
| B | 2.747 | 2.912 |
| D | −11.027 | 0.3260 |
| D | −7.891 | 0.2365 |
| D | −10.418 | −3.896 |
| C | −8.064 | 3.865 |
| B | 5.419 | 3.778 |
| C | −8.463 | 3.163 |
| C | −5.525 | 0.8202 |
| A | 16.841 | −1.342 |
| A | 16.260 | −3.114 |
| A | 4.989 | −1.297 |
| C | 2.625 | 3.169 |
| D | −7.287 | 0.0398 |
| D | −10.230 | 0.4442 |
| C | −7.898 | 3.849 |
| B | 4.974 | −1.353 |
| A | 5.114 | −1.388 |
| B | 5.534 | 3.453 |
| B | 5.096 | 3.989 |
| C | −1.582 | −0.2675 |
| C | −6.076 | −0.0068 |
| C | −3.899 | −0.1193 |
| D | −9.263 | 1.866 |
First 60 of 240 rows.
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.
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
- Scurve pacmaprep3_scurve · features: x, y, z · label: band
- Scurve trimaprep3_scurve · features: x, y, z · label: band
- Iris pacmapml_iris · features: sepal_length, sepal_width, petal_length, petal_width · label: species
- Penguins trimap mixedml_penguins · features: island, bill_len, bill_dep, flipper_len, body_mass, sex · label: species
- Pima pacmap unscaledml_pima · features: glu, bp, bmi, age, ped
- Degenerate n2rep3_scurve · features: x, y, z
- Degenerate infrep3_scurve · features: x, y, z
- Degenerate constantrep3_scurve · features: x, y, z
In the guides
Where it sits in the decision guides
- Representation visualization (t-SNE, UMAP) · DS & ML Decision Guide · Describe — summarize and visualize
What you need
- Featuresnumeric / categorical / boolean · 2–2000 columns
- Columns used to describe each row. Numbers are standardized; categories become indicator columns.
- Color points bycategorical / boolean · 0–1 column
- Optional column used only to color the points; it does not affect the map.
Choices you make
model
- Methoddefault pacmap
Which pairs the map is trained on.
- PaCMAP(default) — Neighbor, mid-near and far pairs in three phases (Wang et al. 2021); little tuning needed.
- TriMap — Triplets: a row, one of its neighbors and a far row (Amid & Warmuth 2019); keeps global layout well.
- Neighborsdefault 10
Near neighbors per row; PaCMAP also draws half as many mid-near and twice as many far pairs.
Advanced
- Iterationsdefault —
Optimization steps over all pairs.
- Rows to mapdefault 3000
Larger data is mapped on this many evenly spaced rows (the exact neighbor search grows with the square of the rows).
preprocess
- Standardize featuresdefault on
Standardize numbers so each counts equally in the distances.
What it reports
- n
- How many independent units the analysis used; it sets precision and power.
- n_features
- How many independent units the analysis used; it sets precision and power.
- neighbors
- How many nearest rows each row links to in the graph a manifold map is built on (the row itself never counts).
- n_pairs
- How many independent units the analysis used; it sets precision and power.
- loss
- A map trained on triplets (row, a near row, a far row) so near rows end up closer than far ones; keeps more global layout.
- trustworthiness
- A 0–1 score for whether rows that look close on a map are really close in the data.
- knn_preservation
- The share of each row's nearest neighbors that stay nearest after reducing dimensions.
Per group, level or term: coord_check[<k>]
Python and R
Python and R agree to 6 decimals (relative tolerance 1e-6). Python uses numpy; R uses codesplashr.
Default traps between the two languages
- Both engines run the codesplash twins (numpy ↔ base R), not the pacmap or trimap packages: the same exact neighbor search (ties by row order), the same Wichmann–Hill draws for mid-near, far and random pairs, gradients summed per row in input order and the same optimizer steps, so coordinates agree to rounding.
- Neighbor pairs use the packages' scaled distance d²/(σᵢσⱼ), with σ the mean distance to the 4th–6th neighbors, among the k + 50 nearest rows found exactly (the packages use approximate neighbor search above a few thousand rows).
- TriMap runs without its delta-bar-delta step-size gains: their sign test turns 1e-16 rounding differences into different trajectories, so two engines could never agree. Plain momentum at the same learning rate gives maps of the same quality (trustworthiness within 0.001 on the S-curve fixture).
- Maps are rotated to their principal axes with canonical signs; rows beyond the row limit (3,000 by default) are mapped on an evenly spaced sample.
- Trustworthiness and neighbor preservation (k = 10, on at most 1,000 evenly spaced rows) are computed on coordinates snapped to a grid of 10⁻⁶ × the largest value, so tied rows are ordered by row in both engines.
The exact script CodeSplash ran for example “Scurve pacmap” · 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"}],
})
The exact script CodeSplash ran for example “Scurve pacmap” · 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"))
))
Sources
- Wang Y, Huang H, Rudin C, Shaposhnik Y (2021). Understanding how dimension reduction tools work: an empirical approach to deciphering t-SNE, UMAP, TriMap, and PaCMAP for data visualization. JMLR 22(201):1–73.
- Amid E, Warmuth MK (2019). TriMap: large-scale dimensionality reduction using triplets. arXiv:1910.00204.
From the CodeSplash method registry · discover.pairmap v1.0.0.