Manifold Learning

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

Many datasets have far more columns than real degrees of freedom: a photograph of a rotating object has thousands of pixels but only one angle that matters. Manifold learning assumes the data lies close to a low-dimensional curved surface (a manifold) embedded in the high-dimensional space, and tries to recover coordinates on that surface. Linear methods such as PCA (see PCA, TruncatedSVD & NMF) can only rotate and project the data; manifold methods can "unroll" a curled sheet. This page covers the sklearn.manifold module of scikit-learn 1.9 (checked in October 2026 against 1.9.1, Python 3.13, NumPy 2.5.4), how each estimator works, how to pick one, how to tune t-SNE, and the pitfalls. Examples target Python 3.13 or 3.14 and were run on Python 3.13. Every example was run on those versions and the printed output is real.

The module is mostly an exploration and visualisation tool. Several estimators cannot embed new points at all, so they do not fit well inside a prediction pipeline; the page says which ones can. For the wider picture of unsupervised methods see Clustering, PCA, TruncatedSVD & NMF and Choosing the Right Estimator; for the conceptual side see Machine Learning Fundamentals.

The idea: distances along the surface

Take a Swiss roll: a flat sheet rolled into a spiral. Two points on neighbouring turns of the roll are close in straight (Euclidean) distance but far apart if you must walk along the sheet. A method that trusts straight-line distance, such as PCA, will squash the turns on top of each other. Manifold methods build a neighbourhood graph (each point is connected to its n_neighbors closest points), and then preserve some property of that graph in a low-dimensional embedding.

A Swiss roll cross-section with a straight shortcut between points A and B, a longer path along the surface, and the same points after unrolling into a strip
Figure 1. A spiral cross-section of a Swiss roll and the strip it unrolls into

The straight dashed line between A and B is the Euclidean distance, which cuts through the empty space between turns. The thick path is the distance along the surface (geodesic distance). After unrolling, the 2-D distance between A and B should match the thick path rather than the dashed line. Isomap does this explicitly, locally linear embedding and spectral embedding preserve local neighbourhoods instead, and t-SNE preserves neighbour probabilities.

The estimators at a glance

Estimator What it preserves Strengths and limits Embeds new data

Isomap

Geodesic (graph shortest-path) distances

Global structure, few parameters; sensitive to short-circuits when noise bridges two turns

Yes, transform

LocallyLinearEmbedding

Local linear reconstruction weights of each neighbourhood

Variants method="modified", "hessian", "ltsa" reduce distortion; fragile with duplicates

Yes, transform

SpectralEmbedding

Graph Laplacian eigenvectors (Laplacian eigenmaps)

Good for clustered structure; embeds only the training set

No (fit_transform only)

MDS

Pairwise dissimilarities, by minimising stress (SMACOF)

Works with any dissimilarity matrix; metric and non-metric variants; iterative and slower

No (fit_transform only)

ClassicalMDS

Pairwise dissimilarities, by eigendecomposition (minimises strain)

Direct, deterministic; equals PCA for Euclidean distances (new in 1.8)

Yes, transform

TSNE

Neighbour probabilities (KL divergence)

Excellent for 2-D visualisation of clusters; stochastic, no global distances, no transform

No (fit_transform only)

The "Embeds new data" column matters in practice. A method with only fit_transform cannot sit as a step in a Pipeline that must later transform unseen rows, and it is not a feature extractor for a model that will predict on new data. TSNE raises an AttributeError if you call transform; use it for pictures, not for features.

The docs give the cost of each method in terms of the number of samples N, the input dimension D, the neighbours k and the output dimension d. Isomap is roughly O(N^2 (k + log N)) plus a dense eigenproblem of cost O(d N^2); LLE and spectral embedding avoid the all-pairs path computation; exact t-SNE is O(d N^2) and the Barnes-Hut approximation is O(d N log N). All of them are meant for datasets of thousands to tens of thousands of rows, not millions; subsample first for larger data.

Prepare the data

All of these methods rely on nearest-neighbour search, so features must share a scale. Standardise first, and use the same preprocessing for every method you compare:

import numpy as np
from sklearn.datasets import make_swiss_roll
from sklearn.manifold import (
    Isomap, LocallyLinearEmbedding, SpectralEmbedding, TSNE, ClassicalMDS, trustworthiness,
)
from sklearn.preprocessing import StandardScaler

