LLE, Laplacian eigenmaps and diffusion maps
Local spectral methods use neighborhood reconstruction or connectivity; diffusion maps add time. Derive and unify these methods as data-built kernel PCA, then embed new points with Nyström.
After this lesson you can
- Derive LLE reconstruction weights, its eigenvalue problem and invariances.
- Derive Laplacian eigenmaps as a constrained minimization of weighted squared distances.
- Construct diffusion maps and explain diffusion distance and α normalization.
- Explain these methods as kernel PCA with data-built kernels.
- Implement Nyström extension to embed new points.
Before you start
Motivation: trusting only neighbors
Isomap makes a global bet: it estimates geodesic distance between all pairs of points using shortest paths on the neighbor graph, then asks classical MDS to preserve it. If the graph is faithful, the result is spectacular. But a shortest path uses the best available route, and one edge jumping between two layers of the manifold (a shortcut, caused by noise or sparse sampling) can make thousands of geodesic distances use it. Balasubramanian and Schwartz (2002) pointed out this topological instability in a Science comment shortly after Isomap was published.
See the effect on a noisy Swiss roll. The cell counts edges in the 10-neighbor graph joining points more than 8 units apart along the manifold (on a roll approximately 89 long and 21 high) and uses Spearman correlation to measure whether each method’s first coordinate traverses the roll from one end to the other.
import numpy as np, warnings
from sklearn.datasets import make_swiss_roll
from sklearn.manifold import Isomap, LocallyLinearEmbedding, SpectralEmbedding
from sklearn.neighbors import kneighbors_graph
from scipy.stats import spearmanr
warnings.filterwarnings("ignore")
def abscisa(t):
"""Longitud de arco de la espiral (t cos t, t sin t) desde t = 0."""
return 0.5 * (t * np.sqrt(1 + t**2) + np.arcsinh(t))
X, t = make_swiss_roll(800, noise=0.5, random_state=0)
s = abscisa(t) # coordenada intrínseca a lo largo del rollo
A = kneighbors_graph(X, 10).tocoo()
salto = np.hypot(s[A.row] - s[A.col], X[A.row, 1] - X[A.col, 1])
print(f"aristas del grafo de 10 vecinos: {A.nnz}; atajos (más de 8 de distancia intrínseca): {(salto > 8).sum()}")
for nombre, m in [("Isomap", Isomap(n_neighbors=10, n_components=2)),
("LLE", LocallyLinearEmbedding(n_neighbors=10, n_components=2, random_state=0)),
("Mapas propios", SpectralEmbedding(n_components=2, n_neighbors=10, random_state=0))]:
Y = m.fit_transform(X)
print(f"{nombre:14s} |Spearman(y1, abscisa)| = {abs(spearmanr(Y[:, 0], s)[0]):.2f}")Two bad edges among 8000 suffice: Isomap’s first coordinate no longer follows the roll (Spearman 0.32), while LLE and Laplacian eigenmaps follow it almost perfectly (0.99). These methods do not ignore the shortcut: rather, it enters only one term of their objective, that of its edge or neighborhood, and does not propagate to distances between every pair. This is one particular sample; with more noise, more shortcuts appear and all methods eventually suffer, but the contrast illustrates their different designs.
This lesson studies the family of local spectral methods, which use only neighborhood information and turn it into an eigenvalue problem:
- LLE describes each point by how its neighbors reconstruct it and seeks low-dimensional coordinates with the same reconstructions.
- Laplacian eigenmaps use only which points are connected and seek the smoothest functions on the graph.
- Diffusion maps run a random walk on the graph and measure distances by how probability diffuses, with a time acting as a scale.
Later you will see that all three (and Isomap) are kernel PCA with a kernel built from the data, and that viewpoint resolves a practical problem inherent to spectral methods: how to embed a point absent from the sample.
LLE: reconstructing each point from its neighbors
Roweis and Saul’s (2000) idea starts from the manifold hypothesis: if data lie near a smooth -dimensional manifold, each point and its nearby neighbors lie approximately on a -dimensional patch of plane (the tangent space). On that patch, each point is a combination of its neighbors with weights describing the intrinsic local geometry. If a smooth map unrolls the manifold onto , locally it is almost a rigid motion (at most with a change of scale), and those same weights should reconstruct each point’s image from its neighbors’ images.
The two optimization problems use the same functional, but the roles are reversed: in step 2 the points are fixed and the weights are sought; in step 3 the weights are fixed and the points are sought.
Weights: a small quadratic problem per point
The error separates by rows: each solves its own problem with unknowns. Fix , denote its weights on neighbors by , and let . Since ,
is the positive semidefinite local Gram matrix. Notice the first step: the sum-to-one constraint is what lets us write the residual using only differences .
Proof
A positive semidefinite, invertible is positive definite, so the objective is strictly convex and the constraint affine: there is one minimum, characterized by the Lagrange conditions. With , the gradient vanishes if , that is, , and the constraint fixes . The error is .
∎In practice nothing is inverted: solve and divide by the sum of its components. Weights can be negative: if lies outside the convex hull of its neighbors, the best affine combination extrapolates.
Invariances: what the weights cannot see
In other words, weights do not see rotations, reflections, uniform scalings or translations of the neighborhood. The proof takes four lines and you will work through it in the exercises; the key is that translation disappears from differences only thanks to , and that is multiplied by , which cancels in the quotient for . Check it with the figure: transform the cloud, compare weights before and after, and remove the constraint.
The figure reveals two nuances. First, invariance applies to similarities (rotation, uniform scaling, translation), not every affine map: a general linear map changes to a matrix with entries , which is generally not proportional to . The exception is an exact and unique reconstruction ( in general position): then the weights are barycentric coordinates, which are preserved by any invertible affine map. Second, without the constraint, rotation and scaling still leave the weights unchanged (the least-squares problem with is invariant under ), but translation does change them, because the residual becomes .
When exceeds the dimension: regularize
with , so . With , is singular and the theorem does not apply. Distinguish two cases:
- With neighbors in general position, is singular but the sum-to-one solution is unique: the barycentric coordinates of , with zero error.
- With , exact combinations form an affine subspace of dimension : infinitely many solutions exist.
The second case matters in practice, and not only when : if data lie in near a 5-dimensional manifold, the local Gram matrix has a few large eigenvalues (the tangent space) and many near-zero ones (noise and curvature), and becomes ill-conditioned once exceeds the intrinsic dimension. The standard solution, already in Saul and Roweis (2003), is trace-proportional Tikhonov regularization:
which is what scikit-learn uses. It is equivalent to minimizing : among nearly exact reconstructions it favors spread-out weights, and as weights approach . Making proportional to the trace preserves scale invariance.
What happens without sufficient regularization on noiseless data is surprising. In a Swiss roll in , a point’s 12 neighbors are not coplanar (the surface curves), their affine hull is all of , and an exact reconstruction always exists. Then : each ambient coordinate , , has and lies in the null space of the step-3 matrix. LLE returns a linear projection of the data, like PCA, without unrolling anything. Regularization prevents exact reconstruction at the expense of low-variance directions (the surface normal), and the ambient coordinates leave the null space. You will see this in the lab.
The embedding: an eigenvalue problem
With fixed, is row of , so
Since every row of sums to one, and : the constant vector is an eigenvector with eigenvalue 0. The constraints remove the two trivial freedoms of : fixes translation (which does not change ), and prevents the solution and fixes the scale.
Proof
Since is symmetric and is an eigenvector, the orthogonal complement is invariant under and has the orthonormal eigenvector basis . With , the problem is to minimize over matrices with orthonormal columns in . By the Ky Fan principle (the sum version of the Courant–Fischer theorem) applied to the restriction of to , the minimum is the sum of its smallest eigenvalues, , attained by any orthonormal basis for the subspace spanned by their eigenvectors, which is unique if .
∎Thus LLE reduces to computing the eigenvectors with the smallest eigenvalues of a sparse matrix (each row of has nonzero entries, and has on the order of ) and discarding the constant one. For small eigenvalues of a sparse matrix, the efficient method is shift-invert Lanczos: eigsh(M, sigma=σ) factorizes once and seeks dominant eigenvalues of , which correspond to eigenvalues of nearest . With slightly negative , is positive definite (there is no need to factorize a singular matrix) and the nearest eigenvalues are the smallest.
The constraint has a cost: it forces each coordinate to have variance 1 and the coordinates to be uncorrelated, so LLE cannot recover proportions: even if it found both directions of a rectangle, it would return them with equal variance, as if it were a square. Goldberg, Zakai, Kushnir and Ritov (2008) show that this normalization makes LLE, Laplacian eigenmaps and other methods in the family fail even with perfect data in simple domains. Variants improving the local estimate (modified LLE by Zhang and Wang, Hessian LLE by Donoho and Grimes, LTSA by Zhang and Zha) are available in sklearn.manifold.LocallyLinearEmbedding(method=...).
Lab: LLE from scratch
The implementation follows the three steps with SciPy sparse matrices. At the end it is compared with scikit-learn’s LocallyLinearEmbedding and weight invariance is checked numerically.
import numpy as np, scipy.sparse as sp, time
from scipy.sparse.linalg import eigsh
from sklearn.neighbors import NearestNeighbors
def lle_pesos(X, k, reg=1e-3):
"""Matriz dispersa W (n x n) con los pesos de reconstrucción de cada punto sobre sus k vecinos."""
n = len(X)
ind = NearestNeighbors(n_neighbors=k + 1).fit(X).kneighbors(X, return_distance=False)[:, 1:]
W = np.empty((n, k))
for i in range(n):
Z = X[ind[i]] - X[i] # vecinos centrados en x_i (k x D)
C = Z @ Z.T # Gram local (k x k), rango <= D
tr = np.trace(C)
C[np.diag_indices(k)] += reg * tr if tr > 0 else reg
w = np.linalg.solve(C, np.ones(k)) # C w = 1 ...
W[i] = w / w.sum() # ... y se normaliza: sum_j w_j = 1
return sp.csr_matrix((W.ravel(), (np.repeat(np.arange(n), k), ind.ravel())), shape=(n, n))
def lle(X, k, d=2, reg=1e-3):
n = len(X)
A = sp.identity(n, format="csr") - lle_pesos(X, k, reg)
M = (A.T @ A).tocsc() # M = (I - W)^T (I - W), dispersa y semidefinida
vals, vecs = eigsh(M, k=d + 1, sigma=-1e-3, which="LM") # los más cercanos a -0.001: los menores
o = np.argsort(vals)
return np.sqrt(n) * vecs[:, o[1:]], vals[o]
X, t = make_swiss_roll(1000, random_state=0)
s = abscisa(t)
Y, vals = lle(X, k=12)
print("tres menores autovalores de M:", np.array2string(vals, precision=2))
Ysk = LocallyLinearEmbedding(n_neighbors=12, n_components=2, reg=1e-3, eigen_solver="arpack", random_state=0).fit_transform(X)
print("|correlación| con sklearn por coordenada:", np.round(np.abs([np.corrcoef(Y[:, c], Ysk[:, c])[0, 1] for c in range(2)]), 4))
print(f"|Spearman(y1, abscisa)| = {abs(spearmanr(Y[:, 0], s)[0]):.3f}")
# invariancia: la misma nube (300 puntos) girada, escalada y trasladada
Q, _ = np.linalg.qr(np.random.default_rng(0).standard_normal((3, 3)))
W1 = lle_pesos(X[:300], 12)
W2 = lle_pesos(2.5 * X[:300] @ Q.T + np.array([10.0, -4.0, 7.0]), 12)
print(f"máx |W(X) - W(2.5 QX + b)| = {abs(W1 - W2).max():.1e}")The implementation matches scikit-learn (correlation 1 in both coordinates; differences are in sign and scale, since scikit-learn returns unit eigenvectors rather than ), the first coordinate traverses the noiseless roll (Spearman 1.000), and the transformed cloud’s weights agree up to rounding. Now consider regularization with noiseless data and . For each reg, the cell measures the five smallest eigenvalues of and the fraction of embedding variance explained by linear regression on ambient coordinates: an of 1 means LLE returned a linear projection.
from sklearn.linear_model import LinearRegression
X5, t5 = make_swiss_roll(500, random_state=0)
ind = NearestNeighbors(n_neighbors=13).fit(X5).kneighbors(X5[[0]], return_distance=False)[0, 1:]
Z = X5[ind] - X5[0]
print("autovalores de la Gram local de x_0 (k = 12):", np.array2string(np.linalg.eigvalsh(Z @ Z.T)[::-1][:5], precision=2), "...")
for reg in [1e-9, 1e-3]:
A = sp.identity(500, format="csr") - lle_pesos(X5, 12, reg)
mu, V = np.linalg.eigh((A.T @ A).toarray())
Yr = V[:, 1:3]
r2 = LinearRegression().fit(X5, Yr).score(X5, Yr)
print(f"reg = {reg:.0e}: cinco menores autovalores de M {np.array2string(mu[:5], precision=1)}; R2 lineal = {r2:.3f}")The local Gram matrix has three nonzero and nine zero eigenvalues to machine precision: rank 3, singular. With reg , has four zero eigenvalues (the constant and the three ambient coordinates) and the embedding is exactly linear in (). With reg the null space contains only the constant vector again and the embedding ceases to be linear. A cluster of nearly degenerate eigenvalues also stalls iterative methods: with the previous cell’s 1000 points, lle(X, 12, reg=1e-9) causes eigsh not to converge.
Laplacian eigenmaps: the smoothest functions on the graph
Belkin and Niyogi (2003) retain even less information: they do not care how each point is reconstructed, only which points are close. They build a similarity graph with weights (a -neighbor or -radius graph with binary weights or the heat kernel ) and seek an embedding where connected points remain close.
The objective penalizes separating connected points, more strongly for larger weights. By the identity applied to each column, it equals . Without constraints, the minimum would be ; the constraint fixes the scale, weighting each point by its degree so highly connected vertices (dense regions) count more. With one coordinate, the Lagrangian gives and the objective at a solution is . The full derivation for coordinates, using to turn it into a Ky Fan problem for the normalized Laplacian , is an exercise.
Why discard the first eigenvector? , so (with ) satisfies and gives objective 0: it sends every point to the same place. This is the minimum but conveys no information; the constraint excludes it. If the graph has connected components, there are zero eigenvalues with component indicator eigenvectors, and the first coordinates say only which component each point occupies.
This is precisely the mathematics of spectral clustering: the Ncut relaxation gives the same generalized problem (equivalent to with ). Shi and Malik’s spectral clustering is a Laplacian eigenmap followed by k-means; the difference is purpose, not computation: there one seeks clusters and expects coordinates to be nearly constant per cluster; here one seeks a continuous parametrization of a manifold. The same eigenvectors, viewed as a basis of functions on the graph, form the graph Fourier transform underlying spectral convolutions in the graphs module.
The continuous limit: the Laplace–Beltrami operator
Why does this flatten manifolds? Consider a function on manifold . If two points are close, , so a function mapping nearby points to nearby values on average over the manifold has small Dirichlet energy, . By Green’s formula, , with the Laplace–Beltrami operator (positive semidefinite with this sign convention). The minimum-energy functions with unit norm and orthogonal to constants are its eigenfunctions with smallest eigenvalues. Belkin and Niyogi justify the algorithm as follows: the graph Laplacian with a heat kernel approximates when and at the appropriate rate, and graph eigenvectors approximate its eigenfunctions (convergence was subsequently proved by, among others, Belkin and Niyogi and Hein, Audibert and von Luxburg). On a manifold with boundary, the limit has Neumann conditions: zero normal derivative at the boundary.
This lets us predict what eigenmaps compute on a simple manifold. On a flat rectangle , the Neumann eigenfunctions are products of cosines:
The first nontrivial one is if : it traverses the long side, as desired. But the second is as soon as , because . And is a function of the first: the embedding is a parabola, a horseshoe, and height only appears at mode , which can come much later. The Swiss roll is about 89 units long and 21 high, a ratio of 4.26: modes , , and () precede height.
This is not an implementation defect: it is what the method promises. The coordinates are the smoothest eigenfunctions, and on an elongated manifold the smoothest are harmonics of its long side. The practical consequence is that the useful coordinate is not always the second: inspect several and choose those that are not functions of earlier ones (Dsilva and coauthors proposed an automatic criterion for “nonharmonic” diffusion-map eigenfunctions in 2018).
Lab: eigenmaps from scratch
from sklearn.neighbors import kneighbors_graph
def mapas_propios(X, k, d=2):
"""Grafo de k vecinos simetrizado, W = (A + A^T)/2, y problema generalizado L y = lambda D y."""
A = kneighbors_graph(X, k, mode="connectivity", include_self=True) # como sklearn: el punto cuenta como vecino
W = 0.5 * (A + A.T)
W.setdiag(0); W.eliminate_zeros() # ... y el lazo se descarta
deg = np.asarray(W.sum(axis=1)).ravel()
D = sp.diags(deg).tocsc()
L = (D - W).tocsc()
vals, vecs = eigsh(L, k=d + 1, M=D, sigma=-1e-3, which="LM") # y^T D y = 1 en la salida
o = np.argsort(vals)
return vecs[:, o[1:]], vals[o]
Y, vals = mapas_propios(X, k=10, d=5)
Ysk = SpectralEmbedding(n_components=5, n_neighbors=10, random_state=0).fit_transform(X)
dif = max(min(np.abs(Y[:, c] - Ysk[:, c]).max(), np.abs(Y[:, c] + Ysk[:, c]).max()) for c in range(5))
print("autovalores:", np.array2string(vals, precision=5))
print(f"máx diferencia con SpectralEmbedding (salvo signo): {dif:.1e}")
L_largo = abscisa(4.5 * np.pi) - abscisa(1.5 * np.pi)
print(f"largo del rollo {L_largo:.1f}, alto 21, proporción {L_largo / 21:.2f}")
h = X[:, 1]
for c in range(5):
r = [abs(np.corrcoef(Y[:, c], np.cos(np.pi * m * (s - s.min()) / L_largo))[0, 1]) for m in range(1, 6)]
ra = abs(np.corrcoef(Y[:, c], np.cos(np.pi * h / 21))[0, 1])
print(f"y{c + 1}: mejor cos(pi m s / L) con m = {np.argmax(r) + 1} (|r| = {max(r):.2f}); |r| con cos(pi h / H) = {ra:.2f}")The implementation matches SpectralEmbedding up to rounding (). This requires copying a scikit-learn detail: it counts the point itself as one of the neighbors and then discards the self-loop, so it actually uses neighbors. The eigenvalues , and increase almost as , the harmonics’ law, and the table confirms the strip prediction: , and are with (correlations 1.00, 0.95 and 0.89), and none sees height. Height appears in (0.72), and the fourth length harmonic in (0.73). Uniform-sampling theory would put mode before , but their theoretical eigenvalues differ by only 12% (); with 1000 points, a neighbor graph, and uniform sampling in (not arc length), the order of two such close eigenvalues is unreliable. What matters is robust: the first two coordinates form a horseshoe and do not contain height.
Review: random walks on a graph
Diffusion maps interpret the same graph as a Markov chain. From vertex , the walker jumps to with probability :
The stationary distribution is proportional to degree, and the chain is reversible: . Reversibility makes , which is not symmetric, similar to a symmetric matrix:
Thus has real eigenvalues (the same as , and : large eigenvalues of are small ones of the Laplacian). Normalize the eigenvectors as follows:
With this choice, , , the are orthonormal under the weighted inner product , and the chain’s th power has spectral decomposition
The term is , the equilibrium; the rest are deviations from equilibrium that decay as . If the graph is connected and non-bipartite, for and the chain converges to at a rate set by .
Diffusion maps: distances measured by a random walk
Coifman and Lafon (2006) propose measuring the distance between two points by how different the futures of walks starting from each are. If walkers starting from and tend to reach the same places in steps, the points are well connected by many paths, even if none is short; if one can reach the other only through a bottleneck, their futures differ.
For the Gaussian kernel, the kernel matrix is positive semidefinite (it is the Gram matrix of a Mercer kernel), as are and : all lie in and is meaningful for any , not just integer time.
Diffusion distance
Proof
By spectral decomposition, , and the term vanishes because . Let . Then
using and orthonormality of the in .
∎The theorem is the heart of the method: a distance defined by all paths of length between two points (rows of sum all their probabilities) is a Euclidean distance in diffusion-map coordinates. And because the decay, a few coordinates suffice. Truncating at , the error in is , because basis completeness gives . Following Coifman and Lafon, the diffusion dimension at precision is the number of surviving coordinates:
Time as a scale
is not a detail: it determines which structure the distance sees. For small , many remain near 1 and the distance distinguishes fine details; as grows, only eigenvalues closest to 1 survive, corresponding to structures from which the walk escapes most slowly: large clusters. It is a zooming-out lens.
The figure tells the story in numbers: the ratio of average distances between two subgroups of the same group to distances between two different groups falls with , and diffusion dimension goes from 8 (the subgroup contrasts) to 2 (the group contrasts), then to 1. This is the same logic as the eigengap in spectral clustering, but without choosing a number of groups: each timescale gives its own geometry.
Another advantage of summing over paths is robustness to shortcuts. A geodesic distance uses the single shortest path, so a bridge of a few points between two layers changes it completely; diffusion distance weights all paths by their probabilities, and a narrow bridge carries very little probability. You will measure this in the lab.
α normalization: separating geometry and density
Graph methods mix two things: the shape of the manifold and how densely it is sampled. A walker in a dense area has more neighbors toward the dense side and drifts that way. Coifman and Lafon calculate the limiting chain generator as and for data with density on a compact manifold: tends, up to a positive constant factor, to the operator
where the second form follows from expanding with . Watch the sign: in this formula, is the analytic Laplacian, negative semidefinite, the opposite of the one used for eigenmaps; with it, is the generator of a diffusion with drift . The three classical values:
- : the usual normalized-Laplacian walk, with drift of strength 2 toward dense regions. Eigenfunctions mix geometry and density: useful for clustering.
- : drift of strength 1, the Fokker–Planck operator of a Langevin diffusion whose equilibrium distribution is the data density itself.
- : no drift. is the Laplace–Beltrami operator: eigenfunctions depend only on geometry, regardless of sampling density.
For a parametrization of the manifold (a coordinate measuring position, not density), use . For clustering, density is useful information and exploits it.
Test yourself before the lab
diffusion_map(X, eps, alpha, t, d) using the kernel , normalization and time , returning an array (n, d) of coordinates , , with normalized in (that is, ). Diagonalize a symmetric matrix similar to with np.linalg.eigh, not with eig. Tests compare with a reference implementation up to each column’s sign.import numpy as np
from scipy.spatial.distance import cdist
def diffusion_map(X, eps, alpha=1.0, t=1, d=2):
"""Coordenadas de difusión lambda_l^t psi_l, l = 1..d, de forma (n, d)."""
K = np.exp(-cdist(X, X, "sqeuclidean") / eps)
# tu código: densidad q, núcleo normalizado con alpha, grados, matriz simétrica S,
# autovectores de S de mayor a menor, psi_l = v_l / v_0 y escala lambda_l^t
return np.zeros((len(X), d))Lab: diffusion maps from scratch
The first cell implements the method, checks the review’s properties (rows sum to 1, stationary, orthonormality in ), and verifies the diffusion distance theorem by comparing the definition with the spectral formula.
from scipy.spatial.distance import cdist
def diffusion_map(X, eps, alpha=1.0, t=1, d=2, devolver_todo=False):
"""Coordenadas de difusión (lambda_l^t psi_l, l = 1..d) con núcleo gaussiano exp(-|x - y|^2 / eps)."""
K = np.exp(-cdist(X, X, "sqeuclidean") / eps)
q = K.sum(axis=1) # estimación de densidad (sin normalizar)
Ka = K / np.outer(q**alpha, q**alpha) # normalización alfa
dd = Ka.sum(axis=1) # grados del nuevo núcleo
S = Ka / np.sqrt(np.outer(dd, dd)) # simétrica y semejante a P = D^-1 Ka
lam, V = np.linalg.eigh(S)
lam, V = lam[::-1], V[:, ::-1] # de mayor a menor; lam[0] = 1
psi = V / V[:, [0]] # autovectores derechos de P con psi_0 = 1
Y = lam[1:d + 1]**t * psi[:, 1:d + 1]
if devolver_todo:
return Y, lam, psi, Ka / dd[:, None], dd / dd.sum()
return Y
X, t = make_swiss_roll(500, random_state=0)
Y, lam, psi, P, pi = diffusion_map(X, eps=4.0, d=2, devolver_todo=True)
print(f"filas de P suman 1: {np.allclose(P.sum(1), 1)}; pi P = pi: {np.allclose(pi @ P, pi)}")
G = psi.T @ (pi[:, None] * psi) # <psi_l, psi_m>_pi
print(f"psi ortonormales en L2(pi): máx |G - I| = {np.abs(G - np.eye(len(G))).max():.1e}")
print("lambda_0..5:", np.round(lam[:6], 4), f" tiempo de relajación 1/(1 - lambda_1) = {1 / (1 - lam[1]):.0f}")
tt = 3
Pt = np.linalg.matrix_power(P, tt)
i, j = 0, 1
D_def = np.sqrt(np.sum((Pt[i] - Pt[j])**2 / pi))
D_esp = np.sqrt(np.sum(lam[1:]**(2 * tt) * (psi[i, 1:] - psi[j, 1:])**2))
print(f"D_3(x0, x1): definición {D_def:.6f}, espectral {D_esp:.6f}")Everything agrees: rows of sum to 1, is stationary, the are orthonormal in to , and diffusion distance at between the first two points is 9.277819 both by definition (summing over 500 destinations of ) and by the spectral formula. Notice the eigenvalues: 0.9993, 0.9975, 0.9936 and subsequent ones are very close to 1. With , the kernel barely connects points more than 3 or 4 units apart (), and such a walk needs on the order of steps to traverse a roll 89 units long: in this sample large times are needed for diffusion to forget its starting point.
rng = np.random.default_rng(0)
x = np.sort(rng.beta(1, 3, 400)) # densidad 3(1 - x)^2 en [0, 1]: muy desigual
P1 = np.c_[x, np.zeros_like(x)]
ref = np.cos(np.pi * (x - x.min()) / (x.max() - x.min()))
for a in [0.0, 0.5, 1.0]:
y1 = diffusion_map(P1, eps=0.002, alpha=a, d=1)[:, 0]
print(f"alpha = {a}: |corr(psi_1, cos(pi x))| = {abs(np.corrcoef(y1, ref)[0, 1]):.3f}")The density is : three times uniform at and nearly zero near . With , the first coordinate resembles the Laplace–Beltrami eigenfunction, , with correlation 0.898; with , 0.968; with , 0.999. This is what the limiting operator predicts: drift disappears at .
from scipy.sparse.csgraph import shortest_path
X, t = make_swiss_roll(400, random_state=0)
s = abscisa(t)
lejos = np.abs(s[:, None] - s[None, :]) > 30 # pares de capas distintas del rollo
Dx = cdist(X, X)
a, b = np.unravel_index(np.argmin(np.where(lejos, Dx, np.inf)), Dx.shape)
puente = X[a] + np.outer([0.25, 0.5, 0.75], X[b] - X[a]) # tres puntos en el segmento entre capas
print(f"capas a distancia euclídea {Dx[a, b]:.2f} y {abs(s[a] - s[b]):.1f} a lo largo del rollo")
def geodesica(Z):
A = kneighbors_graph(Z, 10, mode="distance")
return shortest_path(A.maximum(A.T), directed=False)
def difusion(Z):
Y = diffusion_map(Z, eps=4.0, t=20, d=len(Z) - 1)
return cdist(Y, Y)
n = len(X)
iu = np.triu_indices(n, 1)
for nombre, f in [("geodésica", geodesica), ("difusión t = 20", difusion)]:
D0 = f(X)[iu]
D1 = f(np.vstack([X, puente]))[:n, :n][iu]
cambio = np.abs(D1 - D0) / D0
print(f"{nombre:16s}: pares que cambian más de un 20 %: {np.mean(cambio > 0.2):.2%}; cambio mediano {np.median(cambio):.2%}")Three points (less than 1% of the sample) between two layers 6.23 apart in a straight line but 49.2 along the roll change geodesic distance by more than 20% for 7.48% of pairs: those now taking the bridge shortcut. Most do not use it, so the median change is zero. Diffusion distance at changes that much for only 0.22% of pairs, with a median change of 0.22%. A shortest path uses the entire bridge as soon as it is shorter; a random walk crosses it with low probability, because the bridge contributes very few edges compared with all those within each layer.
Unified view: kernel PCA with data-built kernels
Ham, Lee, Mika and Schölkopf (2004) observed that Isomap, LLE and Laplacian eigenmaps can be written as the same algorithm. Kernel PCA takes a positive semidefinite kernel matrix , centers it ( with ), and uses its eigenvectors with largest eigenvalues as coordinates, scaled by the eigenvalue’s square root. Isomap already did this with , the double-centered squared geodesics. This lesson’s methods use eigenvectors with smallest eigenvalues of a positive semidefinite matrix that annihilates the constant vector; simply reverse the spectrum’s order.
Proof
Both kernels have the same eigenvectors as , with eigenvalues and (and for in ): they are positive semidefinite. Since is an eigenvector, acts as the identity on and annihilates , so the centered kernel retains eigenvectors and their eigenvalues, and sends that of to 0. Functions and decrease on : the largest eigenvalues of the centered kernel correspond to , the smallest nonzero ones of .
∎The unified-view table is:
| Method | Kernel on the sample | What it preserves |
|---|---|---|
| Isomap | (squared geodesics) | global geodesic distances |
| LLE | local linear reconstructions | |
| Eigenmaps | (or in variables ) | graph proximity |
| Diffusion maps (after Ham and coauthors) | , with PCA weighted by | connectivity through paths of length |
Two rows have a nice probabilistic interpretation. is the commute-time kernel: the expected number of steps for a walk to go from to and back is , so eigenmaps with kernel are MDS of commute distance (a classical result relating random walks and electrical networks: commute time is times effective resistance between and ). For diffusion maps, reversibility makes symmetric, and the diffusion-distance theorem’s proof states exactly that : diffusion distance is the distance induced by kernel .
There is an important nuance. These kernels are defined only on the sample: LLE’s , the neighbor graph, and geodesics depend on all points, and there is no formula evaluable at a new . Thus local spectral methods, as published, lack transform. The unified view makes it possible to add one.
Embedding new points: the Nyström extension
Refitting for each new point costs an eigendecomposition. Bengio, Paiement, Vincent, Delalleau, Le Roux and Ouimet (2004) apply the idea of the Nyström approximation, already used to scale spectral clustering, to all these methods: if eigenvectors come from a matrix of the form with a function evaluable at any point, the eigenvalue equation itself tells us how to extend them.
Bengio and coauthors construct a suitable function for each method. For this lesson’s methods the formulas are natural:
- Diffusion maps. The equation is and a new point’s transition row is computed like training rows: with , normalized to sum to 1 (the factor cancels). Then
- Laplacian eigenmaps. is equivalent to , so , with the transition row given by the new point’s weights to its neighbors.
- LLE. With the kernel constructed by Bengio and coauthors, the formula reduces to computing reconstruction weights for over its training neighbors and applying them to their images: . This is the rule already proposed by Saul and Roweis (2003) and used by
LocallyLinearEmbedding.transform.
In all three cases extending a new point costs (distances to the sample) instead of an eigendecomposition, and is a combination of the images of nearby training points: convex in diffusion maps and eigenmaps (multiplied by or , factors greater than 1), affine in LLE. This has an important consequence: Nyström does not extrapolate. Far from the data, the transition row concentrates on the nearest point, and the new point falls practically on its image (divided by ).
Lab: Nyström versus refitting
The cell defines a DiffusionMap with fit and transform, checks that transform reproduces training, compares the extension of 20 new points with refitting that includes them (after Procrustes alignment, since eigenvectors are defined only up to sign), and does the same with scikit-learn’s LLE. To evaluate, it uses the preceding lesson’s trustworthiness on all 220 points.
import time
from scipy.linalg import orthogonal_procrustes
from sklearn.manifold import trustworthiness
def sector(n, seed):
g = np.random.default_rng(seed)
r, th = np.sqrt(g.uniform(1, 9, n)), g.uniform(0, np.pi / 2, n)
return np.c_[r * np.cos(th), r * np.sin(th)]
class DiffusionMap:
def __init__(self, eps, alpha=1.0, t=1, d=2):
self.eps, self.alpha, self.t, self.d = eps, alpha, t, d
def fit(self, X):
self.X = X
K = np.exp(-cdist(X, X, "sqeuclidean") / self.eps)
self.q = K.sum(1)
Ka = K / np.outer(self.q**self.alpha, self.q**self.alpha)
dd = Ka.sum(1)
lam, V = np.linalg.eigh(Ka / np.sqrt(np.outer(dd, dd)))
lam, V = lam[::-1], V[:, ::-1]
self.lam, self.psi = lam[1:self.d + 1], (V / V[:, [0]])[:, 1:self.d + 1]
self.embedding_ = self.lam**self.t * self.psi
return self
def transform(self, Z):
"""Nyström: lambda^t psi(z) = lambda^(t-1) sum_j p(z, x_j) psi(x_j)."""
K = np.exp(-cdist(Z, self.X, "sqeuclidean") / self.eps)
Ka = K / self.q**self.alpha # q(z)^alpha se cancela al normalizar la fila
Pz = Ka / Ka.sum(1, keepdims=True)
return self.lam**(self.t - 1) * (Pz @ self.psi)
def comparar(Y, Ynew, Yrefit, n=200):
R, _ = orthogonal_procrustes(Yrefit[:n], Y) # alinea signos y giros
Yr = Yrefit @ R
diam = np.ptp(Y, axis=0).max()
err = np.linalg.norm(Ynew - Yr[n:], axis=1).mean() / diam
mov = np.linalg.norm(Yr[:n] - Y, axis=1).mean() / diam
return err, mov
Xtr, Xnew = sector(200, 0), sector(20, 1)
Xall = np.vstack([Xtr, Xnew])
dm = DiffusionMap(eps=0.3).fit(Xtr)
print(f"coherencia en el entrenamiento: máx |Nyström(X) - Y| = {np.abs(dm.transform(Xtr) - dm.embedding_).max():.1e}")
t0 = time.perf_counter(); Ynys = dm.transform(Xnew); t_nys = time.perf_counter() - t0
t0 = time.perf_counter(); dm2 = DiffusionMap(eps=0.3).fit(Xall); t_fit = time.perf_counter() - t0
err, mov = comparar(dm.embedding_, Ynys, dm2.embedding_)
print(f"diffusion maps: Nyström frente a reajuste {err:.2%} del diámetro; el entrenamiento se mueve {mov:.2%}")
print(f"reajustar tarda {t_fit / t_nys:.0f} veces más que extender los 20 puntos")
lle1 = LocallyLinearEmbedding(n_neighbors=10, n_components=2, eigen_solver="dense").fit(Xtr)
lle2 = LocallyLinearEmbedding(n_neighbors=10, n_components=2, eigen_solver="dense").fit(Xall)
err, mov = comparar(lle1.embedding_, lle1.transform(Xnew), lle2.embedding_)
print(f"LLE: Nyström (pesos) frente a reajuste {err:.2%} del diámetro; el entrenamiento se mueve {mov:.2%}")
T_ext = trustworthiness(Xall, np.vstack([dm.embedding_, Ynys]), n_neighbors=10)
T_fit = trustworthiness(Xall, dm2.embedding_, n_neighbors=10)
print(f"T(10) de los 220 puntos: extensión {T_ext:.4f}, reajuste {T_fit:.4f}")
lejano = np.array([[-3.0, 0.0]])
j = np.argmin(cdist(lejano, Xtr))
print(f"punto lejano: Nyström {np.round(dm.transform(lejano)[0], 3)}; imagen del dato más cercano / lambda {np.round(dm.embedding_[j] / dm.lam, 3)}")The extension reproduces training to , as required by the formula. For 20 new points, Nyström positions differ from refitting by 1.56% of embedding diameter, while refitting moves the 200 training points themselves by 1.63%: the extension departs from refitting as much as refitting departs from the original fit. LLE behaves similarly (1.55% versus 1.59%). Trustworthiness for the 220 points is 0.9911 with extension and 0.9923 with refitting. Refitting costs roughly a hundred times more than extension (the exact ratio varies between runs and machines, and grows with , because refitting is cubic in and extension linear). Finally, the distant point lands at , almost on its nearest training point’s image divided by , : Nyström does not extrapolate.
Comparison and selection criteria
The figures and labs provide enough material to compare. The benchmark below pits five methods against five datasets using the same -neighbor graph and measures trustworthiness and continuity : penalizes false neighbors in the embedding (points brought together that were not neighbors) and penalizes lost neighbors.
Given what you have seen, these differences matter:
| Isomap | LLE | Eigenmaps | Diffusion maps | |
|---|---|---|---|---|
| Information used | all-pairs geodesics | local reconstructions | graph edges | paths of length |
| Matrix | dense | sparse () | sparse () | dense with Gaussian kernel (sparse if truncated) |
| Eigenvectors | largest | smallest nontrivial | smallest nontrivial | largest nontrivial |
| Coordinate scale | metric (distances) | forced variance 1 | forced | : reflects time scale |
| Parameters | , reg | or , weights | , , | |
| New points | Nyström (MDS formula) | reconstruction weights | Nyström | Nyström |
| Fails with | shortcuts, poorly estimated geodesics | noise, poor reg, proportions | disconnected graphs, harmonics | poor , harmonics |
As selection criteria:
- If the manifold is well sampled, has no shortcuts, and distances matter (for example, to interpret scale), use Isomap. If it is noisy or the graph may have shortcuts, use a local method.
- For a parametrization of the manifold, use diffusion maps with and inspect more than two coordinates: discard those that are functions of earlier ones (harmonics).
- For clustering, use eigenmaps or diffusion maps with , followed by k-means: this is spectral clustering.
- For structure at multiple scales, use diffusion maps at several values of .
- For continuous embedding of new data, use any method with Nyström while new points resemble the sample; if the distribution changes, refit or switch to a parametric embedding.
- If you only want to see clusters in two dimensions, none is the best choice: t-SNE and UMAP, in the next two lessons, directly optimize neighborhood preservation.
Always measure and , but remember what they measure: neighborhoods. In the benchmark, the Laplacian-eigenmap and diffusion-map horseshoe on the Swiss roll has not far from Isomap’s, even though one of its coordinates is a function of the other and height has vanished: when flattening an elongated strip, most neighbors of each point remain neighbors along its length. and do not detect harmonics; inspect coordinates or test whether each can be predicted from earlier ones, as Dsilva and coauthors propose.
Common mistakes
Exercises
Step 1 of 5. What role does the constraint play in the residual's form?
Step 1 of 4. What is for a vector ?
More than one answer may be correct.
Summary
- LLE computes sum-to-one reconstruction weights, invariant to neighborhood rotations, scales and translations, and seeks coordinates with the same reconstructions: eigenvectors with the smallest nontrivial eigenvalues of . With greater than the dimension, regularize.
- Laplacian eigenmaps minimize subject to : the generalized problem , the same as spectral clustering. The constant eigenvector is the trivial solution and is discarded. In the limit these are Laplace–Beltrami eigenfunctions, producing harmonics on elongated manifolds.
- Diffusion maps use random-walk eigenvectors scaled by : Euclidean distance between their coordinates is diffusion distance, summing over all paths and robust to shortcuts. sets the scale and removes the effect of density.
- Unified view: with , smallest eigenvectors of are largest eigenvectors of or ; Isomap, LLE, eigenmaps and diffusion maps are kernel PCA with kernels defined on the sample.
- Nyström extends eigenvectors to new points using the eigenvalue equation, exactly reproduces training, and in the lab differs from refitting as much as refitting moves the sample itself. It does not extrapolate.