Skip to content

Neighbor embeddings: t-SNE, UMAP, TriMap and PaCMAP

These maps keep who sits near whom and give up the rest. Read the losses behind t-SNE, UMAP, TriMap and PaCMAP, see how each balances attraction and repulsion, and learn what their pictures can and can't tell you.

Advanced ~15 min10 steps

What runs in CodeSplash

You will be able to

  • Write t-SNE's KL objective and explain how perplexity and the heavy-tailed map kernel shape the picture
  • Write UMAP's graph cross-entropy and say what its attractive and repulsive terms do
  • Explain how TriMap's triplets and PaCMAP's three kinds of pairs keep more global structure
  • List what a neighbor-embedding picture cannot support

Read first

01

Attract neighbors, repel the rest

Read

Every method here builds a picture by balancing two forces: rows that were neighbors in the data pull together, everyone else pushes apart. What counts as a neighbor, how strong each force is and how it falls off with distance is the whole difference between them.

Because only local relationships are rewarded, the gaps between groups, the sizes of groups and the empty space on the map are by-products of the optimization.

02

t-SNE

Read

t-SNEt-SNEA nonlinear map that keeps near neighbors together; sizes of groups and gaps between them carry little meaning. turns distances into neighbor probabilities pijp_{ij} with a Gaussian around each row, whose width is set so each row has about perplexityPerplexityRoughly how many neighbors each row attends to in t-SNE; small values show fine detail, and can invent it. effective neighbors. In the map it uses a heavy-tailed Student-t kernel, qij∝(1+∥yi−yj∥2)−1q_{ij} \propto (1 + \lVert y_i - y_j\rVert^2)^{-1}, and minimizes

KL⁡(P ∥ Q)=∑i≠jpijlog⁡pijqij.\operatorname{KL}(P \,\Vert\, Q) = \sum_{i \ne j} p_{ij} \log \frac{p_{ij}}{q_{ij}} .

The KL divergenceKullback–Leibler divergenceHow many extra nats it costs to describe draws from one distribution with a code built for another; 0 when they match. punishes neighbors placed far apart much more than strangers placed close. The heavy tail lets moderately distant rows be pushed very far, which is why t-SNE islands look so separated.

03

UMAP

Read

UMAPUMAPA nonlinear map built from a neighbor graph; it keeps local structure, and its global layout is less reliable. builds a weighted neighbor graph pijp_{ij} (each row connected to its nearest neighbors, with weights decaying past the closest) and fits map similarities qij=(1+a∥yi−yj∥2b)−1q_{ij} = (1 + a\lVert y_i - y_j\rVert^{2b})^{-1} by graph cross-entropy:

−∑ij[ pijlog⁡qij+(1−pij)log⁡(1−qij) ].-\sum_{ij} \big[\, p_{ij} \log q_{ij} + (1 - p_{ij}) \log(1 - q_{ij}) \,\big].

The first term attracts linked rows; the second repels unlinked ones, estimated by sampling a few random rows. That sampled repulsion makes UMAP fast, and its min_dist setting (through aa and bb) controls how tightly clumps pack.

04

Same data, three maps

Read
UMAP mapRecorded · Python and R agreeRecorded 2026-11-25 · 4 values compared · largest relative difference 1.2e-2
R

UMAP map of 150 rows: trustworthiness 0.976, 72% of each row's 10 nearest neighbors kept.

Trustworthiness (k = 10)
0.9759
Neighbors kept
72.4%

Plots

