Skip to content

Curved surfaces: Isomap, LLE, diffusion maps and PHATE

When rows lie on a curved sheet, PCA folds it flat and mixes distant parts. Manifold maps follow the sheet instead. Learn which one to pick and how to tell when the neighbor graph lets you down.

Advanced ~14 min8 steps

What runs in CodeSplash

You will be able to

  • Explain why a straight projection fails on a curved surface and what a neighbor graph fixes
  • Choose among Isomap, the LLE family, Laplacian eigenmaps, diffusion maps and PHATE
  • Read residual variance, the neighbor count and the "graph splits into pieces" stop

Read first

01

A sheet rolled into an S

Read

Picture a strip of paper bent into an S and floating in three dimensions. Two points can sit close in space yet far apart along the paper, because they lie on different bends.

PCA projects straight through the S and stacks the bends on top of each other. A manifold mapManifold learningMaps that follow a curved surface the rows lie on, instead of cutting straight across it as PCA does. instead links each row to its nearest neighbors and builds the map from that graph, so it follows the paper.

The fixture behind this lesson is exactly that: 240 noisy points on an S-shaped sheet.

02

Make a guess

Predict

Predict first

Would PCA's first two components unroll the S into a flat strip?

Yes, the S unrollsNo, the bends overlap
Reveal

No. PCA keeps the directions of largest variance, which cut across the bends. Points from opposite ends of the strip can land side by side. A neighbor graph never links them, so a manifold map keeps them apart.

03

Five ideas, one graph

Read

Every method here starts from the same graph: each row is linked to its k nearest rows (the row itself never counts).

MethodWhat the map keepsReach for it when
IsomapIsomapClassical scaling of distances measured along the neighbor graph, so a rolled-up sheet unrolls flat.Distances along the graph (geodesicGeodesic (graph) distanceDistance between two rows measured by hops along the neighbor graph, approximating distance along the surface.)One smooth sheet without holes
LLELocally linear embedding (LLE)Rebuilds each row as a weighted mix of its neighbors, then finds a map where the same weights still work.Each row's mix of its neighborsFast, local unrolling
Hessian LLEHessian LLEAn LLE variant that keeps functions with no curvature on each neighborhood; recovers flat, curled sheets exactly. and LTSALocal tangent space alignment (LTSA)Fits a flat patch (tangent space) to every neighborhood and aligns all patches into one map.Flat patches fitted to each neighborhoodA flat sheet that has been curled
Laplacian eigenmapsLaplacian eigenmapsCoordinates from the smoothest eigenvectors of the neighbor graph, so linked rows land close together.Linked rows land closeA quick, smooth layout of the graph
Diffusion mapDiffusion mapCoordinates from a random walk on a Gaussian kernel; map distance approximates how easily the walk links two rows.How easily a random walk moves between rowsUneven sampling, noisy data
PHATEPHATEDiffuses a neighbor kernel, takes log potentials and places rows by metric scaling; keeps branches and trajectories.Diffusion "potential" distancesBranches and trajectories

On the S-curve, Isomap keeps neighborhoods with trustworthiness 0.931 and leaves 11.2% of the graph distances' variance unexplained (its residual varianceResidual variance (Isomap)1 − r² between graph distances and map distances; 0 means the map reproduces every graph distance.). LTSA reaches 0.951, and PHATE 0.951.

Manifold maps (Isomap, LLE, diffusion maps, PHATE)Recorded · Python and R agreeRecorded 2026-11-25 · 16 values compared
R

Isomap map of 240 rows in 2 dimensions (10 neighbors): trustworthiness 0.931. Residual variance 0.112.

Trustworthiness (k = 10)
0.9309
Neighbors kept
75.5%
Residual variance
0.1123

Eigenvalues behind the map

DimensionEigenvalue
11227.06
2254.63
The exact R script · R R version 4.5.1 (2025-06-13)
# Manifold maps (Isomap, LLE, diffusion maps, PHATE)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.manifold 1.0.0 · spec ed55bb1c2ebf4969
# 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 <- "isomap"
METHOD_LABEL <- c(isomap = "Isomap", lle = "LLE", hlle = "Hessian LLE", ltsa = "LTSA",
                  laplacian = "Laplacian eigenmaps", diffusion = "Diffusion map", phate = "PHATE")[[METHOD]]
