Skip to content

Unrolling a manifold: Isomap, LLE, LTSA, Laplacian eigenmaps and MVU

All of these start from a nearest-neighbor graph and differ in what they keep - distances along the graph, local reconstruction weights, local tangent planes, or smoothness. See each objective and the one eigenproblem behind it.

Advanced ~15 min9 steps

What runs in CodeSplash

You will be able to

  • Write the objective of Isomap, LLE, Hessian LLE, LTSA and Laplacian eigenmaps and the eigenproblem each solves
  • Explain what the neighbor graph does for all of them and how it fails
  • Describe maximum variance unfolding as a semidefinite program and why it is explained here only

Read first

01

One graph, five objectives

Read

Each method here links every row to its kk nearest rows and assumes that, locally, the data look flat. They differ in what they ask the map to keep:

MethodKeepsSolves
IsomapIsomapClassical scaling of distances measured along the neighbor graph, so a rolled-up sheet unrolls flat.distances along the graphclassical MDS on graph distances
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 neighborsbottom eigenvectors of (I−W)⊤(I−W)(I-W)^\top(I-W)
Hessian LLEHessian LLEAn LLE variant that keeps functions with no curvature on each neighborhood; recovers flat, curled sheets exactly.local flatness (no curvature)null space of a Hessian estimate
LTSALocal tangent space alignment (LTSA)Fits a flat patch (tangent space) to every neighborhood and aligns all patches into one map.local tangent coordinatesalignment of local PCA patches
Laplacian eigenmapsLaplacian eigenmapsCoordinates from the smoothest eigenvectors of the neighbor graph, so linked rows land close together.linked rows closebottom eigenvectors of the graph Laplacian
02

Isomap: geodesics, then MDS

Read

Isomap replaces straight-line distances by shortest paths through the neighbor graph, the geodesic distancesGeodesic (graph) distanceDistance between two rows measured by hops along the neighbor graph, approximating distance along the surface., then runs classical MDS on them. Points on opposite bends of a rolled sheet stay far apart, because the graph never links them directly.

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.

On the S-curve, the map leaves 11.2% of the graph distances' variance unexplained, with trustworthiness 0.931. One shortcut edge across a bend is enough to wreck the geodesics.

03

LLE: copy each row's recipe

Read

LLE writes each row as a weighted mix of its neighbors, xi≈∑jwijxjx_i \approx \sum_j w_{ij} x_j with ∑jwij=1\sum_j w_{ij} = 1, then finds low-dimensional points that keep the same recipes:

min⁡Y∑i∥yi−∑jwijyj∥2.\min_Y \sum_i \Big\lVert y_i - \sum_j w_{ij} y_j \Big\rVert^2 .

The answer is the bottom eigenvectors of (I−W)⊤(I−W)(I - W)^\top (I - W), skipping the constant one. When kk exceeds the dimension, the weights aren't unique and need a small ridge term. On the S-curve its trustworthiness is 0.956.

04

Hessian LLE and LTSA: local planes

Read

Hessian LLE estimates, in each neighborhood's tangent plane, how curved a candidate map would be, and keeps the maps with zero curvature. Fitting a quadratic in dd tangent coordinates needs at least 1+d+d(d+1)/21 + d + d(d+1)/2 neighbors: 6 for a 2-D map. It recovers flat sheets that were curled, but is sensitive to noise.

LTSA runs PCA in every neighborhood to get local tangent coordinates, then finds one global map whose pieces line up with all of them by local affine changes.

Both find a subspace, so their maps are defined only up to rotation. LTSA reaches trustworthiness 0.951 here; Hessian LLE, with 12 neighbors, 0.923.

05

Laplacian eigenmaps: keep links short

Read

Give each edge a weight wijw_{ij} (1, or a heat kernel e−∥xi−xj∥2/te^{-\lVert x_i - x_j\rVert^2/t}) and minimize