X, color = make_swiss_roll(n_samples=1500, noise=0.05, random_state=0)
X = StandardScaler().fit_transform(X)

models = {
    "Isomap": Isomap(n_neighbors=12, n_components=2),
    "LLE": LocallyLinearEmbedding(n_neighbors=12, n_components=2, random_state=0),
    "Modified LLE": LocallyLinearEmbedding(
        n_neighbors=12, n_components=2, method="modified", random_state=0
    ),
    "Spectral": SpectralEmbedding(n_components=2, n_neighbors=12, random_state=0),
    "t-SNE": TSNE(n_components=2, perplexity=30, init="pca", random_state=0),
    "ClassicalMDS": ClassicalMDS(n_components=2),
}
for name, model in models.items():
    Z = model.fit_transform(X)
    t = trustworthiness(X, Z, n_neighbors=12)
    print(f"{name:13s} shape={Z.shape} trustworthiness={t:.3f}")

print("Isomap reconstruction_error:", round(models["Isomap"].reconstruction_error(), 4))
print("LLE reconstruction_error_:", models["LLE"].reconstruction_error_)
print("t-SNE kl_divergence_:", round(models["t-SNE"].kl_divergence_, 3), "n_iter_:", models["t-SNE"].n_iter_)
Isomap        shape=(1500, 2) trustworthiness=1.000
LLE           shape=(1500, 2) trustworthiness=0.997
Modified LLE  shape=(1500, 2) trustworthiness=0.996
Spectral      shape=(1500, 2) trustworthiness=0.889
t-SNE         shape=(1500, 2) trustworthiness=0.999
ClassicalMDS  shape=(1500, 2) trustworthiness=0.854
Isomap reconstruction_error: 0.1802
LLE reconstruction_error_: 6.039417609695815e-08
t-SNE kl_divergence_: 0.495 n_iter_: 999

The trustworthiness score (0 to 1) measures how many of the k nearest neighbours of a point in the embedding were also neighbours in the original space; 1 means no false neighbours. ClassicalMDS scores lowest here, as expected: the roll is curled, and ClassicalMDS with Euclidean distances is a linear projection (it reproduces PCA). Treat the score as a way to compare embeddings of the same data, not as an absolute quality grade, and keep in mind that it only inspects neighbourhoods, not global layout.

Isomap

Isomap (isometric mapping) builds the neighbour graph, replaces each pairwise distance by the length of the shortest path through the graph, and then runs classical MDS on those geodesic distances. Parameters worth knowing:

  • n_neighbors (default 5) or radius: the graph connectivity. Too small and the graph falls into disconnected pieces; too large and distant turns connect ("short-circuit") and the unrolling fails.

  • n_components (default 2): the embedding dimension. reconstruction_error() helps pick it.

  • path_method and eigen_solver: left at "auto" unless you have a reason; the docs say scikit-learn selects them.

  • metric, p and metric_params: the distance used to build the graph (Minkowski by default).

Because it has a transform, Isomap works inside a pipeline. This one reduces the 64 pixel features of the digits data to five coordinates and classifies with nearest neighbours; the splitter and stratification are explained in Train/Test Split:

from sklearn.datasets import load_digits
from sklearn.manifold import Isomap
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

X, y = load_digits(return_X_y=True)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, stratify=y, random_state=0)
pipe = make_pipeline(StandardScaler(), Isomap(n_neighbors=10, n_components=5), KNeighborsClassifier())
pipe.fit(X_tr, y_tr)
print("Isomap+kNN accuracy:", round(pipe.score(X_te, y_te), 3))
print(pipe.named_steps["isomap"].embedding_.shape)
Isomap+kNN accuracy: 0.94
(1347, 5)

Source: scikit-learn User Guide, Isomap; pipelines are covered in Pipelines.

Locally linear embedding and its variants

LLE describes each point as a weighted combination of its neighbours, then finds low-dimensional coordinates that are reconstructed by the same weights. All four variants share one class and are selected by method:

method Idea Constraint on n_neighbors

"standard" (default)

Plain LLE with a regularisation term reg that can distort the embedding

None beyond being larger than the target dimension

"modified" (MLLE)

Uses several weight vectors per neighbourhood, which removes most of the distortion