keep <- cs_ml_sample_rows(length(rows), 1000)
if (length(keep) < length(rows)) {
  warnings <- c(warnings, sprintf("%s maps %s evenly spaced rows of %s (the work 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]
D_REQ <- 2L
k <- cs_ml_mf_check(METHOD, length(rows), ncol(X), 10L, D_REQ)
if (k < 10L) warnings <- c(warnings, sprintf("Only %d rows: the graph uses %d neighbors instead of 10.", length(rows), k))

# %% Map
fit <- cs_ml_mf_fit(
  X, METHOD, k, D_REQ,
  reg = 0.001,
  affinity = "connectivity",
  alpha = 1,
  t = 1,
  epsilon = NULL,
  decay = 40,
  phate_t = NULL,
  max_iter = 300
)
Y <- fit$coords
K <- ncol(Y)
num_or_nan <- function(v) if (is.null(v)) NaN else as.numeric(v)
values <- list(
  n = length(rows),
  n_features = length(FEATURES),
  n_components = K,
  neighbors = k,
  residual_variance = num_or_nan(fit$residual_variance),
  recon_error = num_or_nan(fit$recon_error),
  bandwidth = num_or_nan(fit$bandwidth),
  epsilon = num_or_nan(fit$epsilon),
  phate_t = if (METHOD == "phate") as.numeric(fit$t) else NaN,
  stress = num_or_nan(fit$stress)
)
if (!is.null(fit$eigen)) for (j in seq_along(fit$eigen)) values[[sprintf("eigen[%d]", j)]] <- fit$eigen[j]
for (j in seq_len(K)) 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)
ok_eval <- k_eval >= 1L && 2 * length(sample) - 3 * k_eval - 1 > 0
trust_knn <- if (ok_eval) cs_ml_mf_neighborhood(X[sample, , drop = FALSE], Y[sample, , drop = FALSE], k_eval) else c(NaN, NaN)
values$trustworthiness <- unname(trust_knn[1])
values$knn_preservation <- unname(trust_knn[2])

# %% Artifacts
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.manifold/scurve_isomap/out-r")
emb <- data.frame(row = as.integer(rows))
for (j in seq_len(K)) emb[[sprintf("dim_%d", j)]] <- Y[, j]
nanoparquet::write_parquet(emb, file.path(out, "embedding.parquet"))

# %% Charts
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
}
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 = ","))))
if (METHOD == "isomap") {
  show <- cs_ml_even_sample(length(fit$geodesic), 2000) + 1L
  note <- sprintf("Residual variance %.3f", values$residual_variance)
  if (length(show) < length(fit$geodesic)) note <- paste0(note, sprintf("; %s of %s pairs shown", format(length(show), big.mark = ","), format(length(fit$geodesic), big.mark = ",")))
  charts[[length(charts) + 1L]] <- cs_chart("shepard", "shepard-diagram", "Graph distance against map distance", list(
    dissimilarity = cs_col("Graph (geodesic) distance", fit$geodesic[show], "numeric"),
    distance = cs_col("Map distance", fit$map_distance[show], "numeric")
  ), note = note)
}
if (METHOD == "phate") {
  ts <- seq_along(fit$vne)
  charts[[length(charts) + 1L]] <- cs_chart("vne", "elbow-plot", "Choosing the diffusion time", list(
    k = cs_col("Diffusion time t", as.numeric(ts), "numeric"),
    score = cs_col("Von Neumann entropy", fit$vne, "numeric"),
    criterion = cs_col("Criterion", rep("Von Neumann entropy", length(ts)), "categorical"),
    chosen = cs_col("Chosen t", ts == fit$t, "boolean")
  ), note = sprintf("t = %d%s", as.integer(fit$t), if (is.null(NULL)) " (knee of the entropy curve)" else " (set)"))
}

# %% Result
tables <- list()
if (!is.null(fit$eigen)) {
  tables[[1]] <- list(
    key = "eigen",
    title = "Eigenvalues behind the map",
    columns = list(list(key = "dimension", label = "Dimension", type = "integer"), list(key = "eigen", label = "Eigenvalue", type = "number")),
    rows = lapply(seq_along(fit$eigen), function(j) list(dimension = j, eigen = fit$eigen[j]))
  )
}
summary <- sprintf("%s map of %d rows in %d dimensions (%d neighbors): trustworthiness %.3f.", METHOD_LABEL, length(rows), K, k, values$trustworthiness)
if (METHOD == "isomap") summary <- paste(summary, sprintf("Residual variance %.3f.", values$residual_variance))
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")
)
if (METHOD == "isomap") statistics[[length(statistics) + 1L]] <- list(key = "residual_variance", label = "Residual variance", value = values$residual_variance)
if (METHOD == "phate") statistics[[length(statistics) + 1L]] <- list(key = "phate_t", label = "Diffusion time t", value = values$phate_t)
cs_publish(list(
  title = "Manifold maps (Isomap, LLE, diffusion maps, PHATE)",
  engine = cs_engine_info("codesplashr", "nanoparquet"),
  n = length(rows),
  summary = summary,
  statistics = statistics,
  tables = tables,
  charts = charts,
  values = values,
  warnings = warnings,
  artifacts = list(list(key = "embedding", path = file.path(out, "embedding.parquet"), format = "parquet"))
))
Python