∑ijwij∥yi−yj∥2subject toY⊤DY=I,\sum_{ij} w_{ij} \lVert y_i - y_j\rVert^2 \quad\text{subject to}\quad Y^\top D Y = I ,

where DD holds the degrees. That is the generalized eigenproblem Ly=λDyL y = \lambda D y with L=D−WL = D - W. The first eigenvector is constant and skipped; the next ones place strongly linked rows together. Spectral clustering uses the same eigenvectors.

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

Laplacian eigenmaps map of 240 rows in 2 dimensions (10 neighbors): trustworthiness 0.937.

Trustworthiness (k = 10)
0.9373
Neighbors kept
59.3%

Plots

Laplacian eigenmaps mapWhich rows group together, and how well separated are the groups?
View data
bandLaplacian eigenmaps 1Laplacian eigenmaps 2
D−0.0299−0.0133
C−0.02260.0037
C−0.02290.0033
A0.0493−0.0522
A0.0502−0.0546
D−0.0298−0.0130
C−0.02190.0038
A0.0487−0.0488
B0.02390.0290
D−0.0315−0.0190
B0.03410.0347
C−0.02060.0051
A0.0503−0.0544
D−0.0291−0.0109
B0.02050.0561
D−0.0249−0.0006
C−0.02220.0042
C−0.02220.0042
D−0.02400.0007
C−0.00500.0206
C−0.02200.0037
D−0.0298−0.0130
A0.0467−0.0336
A0.0502−0.0571
B0.03200.0355
D−0.0314−0.0188
C−0.02270.0033
C−0.01830.0072
B0.02350.0592
C−0.02360.0020
D−0.0316−0.0194
C−0.02010.0056
D−0.02430.0006
B0.03140.0628
C−0.00800.0177
A0.0502−0.0572
C−0.02290.0032
B0.02160.0578
D−0.0293−0.0125
D−0.0251−0.0012
D−0.0298−0.0130
C−0.02240.0040
B0.03180.0617
C−0.02330.0026
C−0.02360.0017
A0.0502−0.0563
A0.0502−0.0574
A0.03590.0235
C0.02080.0576
D−0.0252−0.0012
D−0.0274−0.0072
C−0.01160.0167
B0.03510.0266
A0.03530.0259
B0.03170.0610
B0.03060.0629
C−0.01910.0066
C−0.02457.404e-5
C−0.02280.0026
D−0.0247−0.0004

First 60 of 240 rows.

Eigenvalues behind the map

DimensionEigenvalue
10.0014
20.0071
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 4d049cf46dc66345
# 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 <- "laplacian"
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 = "heat",
  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_laplacian_heat/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

Laplacian eigenmaps map of 240 rows in 2 dimensions (10 neighbors): trustworthiness 0.937.

Trustworthiness (k = 10)
0.9373
Neighbors kept
59.3%

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

Eigenvalues behind the map

DimensionEigenvalue
10.0014
20.0071
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 4d049cf46dc66345
# 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 = "laplacian"
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="heat",
    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_laplacian_heat/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"}],
})

With a heat kernel of bandwidth 0.222, trustworthiness is 0.937.

06

Maximum variance unfolding

Read

MVUMaximum variance unfoldingUnrolls a manifold by spreading points as far apart as possible while neighbor distances stay fixed, solved as a semidefinite program. pulls the data apart as far as possible while keeping every neighbor distance fixed. It optimizes the Gram matrix KK directly:

max⁡K⪰0tr⁡(K)s.t.K1=0,    Kii+Kjj−2Kij=∥xi−xj∥2 for neighbors.\max_{K \succeq 0} \operatorname{tr}(K) \quad\text{s.t.}\quad K\mathbf{1} = 0,\;\; K_{ii} + K_{jj} - 2K_{ij} = \lVert x_i - x_j\rVert^2 \text{ for neighbors}.