n_neighbors > n_components

"hessian" (HLLE)

Estimates a Hessian-based quadratic form on the local tangent space

n_neighbors > n_components * (n_components + 3) / 2

"ltsa"

Local tangent space alignment

None beyond being larger than the target dimension

Singular weight matrices occur when the data contains duplicate points or disconnected groups. If the arpack solver cannot find the null space, switch to eigen_solver="dense" (slower), remove the duplicates, or raise n_neighbors for disconnected groups. A reconstruction error near zero (as in the run above) is not a quality measure on its own: it tells you the weights fit, not that the unrolling is right.

Spectral embedding

SpectralEmbedding (Laplacian eigenmaps) builds a similarity graph and uses the lowest eigenvectors of its graph Laplacian as coordinates. affinity selects the graph: "nearest_neighbors" (default), "rbf", "precomputed" or "precomputed_nearest_neighbors". It tends to separate clusters well (it is the same machinery as spectral clustering, see Clustering) but preserves distances poorly, as the 0.889 trustworthiness above shows. There is no transform: only the training set is embedded.

Multi-dimensional scaling

MDS finds points whose pairwise distances match a given dissimilarity matrix, which makes it the natural choice when you only have distances (survey similarities, edit distances between strings) rather than coordinates. scikit-learn has two implementations, and the API changed in 1.8 and 1.9.

  • MDS runs the iterative SMACOF algorithm and minimises stress. With metric_mds=True (the default) it matches the dissimilarities themselves (metric MDS); with metric_mds=False it uses isotonic regression to preserve only their ordering (non-metric MDS), and normalized_stress=True gives Stress-1.

  • ClassicalMDS (new in 1.8) minimises strain by a single eigendecomposition: no iterations, no random starts. With Euclidean distances it is equivalent to PCA.

import numpy as np
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
from sklearn.manifold import MDS, ClassicalMDS
from sklearn.metrics import pairwise_distances

X, y = load_digits(return_X_y=True)
X = X[:800]

# Classical MDS == PCA (up to sign) for Euclidean distances
Zc = ClassicalMDS(n_components=2).fit_transform(X)
Zp = PCA(n_components=2).fit_transform(X)
print("ClassicalMDS vs PCA, max |abs| diff:", float(np.abs(np.abs(Zc) - np.abs(Zp)).max().round(6)))

# MDS from a precomputed dissimilarity matrix, starting from the classical solution
D = pairwise_distances(X[:300])
mds = MDS(n_components=2, metric="precomputed", init="classical_mds",
          normalized_stress="auto", random_state=0)
Zm = mds.fit_transform(D)
print("MDS stress_:", round(mds.stress_, 1), "shape", Zm.shape)

# non-metric MDS keeps only the ordering of distances
nm = MDS(n_components=2, metric_mds=False, init="classical_mds", metric="precomputed",
         normalized_stress=True, random_state=0)
nm.fit(D)
print("non-metric stress-1:", round(nm.stress_, 4))
ClassicalMDS vs PCA, max |abs| diff: 0.0
MDS stress_: 10906462.6 shape (300, 2)
non-metric stress-1: 0.2824

The MDS signature moved several times, and tutorials written before 2025 use names that now warn or fail:

Older code Current behaviour Since

MDS(metric=False) for non-metric MDS

The metric parameter now names the distance ("euclidean" or "precomputed"); use metric_mds=False. Passing a boolean is dropped in 1.10.

1.8

MDS(dissimilarity="precomputed")

Renamed metric="precomputed"; dissimilarity is deprecated and removed in 1.10

1.8

MDS(n_init=4) as the default

The default n_init is now 1

1.9

Default init random

init is "random" or "classical_mds"; leaving it unset emits a warning because the default changes to "classical_mds" in 1.10. Pass it explicitly to silence the warning

1.8 (upcoming default change in 1.10)

eps=1e-3 convergence tolerance

Default eps=1e-6 after a bug fix in the stopping criterion; stress values from old runs are not comparable

1.7

t-SNE

t-distributed stochastic neighbour embedding turns distances into neighbour probabilities in both spaces and moves the embedded points to minimise the Kullback-Leibler divergence between the two distributions. It is the usual choice for looking at clusters in a 2-D plot. The cost is that the picture is easy to over-read.