Isomap map of 240 rows in 2 dimensions (10 neighbors): trustworthiness 0.931. Residual variance 0.112.

Trustworthiness (k = 10)
0.9309
Neighbors kept
75.5%
Residual variance
0.1123

Eigenvalues behind the map

DimensionEigenvalue
11227.06
2254.63
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Manifold maps (Isomap, LLE, diffusion maps, PHATE)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.manifold 1.0.0 · spec ed55bb1c2ebf4969
# 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 cluster as csc
from codesplash.ml import embed as csembed
from codesplash.ml import manifold as csman

# %% 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 = "isomap"
METHOD_LABEL = csman.METHOD_LABELS[METHOD]
keep = csembed.sample_rows(len(rows), 1000)
if len(keep) < len(rows):
    warnings.append(f"{METHOD_LABEL} maps {len(keep):,} evenly spaced rows of {len(rows):,} (the work grows with the square of the rows).")
X = X[keep]
rows = rows[keep]
D_REQ = 2
k = csman.check_setup(METHOD, len(rows), X.shape[1], 10, D_REQ)
if k < 10:
    warnings.append(f"Only {len(rows)} rows: the graph uses {k} neighbors instead of 10.")

# %% Map
fit = csman.fit(
    X,
    METHOD,
    k,
    D_REQ,
    reg=0.001,
    affinity="connectivity",
    alpha=1,
    t=1,
    epsilon=None,
    decay=40,
    phate_t=None,
    max_iter=300,
)
Y = fit["coords"]
K = Y.shape[1]
NAN = float("nan")
values = {
    "n": len(rows),
    "n_features": len(FEATURES),
    "n_components": K,
    "neighbors": k,
    "residual_variance": float(fit.get("residual_variance", NAN)),
    "recon_error": float(fit.get("recon_error", NAN)),
    "bandwidth": float(fit.get("bandwidth", NAN)),
    "epsilon": float(fit.get("epsilon", NAN)),
    "phate_t": float(fit["t"]) if METHOD == "phate" else NAN,
    "stress": float(fit.get("stress", NAN)),
}
eigen = fit.get("eigen")
if eigen is not None:
    for j, v in enumerate(eigen):
        values[f"eigen[{j + 1}]"] = float(v)
for j in range(K):
    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)
ok_eval = k_eval >= 1 and 2 * len(sample) - 3 * k_eval - 1 > 0
trust_knn = csman.neighborhood_scores(X[sample], Y[sample], k_eval) if ok_eval else (NAN, NAN)
values["trustworthiness"], values["knn_preservation"] = float(trust_knn[0]), float(trust_knn[1])

# %% Artifacts
out = csml.out_dir("target/academy-parity/run-8142/discover.manifold/scurve_isomap/out-python")
emb = pd.DataFrame({"row": rows.astype(np.int64)})
for j in range(K):
    emb[f"dim_{j + 1}"] = Y[:, j]
emb.to_parquet(os.path.join(out, "embedding.parquet"), index=False)

# %% Charts
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))]
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.")]
if METHOD == "isomap":
    show = csc.even_sample(len(fit["geodesic"]), 2000)
    charts.append(cs.chart("shepard", "shepard-diagram", "Graph distance against map distance", {
        "dissimilarity": cs.col("Graph (geodesic) distance", fit["geodesic"][show], "numeric"),
        "distance": cs.col("Map distance", fit["map_distance"][show], "numeric"),
    }, note=f"Residual variance {values['residual_variance']:.3f}" + ("" if len(show) == len(fit["geodesic"]) else f"; {len(show):,} of {len(fit['geodesic']):,} pairs shown")))
if METHOD == "phate":
    vne = fit["vne"]
    ts = np.arange(1, len(vne) + 1)
    charts.append(cs.chart("vne", "elbow-plot", "Choosing the diffusion time", {
        "k": cs.col("Diffusion time t", ts.astype(float), "numeric"),
        "score": cs.col("Von Neumann entropy", vne, "numeric"),
        "criterion": cs.col("Criterion", ["Von Neumann entropy"] * len(vne), "categorical"),
        "chosen": cs.col("Chosen t", [bool(t == fit["t"]) for t in ts], "boolean"),
    }, note=f"t = {fit['t']}" + (" (knee of the entropy curve)" if None is None else " (set)")))

# %% Result
tables = []
if eigen is not None:
    tables.append({
        "key": "eigen",
        "title": "Eigenvalues behind the map",
        "columns": [{"key": "dimension", "label": "Dimension", "type": "integer"}, {"key": "eigen", "label": "Eigenvalue", "type": "number"}],
        "rows": [{"dimension": j + 1, "eigen": float(v)} for j, v in enumerate(eigen)],
    })
trust = values["trustworthiness"]
summary = f"{METHOD_LABEL} map of {len(rows)} rows in {K} dimensions ({k} neighbors): trustworthiness {trust:.3f}."
if METHOD == "isomap":
    summary += f" Residual variance {values['residual_variance']:.3f}."