UMAP mapWhich rows group together, and how well separated are the groups?
View data
speciesUMAP 1UMAP 2
setosa−5.0668.095
setosa−2.7469.393
setosa−3.3828.862
setosa−3.0308.898
setosa−5.8887.978
setosa−6.7278.593
setosa−4.5258.694
setosa−4.6418.115
setosa−2.7658.837
setosa−3.1139.396
setosa−6.2968.471
setosa−4.8418.498
setosa−2.9779.336
setosa−2.7268.802
setosa−7.0918.400
setosa−6.9468.308
setosa−6.8988.347
setosa−5.2518.064
setosa−6.6488.560
setosa−6.6028.110
setosa−4.9237.750
setosa−6.1838.140
setosa−5.4828.195
setosa−4.7067.973
setosa−4.5018.502
setosa−2.9069.527
setosa−4.7708.322
setosa−5.2977.916
setosa−4.9407.934
setosa−3.3808.988
setosa−3.2449.171
setosa−4.9407.824
setosa−6.9058.392
setosa−7.0248.479
setosa−3.2069.241
setosa−3.6238.802
setosa−5.1777.964
setosa−5.7098.100
setosa−2.8488.888
setosa−4.9178.061
setosa−5.1898.200
setosa−2.6398.824
setosa−3.0898.838
setosa−4.7978.236
setosa−6.4308.247
setosa−2.8959.497
setosa−6.3368.218
setosa−3.3388.942
setosa−6.3768.367
setosa−4.3818.320
versicolor3.332−3.326
versicolor3.022−3.637
versicolor3.229−3.373
versicolor−0.7191−4.220
versicolor2.356−3.565
versicolor0.4349−3.538
versicolor3.078−3.794
versicolor−1.039−4.139
versicolor2.545−3.219
versicolor−0.6581−3.444

First 60 of 150 rows.

The exact R script · R R version 4.5.1 (2025-06-13)
# UMAP map
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.umap 1.0.0 · spec b40ffe12d3077c1d
# Dataset: ml_iris (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)
suppressPackageStartupMessages(library(uwot))