Parameters

  • perplexity (default 30): roughly the effective number of neighbours of each point. Larger values suit larger or noisier datasets. It must be smaller than the number of samples.

  • early_exaggeration (default 12): rarely needs changing; too large a value can increase the divergence in the early phase.

  • learning_rate (default "auto"): sample size divided by the early-exaggeration factor. Too low gets stuck in local minima; too high raises the divergence.

  • init: "pca" (default) or "random". PCA initialisation is deterministic and better preserves global structure; prefer it.

  • max_iter (default 1000; named n_iter in old code, renamed in 1.5) and n_iter_without_progress.

  • method: "barnes_hut" (default, O(N log N), only n_components below 4, dense input only) or "exact" (O(N^2), small datasets).

  • angle: the Barnes-Hut speed/accuracy trade-off; unused by the exact method.

  • metric: any distance that scikit-learn knows, or "precomputed".

from sklearn.datasets import load_digits
from sklearn.manifold import TSNE, trustworthiness

X, y = load_digits(return_X_y=True)
X = X[:800]

for p in (5, 30, 100):
    Z = TSNE(perplexity=p, init="pca", random_state=0).fit_transform(X)
    print(f"perplexity={p:3d} trustworthiness={trustworthiness(X, Z, n_neighbors=10):.3f}")

for seed in range(4):
    t = TSNE(perplexity=30, init="random", random_state=seed).fit(X)
    print("random init seed", seed, round(t.kl_divergence_, 3))

print("TSNE has transform:", hasattr(TSNE(), "transform"))
perplexity=  5 trustworthiness=0.989
perplexity= 30 trustworthiness=0.993
perplexity=100 trustworthiness=0.991
random init seed 0 0.505
random init seed 1 0.502
random init seed 2 0.502
random init seed 3 0.502
TSNE has transform: False

How to read a t-SNE plot

  • The divergence is non-convex and the algorithm is stochastic, so different seeds can give different layouts. The docs recommend several runs and keeping the one with the lowest kl_divergence_. With init="pca" the starting layout is fixed, so runs usually differ little (the four PCA-initialised runs on this data matched to three decimals); random initialisation shows more spread.

  • Global structure is not preserved. The distance between two clusters, their relative size and their density in the plot carry little meaning. Cluster membership is the reliable part.

  • Failing to separate classes in a 2-D t-SNE picture does not prove the classes are inseparable; two dimensions may simply be too few.

  • Barnes-Hut accepts only dense input. For sparse data use a dense low-rank projection (for example TruncatedSVD, see PCA, TruncatedSVD & NMF) first, or the exact method.

  • Because it has no transform, you cannot add test rows to an existing embedding. Fit on all the data you want to show, and never use t-SNE coordinates as model features.

Choosing a method

flowchart TD A[Need a low-dimensional view?] --> B{Only dissimilarities available?} B -->|yes| C[MDS or ClassicalMDS with metric precomputed] B -->|no| D{Need to embed new rows?} D -->|yes| E[Isomap, LLE or ClassicalMDS] D -->|no| F{Goal} F -->|look at clusters| G[TSNE with init pca] F -->|global geometry| H[Isomap] F -->|graph structure| I[SpectralEmbedding] A --> J[Try PCA first: it is the baseline]

A practical sequence is: scale the data, run PCA and look at the explained variance; if a few components do not capture the structure, try Isomap or LLE for the geometry and t-SNE for a picture. Compare the embeddings with trustworthiness on the same n_neighbors.

Pitfalls

  • Unscaled features: one column in large units dominates the neighbour search and the embedding.

  • n_components and n_neighbors interplay: the reconstruction error falls as n_components grows until it reaches the manifold’s intrinsic dimension; use it to choose the dimension. Noisy data can short-circuit the manifold.

  • Duplicate rows and disconnected groups make LLE and spectral embedding singular (see above).

  • Stale tutorial code: MDS(metric=False), MDS(dissimilarity=...) and TSNE(n_iter=...) (renamed max_iter) fail or warn in current releases; and TSNE(learning_rate=...) guidance written for the old default of 200 predates "auto".

  • Reading a t-SNE plot as a map of distances (see above).

  • Unbounded cost: these methods scale at least quadratically in the worst case; subsample before embedding a large dataset.