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.
What runs in CodeSplash
- REP028Isomap Runs in CodeSplash
- REP029Locally linear embedding (LLE) Runs in CodeSplash
- REP030Hessian LLE / Hessian eigenmaps Runs in CodeSplash
- REP031Local tangent space alignment (LTSA) Runs in CodeSplash
- REP032Laplacian eigenmaps Runs in CodeSplash
- REP040Maximum variance unfolding (MVU) Explained here
- Manifold maps (Isomap, LLE, diffusion maps, PHATE) Verified in Python and R
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
One graph, five objectives
ReadEach method here links every row to its nearest rows and assumes that, locally, the data look flat. They differ in what they ask the map to keep:
| Method | Keeps | Solves |
|---|---|---|
| IsomapIsomapClassical scaling of distances measured along the neighbor graph, so a rolled-up sheet unrolls flat. | distances along the graph | classical 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 neighbors | bottom eigenvectors of |
| 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 coordinates | alignment of local PCA patches |
| Laplacian eigenmapsLaplacian eigenmapsCoordinates from the smoothest eigenvectors of the neighbor graph, so linked rows land close together. | linked rows close | bottom eigenvectors of the graph Laplacian |
Isomap: geodesics, then MDS
ReadIsomap 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.
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
| Dimension | Eigenvalue |
|---|---|
| 1 | 1227.06 |
| 2 | 254.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"))
))
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
| Dimension | Eigenvalue |
|---|---|
| 1 | 1227.06 |
| 2 | 254.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.
LLE: copy each row's recipe
ReadLLE writes each row as a weighted mix of its neighbors, with , then finds low-dimensional points that keep the same recipes:
The answer is the bottom eigenvectors of , skipping the constant one. When exceeds the dimension, the weights aren't unique and need a small ridge term. On the S-curve its trustworthiness is 0.956.
Hessian LLE and LTSA: local planes
ReadHessian 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 tangent coordinates needs at least 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.
Laplacian eigenmaps: keep links short
ReadGive each edge a weight (1, or a heat kernel ) and minimize
where holds the degrees. That is the generalized eigenproblem with . The first eigenvector is constant and skipped; the next ones place strongly linked rows together. Spectral clustering uses the same eigenvectors.
Laplacian eigenmaps map of 240 rows in 2 dimensions (10 neighbors): trustworthiness 0.937.
- Trustworthiness (k = 10)
- 0.9373
- Neighbors kept
- 59.3%
Plots
View data
| band | Laplacian eigenmaps 1 | Laplacian eigenmaps 2 |
|---|---|---|
| D | −0.0299 | −0.0133 |
| C | −0.0226 | 0.0037 |
| C | −0.0229 | 0.0033 |
| A | 0.0493 | −0.0522 |
| A | 0.0502 | −0.0546 |
| D | −0.0298 | −0.0130 |
| C | −0.0219 | 0.0038 |
| A | 0.0487 | −0.0488 |
| B | 0.0239 | 0.0290 |
| D | −0.0315 | −0.0190 |
| B | 0.0341 | 0.0347 |
| C | −0.0206 | 0.0051 |
| A | 0.0503 | −0.0544 |
| D | −0.0291 | −0.0109 |
| B | 0.0205 | 0.0561 |
| D | −0.0249 | −0.0006 |
| C | −0.0222 | 0.0042 |
| C | −0.0222 | 0.0042 |
| D | −0.0240 | 0.0007 |
| C | −0.0050 | 0.0206 |
| C | −0.0220 | 0.0037 |
| D | −0.0298 | −0.0130 |
| A | 0.0467 | −0.0336 |
| A | 0.0502 | −0.0571 |
| B | 0.0320 | 0.0355 |
| D | −0.0314 | −0.0188 |
| C | −0.0227 | 0.0033 |
| C | −0.0183 | 0.0072 |
| B | 0.0235 | 0.0592 |
| C | −0.0236 | 0.0020 |
| D | −0.0316 | −0.0194 |
| C | −0.0201 | 0.0056 |
| D | −0.0243 | 0.0006 |
| B | 0.0314 | 0.0628 |
| C | −0.0080 | 0.0177 |
| A | 0.0502 | −0.0572 |
| C | −0.0229 | 0.0032 |
| B | 0.0216 | 0.0578 |
| D | −0.0293 | −0.0125 |
| D | −0.0251 | −0.0012 |
| D | −0.0298 | −0.0130 |
| C | −0.0224 | 0.0040 |
| B | 0.0318 | 0.0617 |
| C | −0.0233 | 0.0026 |
| C | −0.0236 | 0.0017 |
| A | 0.0502 | −0.0563 |
| A | 0.0502 | −0.0574 |
| A | 0.0359 | 0.0235 |
| C | 0.0208 | 0.0576 |
| D | −0.0252 | −0.0012 |
| D | −0.0274 | −0.0072 |
| C | −0.0116 | 0.0167 |
| B | 0.0351 | 0.0266 |
| A | 0.0353 | 0.0259 |
| B | 0.0317 | 0.0610 |
| B | 0.0306 | 0.0629 |
| C | −0.0191 | 0.0066 |
| C | −0.0245 | 7.404e-5 |
| C | −0.0228 | 0.0026 |
| D | −0.0247 | −0.0004 |
First 60 of 240 rows.
Eigenvalues behind the map
| Dimension | Eigenvalue |
|---|---|
| 1 | 0.0014 |
| 2 | 0.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"))
))
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
| Dimension | Eigenvalue |
|---|---|
| 1 | 0.0014 |
| 2 | 0.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.
Maximum variance unfolding
ReadMVUMaximum 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 directly:
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.
Readiness
ReadIsomap, 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.Check: manifold maps
CheckpointCheck yourself
Put Isomap's steps in order.
Show the answer
The order:
- Link each row to its nearest neighbors
- Compute shortest-path distances through the graph
- 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 exceeds the dimension, so the weights aren't unique without regularization.
Check yourself
Hessian LLE fits a quadratic in tangent coordinates: terms. How many neighbors does it need, at least, for a 3-dimensional map?
Show the answer
Answer: 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 reward?
Show the answer
Answer: a
Heavy edges make distance costly, so linked rows land together. The constraint 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 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 . Isomap and the Laplacian methods give similar unrollings with one eigendecomposition.
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