# %% Data
IMPUTE <- "median"
SCALE <- "standard"
FEATURES <- c("sepal_length", "sepal_width", "petal_length", "petal_width")
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_iris.parquet", col_select = FEATURES))
warnings <- list()
design <- cs_ml_design(
  df, FEATURES,
  kinds = list(
    sepal_length = "numeric",
    sepal_width = "numeric",
    petal_length = "numeric",
    petal_width = "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 <- "species"
if (!is.null(LABEL)) df[[LABEL]] <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_iris.parquet", col_select = LABEL))[[LABEL]]

# %% UMAP (host kNN graph + host starting layout, shared with Python)
k <- min(15, length(rows) - 1L)
epochs <- NULL
if (is.null(epochs)) epochs <- if (length(rows) <= 10000) 500 else 200
nn <- if (length(rows) <= 20000) cs_ml_exact_knn(X, k) else {
  warnings <- c(warnings, "More than 20,000 rows: each engine builds its own approximate neighbor graph.")
  "annoy"
}
init <- cs_ml_pca_init(X, 10)
Y <- uwot::umap(
  X,
  n_neighbors = k,
  min_dist = 0.1,
  n_components = 2,
  metric = "euclidean",
  n_epochs = epochs,
  nn_method = nn,
  init = init,
  n_threads = 1,
  n_sgd_threads = 0,  # single-threaded and reproducible
  seed = 42
)
METHOD_LABEL <- "UMAP"
ENGINE_PACKAGES <- c("uwot", "nanoparquet")
extra_values <- list()

# %% Neighborhood preservation (same rows in both engines)
K_EVAL <- 10L
sample <- cs_ml_sample_rows(length(rows))
k_eval <- min(K_EVAL, length(sample) - 2L)
trust <- cs_ml_trustworthiness(X[sample, , drop = FALSE], Y[sample, , drop = FALSE], k_eval)
keep <- cs_ml_knn_preservation(X[sample, , drop = FALSE], Y[sample, , drop = FALSE], k_eval)

# %% Artifacts
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.umap/iris/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
values <- c(list(n = length(rows), n_features = length(FEATURES), trustworthiness = trust, knn_preservation = keep), extra_values)
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
}
cs_publish(list(
  title = "UMAP map",
  engine = do.call(cs_engine_info, as.list(ENGINE_PACKAGES)),
  n = length(rows),
  summary = sprintf("%s map of %d rows: trustworthiness %.3f, %.0f%% of each row's %d nearest neighbors kept.",
                    METHOD_LABEL, length(rows), trust, 100 * keep, k_eval),
  statistics = list(list(key = "trustworthiness", label = sprintf("Trustworthiness (k = %d)", k_eval), value = trust),
                    list(key = "knn_preservation", label = "Neighbors kept", value = keep, 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("%d of %d rows shown.", length(pick), length(rows)))),
  values = values,
  warnings = warnings,
  artifacts = list(list(key = "embedding", path = file.path(out, "embedding.parquet"), format = "parquet"))
))
Python

UMAP map of 150 rows: trustworthiness 0.979, 73% of each row's 10 nearest neighbors kept.

Trustworthiness (k = 10)
0.9786
Neighbors kept
73.3%

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
# UMAP map
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.umap 1.0.0 · spec b40ffe12d3077c1d
# Dataset: ml_iris (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os
import warnings as _warnings

import numpy as np
import pandas as pd
import umap

import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import embed as csembed

# %% Data
IMPUTE = "median"
SCALE = "standard"
FEATURES = ["sepal_length", "sepal_width", "petal_length", "petal_width"]
df = pd.read_parquet("tests/parity/fixtures/ml_iris.parquet", columns=FEATURES)
warnings = []
design = csml.Design.for_frame(
    df,
    FEATURES,
    kinds={
        "sepal_length": "numeric",
        "sepal_width": "numeric",
        "petal_length": "numeric",
        "petal_width": "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 = "species"
if LABEL:
    df[LABEL] = pd.read_parquet("tests/parity/fixtures/ml_iris.parquet", columns=[LABEL])[LABEL]

# %% UMAP (host kNN graph + host starting layout, shared with R)
k = min(15, len(rows) - 1)
epochs = None or (500 if len(rows) <= 10000 else 200)
extra = {}
if len(rows) <= 20000:
    knn_idx, knn_dist = csembed.exact_knn(X, k)
    extra["precomputed_knn"] = (knn_idx, knn_dist, None)
else:
    warnings.append("More than 20,000 rows: each engine builds its own approximate neighbor graph.")
init = csembed.pca_init(X, 10.0)
with _warnings.catch_warnings():
    _warnings.simplefilter("ignore")  # "no search index" for precomputed_knn: transform() is not used
    reducer = umap.UMAP(
        n_neighbors=k,
        min_dist=0.1,
        n_components=2,
        metric="euclidean",
        n_epochs=epochs,
        init=init,
        random_state=42,  # single-threaded and reproducible
        n_jobs=1,
        **extra,
    )
    Y = reducer.fit_transform(X)
METHOD_LABEL = "UMAP"
ENGINE_PACKAGES = ("umap-learn", "numpy", "pandas")
extra_values = {}

# %% Neighborhood preservation (same rows in both engines)
K_EVAL = 10
sample = csembed.sample_rows(len(rows))
k_eval = min(K_EVAL, len(sample) - 2)
trust = csembed.trustworthiness(X[sample], Y[sample], k_eval)
keep = csembed.knn_preservation(X[sample], Y[sample], k_eval)

# %% Artifacts
out = csml.out_dir("target/academy-parity/run-8142/discover.umap/iris/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
values = {"n": len(rows), "n_features": len(FEATURES), "trustworthiness": trust, "knn_preservation": keep}
values.update(extra_values)
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))]
cs.publish({
    "title": "UMAP map",
    "engine": cs.engine_info(*ENGINE_PACKAGES),
    "n": len(rows),
    "summary": f"{METHOD_LABEL} map of {len(rows)} rows: trustworthiness {trust:.3f}, {keep:.0%} of each row's {k_eval} nearest neighbors kept.",
    "statistics": [
        {"key": "trustworthiness", "label": f"Trustworthiness (k = {k_eval})", "value": trust},
        {"key": "knn_preservation", "label": "Neighbors kept", "value": keep, "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"}],
})

On iris, all three keep neighborhoods well. Trustworthiness is 0.987 for t-SNE, 0.976 for UMAP and 0.976 for PaCMAP. Share of each row's 10 nearest neighbors kept: 80%, 72% and 71%.

High trustworthiness says close-on-the-map means close-in-the-data. It doesn't validate the gaps.

05

TriMap: triplets for the big picture

Read

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. samples triplets (i,j,k)(i, j, k) where ii should stay closer to jj than to kk, and minimizes a bounded loss per triplet,

wijk s(yi,yk)s(yi,yj)+s(yi,yk),w_{ijk}\, \frac{s(y_i, y_k)}{s(y_i, y_j) + s(y_i, y_k)},

with a heavy-tailed similarity ss. Triplets that compare near and far rows carry information about the global arrangement that pure neighbor losses throw away. How triplets are sampled and weighted is part of the method: poor sampling misses structure.

06

PaCMAP: three kinds of pairs

Read

PaCMAPPaCMAPA map trained on near, mid-near and far pairs in three phases, balancing local neighbors and global layout. uses three kinds of pairs with d~=1+∥yi−yj∥2\tilde d = 1 + \lVert y_i - y_j\rVert^2:

PairTermRole
neighborsd~/(10+d~)\tilde d / (10 + \tilde d)attract strongly
mid-neard~/(10000+d~)\tilde d / (10000 + \tilde d)attract gently, over long range
further1/(1+d~)1 / (1 + \tilde d)repel

Their weights change on a schedule: early on, mid-near pairs dominate and set the global layout; later, neighbors refine it. On the S-curve, PaCMAP keeps trustworthiness 0.994 and TriMap 0.991.

07

What the picture can't tell you

Explore

AExplorable · What t-SNE and UMAP maps don't show

What can you safely read from a t-SNE or UMAP picture?

One group here may be far wider than another in the original space. In the map, that difference in size will be…

How sure?

Ten-dimensional data

Method

30
120
Simulating…

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

Try the cluster-sizes and cluster-distances datasets. Then remember the rules:

  • Gaps between islands and island sizes aren't quantitative.
  • A tight island isn't proof of a real group: noise can form islands.
  • Two runs with different seeds can differ while scoring the same loss.
  • None of these maps places new rows natively.
08

What perplexity changes

Explore

AExplorable · Perplexity: how many neighbors count

What does t-SNE's perplexity actually change, and how can you tell whether a map kept its neighbors?

Raise the perplexity from 5 to 30. What happens to each point's bandwidth σ?

How sure?

Ten-dimensional data

10
10
120
Simulating…

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

Each point gets its own bandwidth σ, set so its neighbor distribution has the chosen perplexity. Dense groups get small σ and sparse ones large σ, so the size of a group in the map stops meaning spread. Trustworthiness and continuity score how many neighbors the map kept.

09

Check: neighbor embeddings

Checkpoint

Check yourself

Which mistake does t-SNE's KL objective punish most?

Show the answer

Answer: a

Where pijp_{ij} is large and qijq_{ij} small, plog⁡(p/q)p\log(p/q) is large. Strangers placed close (small pp) cost little, so global layout is weakly constrained.

Check yourself

Why does t-SNE use a heavy-tailed Student-t kernel in the map rather than a Gaussian?

Show the answer

Answer: a

Low-dimensional maps don't have room for all moderate distances. The heavy tail pushes them out, and that's why gaps on t-SNE maps aren't to scale.

Check yourself

What does t-SNE's perplexity control?

Show the answer

Answer: a

Each row's bandwidth is tuned so its neighbor distribution has that perplexity. Small values focus on very local structure.

Check yourself

In UMAP's cross-entropy, what does the (1−pij)log⁡(1−qij)(1 - p_{ij})\log(1 - q_{ij}) term do?

Show the answer

Answer: a

When pijp_{ij} is near 0, minimizing the loss pushes qijq_{ij} toward 0, which means moving the rows apart.

Check yourself

Why is UMAP's optimization fast on large data?

Show the answer

Answer: a

A dense sum over all n2n^2 pairs is replaced by negative sampling, like word2vec.

Check yourself

What does a TriMap triplet (i,j,k)(i, j, k) ask of the map?

Show the answer

Answer: a

Relative comparisons including far rows carry global information that neighbor-only losses lack.

Check yourself

A TriMap map satisfies most of its triplets. Can you read pairwise distances from it as exact?

Show the answer

Answer: a

Triplet accuracy says "closer than", not "how much closer". Outliers can also distort the global arrangement.

Check yourself

What role do PaCMAP's mid-near pairs play?

Show the answer

Answer: a

Their weight is high in the first phase and fades later, so the coarse arrangement is fixed before neighbors refine it.

Check yourself

Why can one PaCMAP plot not prove that all global distances are preserved?

Show the answer

Answer: a

Check global claims with distance correlations or Shepard plots, and compare seeds.

10

Recap

Recap
  • t-SNE minimizes KL between Gaussian neighbor probabilities and heavy-tailed map similarities; perplexity sets the neighborhood size.
  • UMAP fits a neighbor graph by cross-entropy with sampled repulsion.
  • TriMap's triplets and PaCMAP's mid-near pairs add global structure, without making distances exact.

Concepts in this lesson