t-SNE and UMAP: what a map can and can't tell you
These maps keep neighbors together and quietly lose almost everything else. Learn what to read from them and how to check a map before you trust it.
What runs in CodeSplash
You will be able to
- Say what t-SNE and UMAP preserve and what they don't
- Interpret trustworthiness and neighbor preservation
- Avoid reading cluster size, distance or density from a map
Neighbors first
ReadPCA keeps large-scale variance and flattens the rest. t-SNEt-SNEA nonlinear map that keeps near neighbors together; sizes of groups and gaps between them carry little meaning. and UMAPUMAPA nonlinear map built from a neighbor graph; it keeps local structure, and its global layout is less reliable. do nearly the opposite: they place each row near its nearest neighbors and let everything else go.
That makes tight, attractive islands. It also means that the size of an island, the gap between two islands, and how dense an island looks may have little to do with the data.
Think of a map that keeps each town near its neighboring towns but freely bends the countries.
Make a guess
PredictPredict first
One group in your data is far more spread out than another. On a t-SNE map, will that difference show?
Reveal
Mostly lost. t-SNE adapts to the local density around each point, so wide and narrow groups tend to come out at similar sizes. Check this next by comparing the spread ratio in the data with the one on the map.
Break a map
ExploreAExplorable · 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…
Ten-dimensional data
Method
Commit your prediction above to see the result
Make your prediction to see the result.
Try each dataset in turn. On Clusters of very different spreads, compare the two spread ratios. On Two close clusters and one far away, compare the distance ratios. On Pure noise, turn on the break-it toggle and notice how low perplexityPerplexityRoughly how many neighbors each row attends to in t-SNE; small values show fine detail, and can invent it. draws convincing clumps from nothing.
What you may read
Read| Read from a map | Safe? |
|---|---|
| These rows are neighbors | Yes, if the map scores well |
| Some rows form a tight group | A lead to check against the data |
| This group is bigger or wider | No |
| These two groups are far apart | No |
| There are exactly five clusters | No |
Treat a map as a way to form questions. To test a group, cluster in the original columns and check it there.
How to check a map
ReadTwo numbers on the card measure how well neighbors survived:
- TrustworthinessTrustworthinessA 0–1 score for whether rows that look close on a map are really close in the data.: are rows that look close on the map really close in the data? 1 is perfect.
- Neighbor preservation: what share of each row's 10 nearest neighbors stay nearest on the map?
On iris, t-SNE gets trustworthiness 0.987 and keeps 80% of neighbors. UMAP gets 0.976 and 72%.
These measure local fidelity only. A map can score well and still misstate every gap between groups.
Parameters reshape the picture
ReadPerplexity in t-SNE and neighbors in UMAP set how many neighbors each row attends to. Small values show fine local structure, and may invent it. Larger values give a more global picture. Here penguins use a perplexity of 20, with trustworthiness 0.994.
Try two or three values. Structure that survives is more believable. Scaling matters here too: a UMAP run on Pima with scaling turned off lets its largest-unit columns set the neighbors, and keeps 60% of them.
Why Python and R differ
In the appt-SNE and UMAP depend on stochastic optimizers and approximations. Both engines start from the same layout, but their coordinates differ. The app compares them on neighborhood preservation instead of coordinates.
This is honest, and useful: if two runs disagree on a global arrangement, that arrangement was never a reliable feature of the data.
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
View data
| species | UMAP 1 | UMAP 2 |
|---|---|---|
| setosa | −5.066 | 8.095 |
| setosa | −2.746 | 9.393 |
| setosa | −3.382 | 8.862 |
| setosa | −3.030 | 8.898 |
| setosa | −5.888 | 7.978 |
| setosa | −6.727 | 8.593 |
| setosa | −4.525 | 8.694 |
| setosa | −4.641 | 8.115 |
| setosa | −2.765 | 8.837 |
| setosa | −3.113 | 9.396 |
| setosa | −6.296 | 8.471 |
| setosa | −4.841 | 8.498 |
| setosa | −2.977 | 9.336 |
| setosa | −2.726 | 8.802 |
| setosa | −7.091 | 8.400 |
| setosa | −6.946 | 8.308 |
| setosa | −6.898 | 8.347 |
| setosa | −5.251 | 8.064 |
| setosa | −6.648 | 8.560 |
| setosa | −6.602 | 8.110 |
| setosa | −4.923 | 7.750 |
| setosa | −6.183 | 8.140 |
| setosa | −5.482 | 8.195 |
| setosa | −4.706 | 7.973 |
| setosa | −4.501 | 8.502 |
| setosa | −2.906 | 9.527 |
| setosa | −4.770 | 8.322 |
| setosa | −5.297 | 7.916 |
| setosa | −4.940 | 7.934 |
| setosa | −3.380 | 8.988 |
| setosa | −3.244 | 9.171 |
| setosa | −4.940 | 7.824 |
| setosa | −6.905 | 8.392 |
| setosa | −7.024 | 8.479 |
| setosa | −3.206 | 9.241 |
| setosa | −3.623 | 8.802 |
| setosa | −5.177 | 7.964 |
| setosa | −5.709 | 8.100 |
| setosa | −2.848 | 8.888 |
| setosa | −4.917 | 8.061 |
| setosa | −5.189 | 8.200 |
| setosa | −2.639 | 8.824 |
| setosa | −3.089 | 8.838 |
| setosa | −4.797 | 8.236 |
| setosa | −6.430 | 8.247 |
| setosa | −2.895 | 9.497 |
| setosa | −6.336 | 8.218 |
| setosa | −3.338 | 8.942 |
| setosa | −6.376 | 8.367 |
| setosa | −4.381 | 8.320 |
| versicolor | 3.332 | −3.326 |
| versicolor | 3.022 | −3.637 |
| versicolor | 3.229 | −3.373 |
| versicolor | −0.7191 | −4.220 |
| versicolor | 2.356 | −3.565 |
| versicolor | 0.4349 | −3.538 |
| versicolor | 3.078 | −3.794 |
| versicolor | −1.039 | −4.139 |
| versicolor | 2.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"))
))
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"}],
})
Check your understanding
CheckpointCheck yourself
On a t-SNE map, group A is far from group B, and close to group C. What can you conclude?
Show the answer
Answer: b
t-SNE preserves neighborhoods. Distances between islands aren't reliable, so measure them in the original data.
Check yourself
With a low perplexity, a t-SNE map of pure random noise shows several small clumps. What's the lesson?
Show the answer
Answer: a
A map always draws something. Check tendency and stability in the original columns before you build on a clump.
Check yourself
A map has a trustworthiness of 0.99. What does that certify?
Show the answer
Answer: c
Trustworthiness is a local measure, so it can't vouch for large-scale structure or clusters.
Do it on your own data
In the appUnder Map the data, try t-SNE map and UMAP map on the same features with a Known groups label, and compare two parameter values. Save to dataset writes coordinates, for plotting only.
from sklearn.datasets import load_iris
from sklearn.manifold import TSNE, trustworthiness
from sklearn.preprocessing import StandardScaler
X = StandardScaler().fit_transform(load_iris().data)
for perplexity in (5, 30):
Y = TSNE(perplexity=perplexity, init="pca", random_state=1).fit_transform(X)
print(perplexity, round(trustworthiness(X, Y, n_neighbors=10), 3))X <- scale(unique(iris[, 1:4]))
set.seed(1)
for (perplexity in c(5, 30)) {
fit <- Rtsne::Rtsne(X, perplexity = perplexity, pca = FALSE)
cat(perplexity, round(fit$itercosts[length(fit$itercosts)], 3), "\n")
}Rtsne rejects duplicate rows, hence unique(). It reports the final cost instead of trustworthiness, and it's only comparable between runs at the same perplexity.
Recap
Recap- t-SNE and UMAP keep neighbors and lose sizes, gaps and densities.
- Trustworthiness checks local fidelity, not clusters.
- Use a map to ask questions, and test the answers in the original columns.
Concepts in this lesson