statistics = [
    {"key": "trustworthiness", "label": f"Trustworthiness (k = {k_eval})", "value": values["trustworthiness"]},
    {"key": "knn_preservation", "label": "Neighbors kept", "value": values["knn_preservation"], "format": "percent"},
]
if METHOD == "isomap":
    statistics.append({"key": "residual_variance", "label": "Residual variance", "value": values["residual_variance"]})
if METHOD == "phate":
    statistics.append({"key": "phate_t", "label": "Diffusion time t", "value": values["phate_t"]})
cs.publish({
    "title": "Manifold maps (Isomap, LLE, diffusion maps, PHATE)",
    "engine": cs.engine_info("numpy", "scipy", "pandas"),
    "n": len(rows),
    "summary": summary,
    "statistics": statistics,
    "tables": tables,
    "charts": charts,
    "values": values,
    "warnings": warnings,
    "artifacts": [{"key": "embedding", "path": os.path.join(out, "embedding.parquet"), "format": "parquet"}],
})

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

04

Neighbors make or break the map

Read

The neighbor count is the one setting that matters most.

  • Too few, and the graph falls apart into pieces. The app stops and says how many pieces it found, because separate pieces can't share one map.
  • Too many, and links jump across the bends of the sheet. One such shortcut is enough to fold the map back up.

Try two or three values. Structure that survives a change of k is more believable.

05

Reading the numbers

Read
  • Trustworthiness works as it does for t-SNE and UMAP: are rows that look close on the map really close in the data?
  • Residual variance (Isomap only) is 1 − r² between graph distances and map distances. Watch whether adding a dimension lowers it much.
  • Eigenvalues are listed under the map. A clear gap after the last one you kept suggests the dimension count fits.
  • For PHATE the card shows the diffusion time t. Automatic picks the knee of the von Neumann entropyVon Neumann entropy (PHATE)Entropy of the diffusion spectrum raised to t; PHATE picks t at the knee, where it stops falling quickly. curve. Here it chose 7.

The diffusion map on the same sheet used ε = 0.476 (the median squared distance to each row's 10th neighbor). On iris, Laplacian eigenmaps keep trustworthiness 0.932.

06

Maps up to a rotation

Read

LLE, Hessian LLE and LTSA find a set of directions, not particular axes, so any rotation of their map is equally right. The app turns each map so it lines up with the data's principal components. That way Python and R draw the same picture. Read shapes and neighbors, not which way an axis points.

07

Check your understanding

Checkpoint

Check yourself

Isomap stops with "the 10-nearest-neighbor graph splits into 3 separate pieces". What should you try first?

Show the answer

Answer: b

Separate pieces have no path between them, so graph distances between pieces don't exist. More neighbors can join them, but if the groups are genuinely apart, cluster first and map each group.

Check yourself

You raise Isomap's neighbors from 10 to 80 on a rolled sheet, and the map suddenly folds back on itself. Why?

Show the answer

Answer: a

Graph distances are only right when every link stays on the surface. Too many neighbors adds shortcuts across folds.

Check yourself

Your rows are sampled very unevenly: dense in one region, sparse elsewhere. Which setting helps a diffusion map ignore that?

Show the answer

Answer: b

With α = 1 the map follows the shape of the surface (Laplace–Beltrami), not how densely it was sampled. α = 0 lets dense regions pull the walk.

Check yourself

An LTSA map from Python and one from another tool look the same but rotated by 40°. What does that tell you?

Show the answer

Answer: a

The LLE family recovers a subspace. CodeSplash rotates it to line up with the principal components so both engines agree; other tools may not.

08

Do it on your own data

In the app

Under Map the data, open Manifold maps, pick a method and compare two neighbor counts. The Validity tab shows trustworthiness and continuity for every neighborhood size.

Python
from sklearn.datasets import make_s_curve
from sklearn.manifold import Isomap, LocallyLinearEmbedding, trustworthiness
from sklearn.preprocessing import StandardScaler

X, t = make_s_curve(240, noise=0.03, random_state=1)
X = StandardScaler().fit_transform(X)
for model in (Isomap(n_neighbors=10), LocallyLinearEmbedding(n_neighbors=10, method="ltsa")):
    Y = model.fit_transform(X)
    print(type(model).__name__, round(trustworthiness(X, Y, n_neighbors=10), 3))
R
library(codesplashr)
set.seed(1)
u <- runif(240); v <- runif(240); t <- 3 * pi * (u - 0.5)
X <- scale(cbind(sin(t), 2 * v, sign(t) * (cos(t) - 1)))
fit <- cs_ml_mf_fit(X, "isomap", k = 10, d = 2)
fit$residual_variance

Concepts in this lesson