The trace is the total spread. In the reference's check, a centered Gram matrix satisfying the constraints has trace 108. Solving it is a semidefinite program, costly beyond a few thousand rows.

07

Readiness

Read

Isomap, LLE, Hessian LLE, LTSA and Laplacian eigenmaps run in CodeSplash: Discover → Manifold maps, in Python and R. MVU is explained here: its semidefinite program is too slow for the app's data sizes, and noisy neighbor distances can make the constraints incompatible with a low-dimensional answer.

Reference · REP040 · Explained hereMaximum variance unfolding (MVU)Unfold a manifold by maximizing global spread while preserving distances on a local neighborhood graph.
08

Check: manifold maps

Checkpoint

Check yourself

Put Isomap's steps in order.

  1. 1Run classical MDS on those distances
  2. 2Compute shortest-path distances through the graph
  3. 3Link each row to its nearest neighbors

Show the answer

The order:

  1. Link each row to its nearest neighbors
  2. Compute shortest-path distances through the graph
  3. Run classical MDS on those distances

Neighbor graph, geodesics, then classical scaling.

Check yourself

Why can a single wrong edge ruin an Isomap map?

Show the answer

Answer: a

Every shortest path that can use the shortcut will, so one edge distorts distances between whole regions.

Check yourself

What does LLE keep from the original data?

Show the answer

Answer: a

LLE assumes each neighborhood is nearly flat, so the same mixing weights should rebuild each point in the low-dimensional map.

Check yourself

Why does LLE add a small ridge term when computing the weights?

Show the answer

Answer: a

The local Gram matrix is singular when kk exceeds the dimension, so the weights aren't unique without regularization.

Check yourself

Hessian LLE fits a quadratic in dd tangent coordinates: 1+d+d(d+1)/21 + d + d(d+1)/2 terms. How many neighbors does it need, at least, for a 3-dimensional map?

Show the answer

Answer: 10

1+3+3⋅4/2=1+3+6=101 + 3 + 3 \cdot 4/2 = 1 + 3 + 6 = 10.

Check yourself

What is Hessian LLE good at, and what is its weakness?

Show the answer

Answer: a

Second derivatives amplify noise. Compare it with LTSA and Isomap on the same data.

Check yourself

What does LTSA compute in each neighborhood before aligning them?

Show the answer

Answer: a

Each local PCA gives a small coordinate patch; LTSA then finds one global map that matches every patch up to an affine change.

Check yourself

Python's and another tool's LTSA maps look identical but rotated. Is one wrong?

Show the answer

Answer: a

CodeSplash rotates the map to line up with the principal components so both engines draw the same picture.

Check yourself

What does the Laplacian eigenmaps objective ∑wij∥yi−yj∥2\sum w_{ij}\lVert y_i - y_j\rVert^2 reward?

Show the answer

Answer: a

Heavy edges make distance costly, so linked rows land together. The constraint Y⊤DY=IY^\top D Y = I stops everything collapsing to one point.

Check yourself

Why is the first eigenvector of the graph Laplacian skipped?

Show the answer

Answer: a

A constant vector makes every yi−yjy_i - y_j zero, so it minimizes the objective trivially.

Check yourself

What does MVU maximize, and what does it hold fixed?

Show the answer

Answer: a

Pulling everything apart while local distances are pinned unrolls the manifold, like stretching a crumpled net.

Check yourself

Why is MVU explained here rather than run in CodeSplash?

Show the answer

Answer: a

Semidefinite programs scale badly with nn. Isomap and the Laplacian methods give similar unrollings with one eigendecomposition.

09

Recap

Recap
  • All start from a neighbor graph; too few neighbors split it, too many add shortcuts.
  • Isomap keeps geodesics, LLE keeps neighbor recipes, Hessian LLE and LTSA keep local planes, Laplacian eigenmaps keep links short.
  • MVU maximizes spread with neighbor distances fixed; it is a semidefinite program, explained here only.

Concepts in this lesson