Module contents
Lesson 16 of 24Advanced 100 min

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.

[ ]Two shortcuts are enough to break IsomapBrowser
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 tt 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 dd-dimensional manifold, each point and its nearby neighbors lie approximately on a dd-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 Rd\R^d, 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 ii solves its own problem with kk unknowns. Fix ii, denote its weights on neighbors xj1,…,xjk\vb{x}_{j_1}, \dots, \vb{x}_{j_k} by w∈Rk\vb{w} \in \R^k, and let ηa=xi−xja\vb{\eta}_a = \vb{x}_i - \vb{x}_{j_a}. Since ∑awa=1\sum_a w_a = 1,

xi−∑awaxja=∑awa(xi−xja)=∑awaηa,∥∑awaηa∥2=w⊤Cw,Cab=ηa⊤ηb.\vb{x}_i - \sum_a w_a\vb{x}_{j_a} = \sum_a w_a(\vb{x}_i - \vb{x}_{j_a}) = \sum_a w_a\vb{\eta}_a, \qquad \Big\|\sum_a w_a\vb{\eta}_a\Big\|^2 = \vb{w}\T\mat{C}\vb{w},\quad C_{ab} = \vb{\eta}_a\T\vb{\eta}_b .

C∈Rk×k\mat{C} \in \R^{k\times k} 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 xi−xj\vb{x}_i - \vb{x}_j.

Proof

A positive semidefinite, invertible C\mat{C} is positive definite, so the objective is strictly convex and the constraint affine: there is one minimum, characterized by the Lagrange conditions. With L=w⊤Cw−2μ(1⊤w−1)\mathcal{L} = \vb{w}\T\mat{C}\vb{w} - 2\mu(\vb{1}\T\vb{w} - 1), the gradient vanishes if Cw=μ1\mat{C}\vb{w} = \mu\vb{1}, that is, w=μC−11\vb{w} = \mu\mat{C}\inv\vb{1}, and the constraint fixes μ=1/(1⊤C−11)\mu = 1/(\vb{1}\T\mat{C}\inv\vb{1}). The error is μ2 1⊤C−1CC−11=μ2 1⊤C−11=μ\mu^2\,\vb{1}\T\mat{C}\inv\mat{C}\mat{C}\inv\vb{1} = \mu^2\,\vb{1}\T\mat{C}\inv\vb{1} = \mu.

∎

In practice nothing is inverted: solve Cw=1\mat{C}\vb{w} = \vb{1} and divide w\vb{w} by the sum of its components. Weights can be negative: if xi\vb{x}_i 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 ηa\vb{\eta}_a only thanks to ∑awa=1\sum_a w_a = 1, and that C\mat{C} is multiplied by s2s^2, which cancels in the quotient for w⋆\vb{w}^\star. Check it with the figure: transform the cloud, compare weights before and after, and remove the constraint.

InteractiveLLE weights do not see rotations
Transformed cloud s Rθx+bs\,\mat{R}_\theta\vb{x} + \vb{b} (points) and original (gray)
1: 0.3832: 0.2303: 0.0944: 0.293
  • reconstructed point xi\vb{x}_i
  • neighbors (thickness: ∣wj∣|w_j|)
  • negative weight
  • reconstruction ∑jwjxj\sum_j w_j\vb{x}_j
Neighbors kk
40°
1.30
0.80
0.40
−3.0
vecinow antesw después
10.3830.383
20.2300.230
30.0940.094
40.2930.293
Largest weight change≈ 0
∑jwj\sum_j w_j1.0000
Error εi\varepsilon_i after transformation0.0000
Rank of CC (unregularized)2 of 4
With k = 4 > D + 1 = 3, infinitely many exact combinations exist: C has rank 2 of 4 and regularization chooses one. Increase r to see weights approach 1/k and error grow.
A cloud of 14 points; the orange point is reconstructed using its kk nearest neighbors (blue, with thickness proportional to ∣wj∣|w_j| and dashed red for negative weights). The magenta cross is the reconstruction ∑jwjxj\sum_j w_j\vb{x}_j. The sliders apply x↦sRθx+b\vb{x} \mapsto s\mat{R}_\theta\vb{x} + \vb{b} to the whole cloud (the original is gray) and the table compares weights computed from scratch before and after. In the initial state (k=4k = 4, rotation 40°, scale 1.3 and translation), they agree up to rounding. Disable the constraint ∑jwj=1\sum_j w_j = 1: with translation the weights change; without it, they do not. Also try k=2k = 2 (projection onto a line), k=3k = 3 (barycentric coordinates, zero error), and increase regularization with k=5k = 5. Click another point to reconstruct it or drag any point.

The figure reveals two nuances. First, invariance applies to similarities (rotation, uniform scaling, translation), not every affine map: a general linear map A\mat{A} changes C\mat{C} to a matrix with entries ηa⊤A⊤Aηb\vb{\eta}_a\T\mat{A}\T\mat{A}\vb{\eta}_b, which is generally not proportional to C\mat{C}. The exception is an exact and unique reconstruction (k=D+1k = D + 1 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 min⁡∥x−Nw∥\min\norm{\vb{x} - \mat{N}\vb{w}} with N=[xj1⋯xjk]\mat{N} = [\vb{x}_{j_1} \cdots \vb{x}_{j_k}] is invariant under x↦sQx\vb{x} \mapsto s\mat{Q}\vb{x}), but translation does change them, because the residual becomes sQ(xi−∑awaxja)+(1−∑awa)bs\mat{Q}(\vb{x}_i - \sum_a w_a\vb{x}_{j_a}) + (1 - \sum_a w_a)\vb{b}.

When kk exceeds the dimension: regularize

C=Nη⊤Nη\mat{C} = \mat{N}_\eta\T\mat{N}_\eta with Nη=[η1⋯ηk]∈RD×k\mat{N}_\eta = [\vb{\eta}_1 \cdots \vb{\eta}_k] \in \R^{D\times k}, so rank⁡C≤min⁡(D,k)\rank\mat{C} \le \min(D, k). With k>Dk > D, C\mat{C} is singular and the theorem does not apply. Distinguish two cases:

  • With k=D+1k = D + 1 neighbors in general position, C\mat{C} is singular but the sum-to-one solution is unique: the barycentric coordinates of xi\vb{x}_i, with zero error.
  • With k>D+1k > D + 1, exact combinations form an affine subspace of dimension k−D−1k - D - 1: infinitely many solutions exist.

The second case matters in practice, and not only when k>Dk > D: if data lie in R784\R^{784} 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 kk exceeds the intrinsic dimension. The standard solution, already in Saul and Roweis (2003), is trace-proportional Tikhonov regularization:

C  ←  C+r Ik,r=reg⋅tr⁡C,reg≈10−3,\mat{C} \;\leftarrow\; \mat{C} + r\,\mat{I}_k, \qquad r = \texttt{reg}\cdot\tr\mat{C}, \qquad \texttt{reg} \approx 10^{-3},

which is what scikit-learn uses. It is equivalent to minimizing w⊤Cw+r∥w∥2\vb{w}\T\mat{C}\vb{w} + r\norm{\vb{w}}^2: among nearly exact reconstructions it favors spread-out weights, and as r→∞r \to \infty weights approach 1/k1/k. Making rr proportional to the trace preserves scale invariance.

What happens without sufficient regularization on noiseless data is surprising. In a Swiss roll in R3\R^3, a point’s 12 neighbors are not coplanar (the surface curves), their affine hull is all of R3\R^3, and an exact reconstruction always exists. Then (I−W)X=0(\mat{I} - \mat{W})\mat{X} = \mat{0}: each ambient coordinate xx, yy, zz has Φ=0\Phi = 0 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 W\mat{W} fixed, yi−∑jWijyj\vb{y}_i - \sum_j W_{ij}\vb{y}_j is row ii of (I−W)Y(\mat{I} - \mat{W})\mat{Y}, so

Φ(Y)=∥(I−W)Y∥F2=tr⁡(Y⊤MY),M=(I−W)⊤(I−W)⪰0.\Phi(\mat{Y}) = \norm{(\mat{I} - \mat{W})\mat{Y}}_F^2 = \tr\big(\mat{Y}\T\mat{M}\mat{Y}\big), \qquad \mat{M} = (\mat{I} - \mat{W})\T(\mat{I} - \mat{W}) \succeq 0 .

Since every row of W\mat{W} sums to one, (I−W)1=0(\mat{I} - \mat{W})\vb{1} = \vb{0} and M1=0\mat{M}\vb{1} = \vb{0}: the constant vector is an eigenvector with eigenvalue 0. The constraints remove the two trivial freedoms of Φ\Phi: ∑iyi=0\sum_i\vb{y}_i = \vb{0} fixes translation (which does not change Φ\Phi), and 1nY⊤Y=I\frac1n\mat{Y}\T\mat{Y} = \mat{I} prevents the solution Y=0\mat{Y} = \mat{0} and fixes the scale.

Proof

Since M\mat{M} is symmetric and 1\vb{1} is an eigenvector, the orthogonal complement 1⊥\vb{1}^\perp is invariant under M\mat{M} and has the orthonormal eigenvector basis v2,…,vn\vb{v}_2, \dots, \vb{v}_n. With U=Y/n\mat{U} = \mat{Y}/\sqrt n, the problem is to minimize ntr⁡(U⊤MU)n\tr(\mat{U}\T\mat{M}\mat{U}) over matrices with orthonormal columns in 1⊥\vb{1}^\perp. By the Ky Fan principle (the sum version of the Courant–Fischer theorem) applied to the restriction of M\mat{M} to 1⊥\vb{1}^\perp, the minimum is the sum of its dd smallest eigenvalues, μ2+⋯+μd+1\mu_2 + \cdots + \mu_{d+1}, attained by any orthonormal basis for the subspace spanned by their eigenvectors, which is unique if μd+1<μd+2\mu_{d+1} < \mu_{d+2}.

∎

Thus LLE reduces to computing the d+1d + 1 eigenvectors with the smallest eigenvalues of a sparse n×nn \times n matrix (each row of W\mat{W} has kk nonzero entries, and M\mat{M} has on the order of nk2nk^2) and discarding the constant one. For small eigenvalues of a sparse matrix, the efficient method is shift-invert Lanczos: eigsh(M, sigma=σ) factorizes M−σI\mat{M} - \sigma\mat{I} once and seeks dominant eigenvalues of (M−σI)−1(\mat{M} - \sigma\mat{I})\inv, which correspond to eigenvalues of M\mat{M} nearest σ\sigma. With slightly negative σ\sigma, M−σI\mat{M} - \sigma\mat{I} is positive definite (there is no need to factorize a singular matrix) and the nearest eigenvalues are the smallest.

The constraint 1nY⊤Y=I\frac1n\mat{Y}\T\mat{Y} = \mat{I} 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 4×14 \times 1 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.

[ ]LLE from scratch versus scikit-learnBrowser
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 n v\sqrt n\,\vb{v}), 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 k=12>D=3k = 12 > D = 3. For each reg, the cell measures the five smallest eigenvalues of M\mat{M} and the fraction of embedding variance explained by linear regression on ambient coordinates: an R2R^2 of 1 means LLE returned a linear projection.

[ ]Without regularization, LLE returns a linear projectionBrowser
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 =10−9= 10^{-9}, M\mat{M} has four zero eigenvalues (the constant and the three ambient coordinates) and the embedding is exactly linear in x\vb{x} (R2=1.000R^2 = 1.000). With reg =10−3= 10^{-3} 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 wij=wji≥0w_{ij} = w_{ji} \ge 0 (a kk-neighbor or ε\varepsilon-radius graph with binary weights or the heat kernel wij=e−∥xi−xj∥2/τw_{ij} = e^{-\norm{\vb{x}_i - \vb{x}_j}^2/\tau}) and seek an embedding where connected points remain close.

The objective penalizes separating connected points, more strongly for larger weights. By the identity ∑i,jwij(fi−fj)2=2f⊤Lf\sum_{i,j}w_{ij}(f_i - f_j)^2 = 2\vb{f}\T\mat{L}\vb{f} applied to each column, it equals tr⁡(Y⊤LY)\tr(\mat{Y}\T\mat{L}\mat{Y}). Without constraints, the minimum would be Y=0\mat{Y} = \mat{0}; the constraint Y⊤DY=I\mat{Y}\T\mat{D}\mat{Y} = \mat{I} fixes the scale, weighting each point by its degree so highly connected vertices (dense regions) count more. With one coordinate, the Lagrangian y⊤Ly−λ(y⊤Dy−1)\vb{y}\T\mat{L}\vb{y} - \lambda(\vb{y}\T\mat{D}\vb{y} - 1) gives Ly=λDy\mat{L}\vb{y} = \lambda\mat{D}\vb{y} and the objective at a solution is y⊤Ly=λ\vb{y}\T\mat{L}\vb{y} = \lambda. The full derivation for dd coordinates, using U=D1/2Y\mat{U} = \mat{D}^{1/2}\mat{Y} to turn it into a Ky Fan problem for the normalized Laplacian Lsym=D−1/2LD−1/2\mat{L}_{\mathrm{sym}} = \mat{D}^{-1/2}\mat{L}\mat{D}^{-1/2}, is an exercise.

Why discard the first eigenvector? L1=0\mat{L}\vb{1} = \vb{0}, so y=1/vol⁡V\vb{y} = \vb{1}/\sqrt{\operatorname{vol}V} (with vol⁡V=∑idi\operatorname{vol}V = \sum_i d_i) satisfies y⊤Dy=1\vb{y}\T\mat{D}\vb{y} = 1 and gives objective 0: it sends every point to the same place. This is the minimum but conveys no information; the constraint Y⊤D1=0\mat{Y}\T\mat{D}\vb{1} = \vb{0} excludes it. If the graph has cc connected components, there are cc 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 Lrwy=λy\mat{L}_{\mathrm{rw}}\vb{y} = \lambda\vb{y} with Lrw=D−1L\mat{L}_{\mathrm{rw}} = \mat{D}\inv\mat{L}). Shi and Malik’s spectral clustering is a Laplacian eigenmap followed by k-means; the difference is purpose, not computation: there one seeks kk 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 ff on manifold M\mathcal{M}. If two points are close, ∣f(x)−f(z)∣≲∥∇f(x)∥ ∥x−z∥\abs{f(\vb{x}) - f(\vb{z})} \lesssim \norm{\grad f(\vb{x})}\,\norm{\vb{x} - \vb{z}}, so a function mapping nearby points to nearby values on average over the manifold has small Dirichlet energy, ∫M∥∇f∥2\int_{\mathcal{M}}\norm{\grad f}^2. By Green’s formula, ∫∥∇f∥2=∫f Δf\int\norm{\grad f}^2 = \int f\,\Delta f, with Δ=−div⁡∇\Delta = -\operatorname{div}\grad 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 Δ\Delta when n→∞n \to \infty and τ→0\tau \to 0 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 [0,L]×[0,H][0, L] \times [0, H], the Neumann eigenfunctions are products of cosines:

fk,l(x,y)=cos⁡πkxLcos⁡πlyH,Δfk,l=π2(k2L2+l2H2)fk,l,k,l∈{0,1,2,… }.f_{k,l}(x, y) = \cos\frac{\pi k x}{L}\cos\frac{\pi l y}{H}, \qquad \Delta f_{k,l} = \pi^2\Big(\frac{k^2}{L^2} + \frac{l^2}{H^2}\Big) f_{k,l}, \qquad k, l \in \{0, 1, 2, \dots\}.

The first nontrivial one is cos⁡(πx/L)\cos(\pi x/L) if L>HL > H: it traverses the long side, as desired. But the second is cos⁡(2πx/L)\cos(2\pi x/L) as soon as L>2HL > 2H, because 4/L2<1/H24/L^2 < 1/H^2. And cos⁡(2πx/L)=2cos⁡2(πx/L)−1\cos(2\pi x/L) = 2\cos^2(\pi x/L) - 1 is a function of the first: the embedding (f1,0,f2,0)(f_{1,0}, f_{2,0}) is a parabola, a horseshoe, and height only appears at mode (0,1)(0, 1), which can come much later. The Swiss roll is about 89 units long and 21 high, a ratio of 4.26: modes (1,0)(1,0), (2,0)(2,0), (3,0)(3,0) and (4,0)(4,0) (16/4.262≈0.88<116/4.26^2 \approx 0.88 < 1) precede height.

InteractiveHarmonics of a strip
ψ1\psi_1 ≈ mode (1, 0), ∣ρ∣=1.000|\rho| = 1.000
ψ2\psi_2 ≈ mode (2, 0), ∣ρ∣=1.000|\rho| = 1.000
ψ3\psi_3 ≈ mode (0, 1), ∣ρ∣=0.996|\rho| = 0.996
Embedding (ψ1,ψ2)(\psi_1, \psi_2), colored by position xx along the strip
  • positive eigenvector
  • negative
  • embedding: x=0x = 0
  • x=L/2x = L/2
  • x=Lx = L
3.00
coord.predichocalculado
ψ1(1, 0)(1, 0) · 1.00
ψ2(2, 0)(2, 0) · 1.00
ψ3(0, 1)(0, 1) · 1.00
ψ4(3, 0)(3, 0) · 0.94
First coordinate containing height (predicted / calculated)3 / 3
λ1,λ2,λ3\lambda_1, \lambda_2, \lambda_3 of P\mat{P}0.987 · 0.947 · 0.889
With L/H=3.00>2L/H = 3.00 > 2, the second eigenvector is cos⁡(2πx/L)\cos(2\pi x/L), a function of ψ1=cos⁡(πx/L)\psi_1 = \cos(\pi x/L): embedding (ψ1,ψ2)(\psi_1, \psi_2) is a horseshoe (the parabola ψ2∝2ψ12−1\psi_2 \propto 2\psi_1^2 - 1) and height does not appear until coordinate 3.
About 220 points in a rectangle of aspect ratio L/HL/H and the first three nontrivial eigenvectors (red positive, blue negative), computed with the Gaussian kernel and normalization approaching the Laplace–Beltrami operator (covered under diffusion maps). Labels show which Neumann mode (k,l)(k, l) each resembles and its correlation. Below is the embedding with the first two coordinates, colored from x=0x = 0 (purple) to x=Lx = L (yellow). Initially, L/H=3L/H = 3: ψ2\psi_2 is cos⁡(2πx/L)\cos(2\pi x/L) and the embedding is a horseshoe. Lower L/HL/H below 2 and the rectangle unfolds; near L/H=2L/H = 2 (or a square, L/H=1L/H = 1), two modes have nearly equal eigenvalues and computed eigenvectors can mix: see the correlations.

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

[ ]Laplacian eigenmaps from scratch and their harmonicsBrowser
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 (8.3×10−158.3\times 10^{-15}). This requires copying a scikit-learn detail: it counts the point itself as one of the kk neighbors and then discards the self-loop, so it actually uses k−1k - 1 neighbors. The eigenvalues 7.35×10−47.35\times 10^{-4}, 3.26×10−33.26\times 10^{-3} and 6.86×10−36.86\times 10^{-3} increase almost as 1:4:91 : 4 : 9, the harmonics’ m2m^2 law, and the table confirms the strip prediction: y1y_1, y2y_2 and y3y_3 are cos⁡(πms/L)\cos(\pi m s/L) with m=1,2,3m = 1, 2, 3 (correlations 1.00, 0.95 and 0.89), and none sees height. Height appears in y4y_4 (0.72), and the fourth length harmonic in y5y_5 (0.73). Uniform-sampling theory would put mode (4,0)(4, 0) before (0,1)(0, 1), but their theoretical eigenvalues differ by only 12% (16/4.262≈0.8816/4.26^2 \approx 0.88); with 1000 points, a neighbor graph, and uniform sampling in tt (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 ii, the walker jumps to jj with probability pij=wij/dip_{ij} = w_{ij}/d_i:

P=D−1W,∑jpij=1,πi=divol⁡V,π⊤P=π⊤.\mat{P} = \mat{D}\inv\mat{W}, \qquad \sum_j p_{ij} = 1, \qquad \pi_i = \frac{d_i}{\operatorname{vol}V}, \qquad \vb{\pi}\T\mat{P} = \vb{\pi}\T .

The stationary distribution π\vb{\pi} is proportional to degree, and the chain is reversible: πipij=wij/vol⁡V=πjpji\pi_i p_{ij} = w_{ij}/\operatorname{vol}V = \pi_j p_{ji}. Reversibility makes P\mat{P}, which is not symmetric, similar to a symmetric matrix:

P=D−1/2 S D1/2,S=D−1/2WD−1/2=∑l=0n−1λlvlvl⊤.\mat{P} = \mat{D}^{-1/2}\,\mat{S}\,\mat{D}^{1/2}, \qquad \mat{S} = \mat{D}^{-1/2}\mat{W}\mat{D}^{-1/2} = \sum_{l=0}^{n-1}\lambda_l\vb{v}_l\vb{v}_l\T .

Thus P\mat{P} has real eigenvalues 1=λ0≥λ1≥⋯≥λn−1≥−11 = \lambda_0 \ge \lambda_1 \ge \cdots \ge \lambda_{n-1} \ge -1 (the same as S\mat{S}, and S=I−Lsym\mat{S} = \mat{I} - \mat{L}_{\mathrm{sym}}: large eigenvalues of P\mat{P} are small ones of the Laplacian). Normalize the eigenvectors as follows:

ψl=vol⁡V D−1/2vl    (right: Pψl=λlψl),ϕl=π⊙ψl    (left: ϕl⊤P=λlϕl⊤).\psi_l = \sqrt{\operatorname{vol}V}\,\mat{D}^{-1/2}\vb{v}_l \;\;(\text{right: } \mat{P}\psi_l = \lambda_l\psi_l), \qquad \phi_l = \vb{\pi}\odot\psi_l \;\;(\text{left: } \phi_l\T\mat{P} = \lambda_l\phi_l\T).

With this choice, ψ0=1\psi_0 = \vb{1}, ϕ0=π\phi_0 = \vb{\pi}, the ψl\psi_l are orthonormal under the weighted inner product ⟨f,g⟩π=∑iπifigi\inner{\vb{f}}{\vb{g}}_\pi = \sum_i\pi_i f_i g_i, and the chain’s ttth power has spectral decomposition

pt(i,j)=(Pt)ij=∑l=0n−1λlt ψl(i) ϕl(j)=πj∑l=0n−1λlt ψl(i) ψl(j).p_t(i, j) = (\mat{P}^t)_{ij} = \sum_{l=0}^{n-1}\lambda_l^t\,\psi_l(i)\,\phi_l(j) = \pi_j\sum_{l=0}^{n-1}\lambda_l^t\,\psi_l(i)\,\psi_l(j) .

The l=0l = 0 term is πj\pi_j, the equilibrium; the rest are deviations from equilibrium that decay as λlt\lambda_l^t. If the graph is connected and non-bipartite, ∣λl∣<1\abs{\lambda_l} < 1 for l≥1l \ge 1 and the chain converges to π\vb{\pi} at a rate set by λ1\lambda_1.

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 x\vb{x} and y\vb{y} tend to reach the same places in tt 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 K(α)=Q−αKQ−α\mat{K}^{(\alpha)} = \mat{Q}^{-\alpha}\mat{K}\mat{Q}^{-\alpha} and S\mat{S}: all λl\lambda_l lie in [0,1][0, 1] and λlt\lambda_l^t is meaningful for any t>0t > 0, not just integer time.

Diffusion distance

Proof

By spectral decomposition, pt(i,z)−pt(j,z)=∑lλlt(ψl(i)−ψl(j))ϕl(z)p_t(i, z) - p_t(j, z) = \sum_{l}\lambda_l^t\big(\psi_l(i) - \psi_l(j)\big)\phi_l(z), and the l=0l = 0 term vanishes because ψ0=1\psi_0 = \vb{1}. Let al=λlt(ψl(i)−ψl(j))a_l = \lambda_l^t(\psi_l(i) - \psi_l(j)). Then

Dt(i,j)2=∑l,m≥1alam∑zϕl(z)ϕm(z)πz=∑l,m≥1alam∑zπzψl(z)ψm(z)=∑l≥1al2,D_t(i, j)^2 = \sum_{l, m \ge 1} a_l a_m \sum_z \frac{\phi_l(z)\phi_m(z)}{\pi_z} = \sum_{l, m \ge 1} a_l a_m \sum_z \pi_z\psi_l(z)\psi_m(z) = \sum_{l \ge 1}a_l^2,

using ϕl=π⊙ψl\phi_l = \vb{\pi}\odot\psi_l and orthonormality of the ψl\psi_l in L2(π)L^2(\pi).

∎

The theorem is the heart of the method: a distance defined by all paths of length tt between two points (rows of Pt\mat{P}^t sum all their probabilities) is a Euclidean distance in diffusion-map coordinates. And because the λl2t\lambda_l^{2t} decay, a few coordinates suffice. Truncating at dd, the error in Dt2D_t^2 is ∑l>dλl2t(ψl(i)−ψl(j))2≤λd+12t(1/πi+1/πj)\sum_{l > d}\lambda_l^{2t}(\psi_l(i) - \psi_l(j))^2 \le \lambda_{d+1}^{2t}\big(1/\pi_i + 1/\pi_j\big), because basis completeness gives ∑l≥0ψl(i)ψl(j)=δij/πi\sum_{l \ge 0}\psi_l(i)\psi_l(j) = \delta_{ij}/\pi_i. Following Coifman and Lafon, the diffusion dimension at precision δ\delta is the number of surviving coordinates:

q(t)=#{ l≥1:λlt>δ λ1t }.q(t) = \#\{\,l \ge 1 : \lambda_l^t > \delta\,\lambda_1^t\,\}.

Time as a scale

tt is not a detail: it determines which structure the distance sees. For small tt, many λlt\lambda_l^t remain near 1 and the distance distinguishes fine details; as tt 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.

InteractiveDiffusion time as a lens
Heat pt(x0,⋅)p_t(x_0, \cdot) after t=5t = 5 steps (size and opacity)
Mean diffusion distance relative to the between-group mean
00.250.50.751110¹10²10³10⁴10⁵tiempo t (escala logarítmica)
Dt(xi,xj)D_t(x_i, x_j) matrix, ordered by group and subgroup (intense: close)
Weights λlt\lambda_l^t of coordinates l=1,…,12l = 1, \dots, 12
00.250.50.751123456789101112δ·λ₁ᵗcoordenada l
  • group 1
  • group 2
  • group 3
  • subgroups: shades of group color
  • heat source
  • different subgroups of same group
  • same subgroup
5
Diffusion dimension q(t)q(t), δ=0.1\delta = 0.18
Mean DtD_t between subgroups within a group / between groups0.848
Mean DtD_t within a subgroup / between groups0.058
Heat in starting subgroup80.5 %
Heat in starting group99.9 %
At t = 5, 8 coordinates remain: diffusion distance separates nine subgroups and heat barely leaves the starting subgroup (80 % remains).
Three groups, each with three subgroups of 10 points (Gaussian kernel with ε=1\varepsilon = 1, α=1\alpha = 1). Top left, the heat pt(x0,⋅)p_t(x_0, \cdot) of a walk starting at the marked point (click another to change it); right, average diffusion distances between points in the same subgroup (dashed) and between different subgroups of the same group (purple), divided by the average between different groups, for every tt. Below, matrix DtD_t (Euclidean distances in the full diffusion embedding), points ordered by group and subgroup, and the weights λlt\lambda_l^t of the first coordinates with threshold δλ1t\delta\lambda_1^t, δ=0.1\delta = 0.1. Initially t=5t = 5: the matrix has nine blocks and eight coordinates survive. Set tt to 300: three blocks, two coordinates, the purple curve has fallen and heat has spread through the group. At 10410^4 only one coordinate remains.

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 tt, and diffusion dimension goes from 8 (the 9−19 - 1 subgroup contrasts) to 2 (the 3−13 - 1 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 n→∞n \to \infty and ε→0\varepsilon \to 0 for data with density qq on a compact manifold: (Pε,α−I)/ε(\mat{P}_{\varepsilon, \alpha} - \mat{I})/\varepsilon tends, up to a positive constant factor, to the operator

Lαf=Δ(fq1−α)q1−α−Δ(q1−α)q1−α f  =  Δf+2(1−α) ⟨∇log⁡q,∇f⟩,\mathcal{L}_\alpha f = \frac{\Delta(f q^{1-\alpha})}{q^{1-\alpha}} - \frac{\Delta(q^{1-\alpha})}{q^{1-\alpha}}\,f \;=\; \Delta f + 2(1 - \alpha)\,\inner{\grad\log q}{\grad f},

where the second form follows from expanding Δ(fg)=gΔf+2⟨∇f,∇g⟩+fΔg\Delta(fg) = g\Delta f + 2\inner{\grad f}{\grad g} + f\Delta g with g=q1−αg = q^{1-\alpha}. Watch the sign: in this formula, Δ=div⁡∇\Delta = \operatorname{div}\grad is the analytic Laplacian, negative semidefinite, the opposite of the one used for eigenmaps; with it, Lα\mathcal{L}_\alpha is the generator of a diffusion with drift 2(1−α)∇log⁡q2(1 - \alpha)\grad\log q. The three classical values:

  • α=0\alpha = 0: the usual normalized-Laplacian walk, with drift of strength 2 toward dense regions. Eigenfunctions mix geometry and density: useful for clustering.
  • α=1/2\alpha = 1/2: drift of strength 1, the Fokker–Planck operator of a Langevin diffusion whose equilibrium distribution is the data density qq itself.
  • α=1\alpha = 1: no drift. L1=Δ\mathcal{L}_1 = \Delta is the Laplace–Beltrami operator: eigenfunctions depend only on geometry, regardless of sampling density.
InteractiveDensity misleads
Sample on the arc, colored by ψ1\psi_1
s = 0s = 1
a ψ1(s)a\,\psi_1(s) versus Laplace–Beltrami eigenfunction cos⁡(πs)\cos(\pi s)
−1−0.500.5100.250.50.751abscisa de arco s
  • computed a ψ1a\,\psi_1 (one point in three)
  • cos⁡(πs)\cos(\pi s), limit with α=1\alpha = 1
0.00
3.0
Lαf=Δf+2.00 ⟨∇log⁡q,∇f⟩\mathcal{L}_\alpha f = \Delta f + 2.00\,\langle \nabla \log q, \nabla f \rangle
Maximum error versus cos⁡(πs)\cos(\pi s)0.932
∣ρ(ψ1,cos⁡πs)∣|\rho(\psi_1, \cos \pi s)|0.9595
Density at s=0s = 0 versus s=1s = 120.1 : 1
λ1\lambda_10.9799
With α=0.00\alpha = 0.00 the limiting operator has drift 2(1−α)⟨∇log⁡q,∇f⟩2(1 - \alpha)\langle\nabla\log q, \nabla f\rangle: la autofunción casi no varía en la zona densa y concentra su variación en la escasa (maximum error 0.932 ). Increase α\alpha to 1.
150 points on a 200° arc with arc coordinate ss sampled with density proportional to e−βse^{-\beta s} (the region at s=0s = 0 is up to e4.5≈90e^{4.5} \approx 90 times denser than at s=1s = 1). Left, points colored by the first diffusion coordinate; right, that coordinate (least-squares scaled) against ss, with the Laplace–Beltrami eigenfunction cos⁡(πs)\cos(\pi s) dashed. Initially α=0\alpha = 0 and β=3\beta = 3: the coordinate varies little in the dense region and concentrates its variation in the sparse one. Raise α\alpha to 1 and it approaches the cosine; set β=0\beta = 0 and all α\alpha agree. Upper right, the limiting operator with its drift coefficient.

For a parametrization of the manifold (a coordinate measuring position, not density), use α=1\alpha = 1. For clustering, density is useful information and α=0\alpha = 0 exploits it.

Test yourself before the lab

CodeDiffusion maps in one function
Implement diffusion_map(X, eps, alpha, t, d) using the kernel exp⁡(−∥x−y∥2/ε)\exp(-\|x - y\|^2/\varepsilon), α\alpha normalization and time tt, returning an array (n, d) of coordinates λltψl\lambda_l^t\psi_l, l=1,…,dl = 1, \dots, d, with ψl\psi_l normalized in L2(π)L^2(\pi) (that is, ψ0=1\psi_0 = 1). Diagonalize a symmetric matrix similar to PP with np.linalg.eigh, not PP 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))
Shift+Enter to run

Lab: diffusion maps from scratch

The first cell implements the method, checks the review’s properties (rows sum to 1, π\vb{\pi} stationary, orthonormality in L2(π)L^2(\pi)), and verifies the diffusion distance theorem by comparing the definition with the spectral formula.

[ ]Diffusion maps and diffusion distanceBrowser
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 P\mat{P} sum to 1, π\vb{\pi} is stationary, the ψl\psi_l are orthonormal in L2(π)L^2(\pi) to 2.5×10−132.5\times 10^{-13}, and diffusion distance at t=3t = 3 between the first two points is 9.277819 both by definition (summing over 500 destinations of P3\mat{P}^3) and by the spectral formula. Notice the eigenvalues: 0.9993, 0.9975, 0.9936 and subsequent ones are very close to 1. With ε=4\varepsilon = 4, the kernel barely connects points more than 3 or 4 units apart (e−16/4≈0.02e^{-16/4} \approx 0.02), and such a walk needs on the order of 1/(1−λ1)≈13701/(1 - \lambda_1) \approx 1370 steps to traverse a roll 89 units long: in this sample large times are needed for diffusion to forget its starting point.

[ ]α normalization on a segment with uneven densityBrowser
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 Beta(1,3)\mathrm{Beta}(1, 3) density is 3(1−x)23(1 - x)^2: three times uniform at x=0x = 0 and nearly zero near x=1x = 1. With α=0\alpha = 0, the first coordinate resembles the Laplace–Beltrami eigenfunction, cos⁡(πx)\cos(\pi x), with correlation 0.898; with α=1/2\alpha = 1/2, 0.968; with α=1\alpha = 1, 0.999. This is what the limiting operator predicts: drift 2(1−α)∇log⁡q2(1 - \alpha)\grad\log q disappears at α=1\alpha = 1.

[ ]A bridge between layers: geodesic versus diffusion distanceBrowser
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 t=20t = 20 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 K\mat{K}, centers it (K~=HKH\tilde{\mat{K}} = \mat{H}\mat{K}\mat{H} with H=I−1n11⊤\mat{H} = \mat{I} - \frac1n\vb{1}\vb{1}\T), and uses its eigenvectors with largest eigenvalues as coordinates, scaled by the eigenvalue’s square root. Isomap already did this with K=−12HDG(2)H\mat{K} = -\frac12\mat{H}\mat{D}_G^{(2)}\mat{H}, 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 M\mat{M}, with eigenvalues c−μl≥0c - \mu_l \ge 0 and 1/μl1/\mu_l (and 00 for v1\vb{v}_1 in M+\mat{M}\pinv): they are positive semidefinite. Since v1∝1\vb{v}_1 \propto \vb{1} is an eigenvector, H\mat{H} acts as the identity on 1⊥\vb{1}^\perp and annihilates 1\vb{1}, so the centered kernel retains eigenvectors v2,…,vn\vb{v}_2, \dots, \vb{v}_n and their eigenvalues, and sends that of v1\vb{v}_1 to 0. Functions μ↦c−μ\mu \mapsto c - \mu and μ↦1/μ\mu \mapsto 1/\mu decrease on (0,∞)(0, \infty): the dd largest eigenvalues of the centered kernel correspond to μ2,…,μd+1\mu_2, \dots, \mu_{d+1}, the smallest nonzero ones of M\mat{M}.

∎

The unified-view table is:

MethodKernel on the sampleWhat it preserves
Isomap−12HDG(2)H-\frac12\mat{H}\mat{D}_G^{(2)}\mat{H} (squared geodesics)global geodesic distances
LLEλmax⁡I−(I−W)⊤(I−W)\lambda_{\max}\mat{I} - (\mat{I} - \mat{W})\T(\mat{I} - \mat{W})local linear reconstructions
EigenmapsL+\mat{L}\pinv (or Lsym+\mat{L}_{\mathrm{sym}}\pinv in variables D1/2Y\mat{D}^{1/2}\mat{Y})graph proximity
Diffusion maps (after Ham and coauthors)a2t(i,j)=p2t(i,j)/πja_{2t}(i, j) = p_{2t}(i, j)/\pi_j, with PCA weighted by π\vb{\pi}connectivity through paths of length tt

Two rows have a nice probabilistic interpretation. L+\mat{L}\pinv is the commute-time kernel: the expected number of steps for a walk to go from ii to jj and back is vol⁡V (ei−ej)⊤L+(ei−ej)\operatorname{vol}V\,(\vb{e}_i - \vb{e}_j)\T\mat{L}\pinv(\vb{e}_i - \vb{e}_j), so eigenmaps with kernel L+\mat{L}\pinv are MDS of commute distance (a classical result relating random walks and electrical networks: commute time is vol⁡V\operatorname{vol}V times effective resistance between ii and jj). For diffusion maps, reversibility makes as(i,j)=ps(i,j)/πj=∑lλlsψl(i)ψl(j)a_s(i, j) = p_s(i, j)/\pi_j = \sum_l\lambda_l^s\psi_l(i)\psi_l(j) symmetric, and the diffusion-distance theorem’s proof states exactly that Dt(i,j)2=a2t(i,i)+a2t(j,j)−2a2t(i,j)D_t(i, j)^2 = a_{2t}(i, i) + a_{2t}(j, j) - 2a_{2t}(i, j): diffusion distance is the distance induced by kernel a2ta_{2t}.

There is an important nuance. These kernels are defined only on the sample: LLE’s W\mat{W}, the neighbor graph, and geodesics depend on all points, and there is no formula k(x,z)k(\vb{x}, \vb{z}) evaluable at a new x\vb{x}. 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 n×nn\times n 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 (K)ij=kn(xi,xj)(\mat{K})_{ij} = k_n(\vb{x}_i, \vb{x}_j) with a function knk_n evaluable at any point, the eigenvalue equation itself tells us how to extend them.

Bengio and coauthors construct a suitable function knk_n for each method. For this lesson’s methods the formulas are natural:

  • Diffusion maps. The equation is Pψl=λlψl\mat{P}\psi_l = \lambda_l\psi_l and a new point’s transition row is computed like training rows: k(α)(x,xj)=kε(x,xj)/(q(x)αq(xj)α)k^{(\alpha)}(\vb{x}, \vb{x}_j) = k_\varepsilon(\vb{x}, \vb{x}_j)/(q(\vb{x})^\alpha q(\vb{x}_j)^\alpha) with q(x)=∑jkε(x,xj)q(\vb{x}) = \sum_j k_\varepsilon(\vb{x}, \vb{x}_j), normalized to sum to 1 (the factor q(x)αq(\vb{x})^\alpha cancels). Then
λlt ψl(x)=λlt−1∑jp(x,xj) ψl(xj).\lambda_l^t\,\psi_l(\vb{x}) = \lambda_l^{t-1}\sum_{j} p(\vb{x}, \vb{x}_j)\,\psi_l(\vb{x}_j).
  • Laplacian eigenmaps. Ly=λDy\mat{L}\vb{y} = \lambda\mat{D}\vb{y} is equivalent to Py=(1−λ)y\mat{P}\vb{y} = (1 - \lambda)\vb{y}, so yl(x)=11−λl∑jp(x,xj) yl(j)y_l(\vb{x}) = \frac{1}{1 - \lambda_l}\sum_j p(\vb{x}, \vb{x}_j)\,y_l(j), 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 x\vb{x} over its kk training neighbors and applying them to their images: y(x)=∑jwj(x) yj\vb{y}(\vb{x}) = \sum_j w_j(\vb{x})\,\vb{y}_j. 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 O(nD)\bigO(nD) (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 1/λl1/\lambda_l or 1/(1−λl)1/(1 - \lambda_l), 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 λl\lambda_l).

InteractiveEmbedding new points
Input space: drag the new point
Embedding (λ1ψ1,λ2ψ2)(\lambda_1\psi_1, \lambda_2\psi_2)
  • training (color: angle)
  • Nyström of new point
  • refit (ring)
Method
Nyström versus refit (dragged point)0.19 %
Training displacement under refitting0.31 %
Distance to nearest data point0.037
Inside the data, the extension lies 0.2 % of the diameter from the refitted position; refitting moves training points by 0.3 % on average. The discrepancy is of the same order as the fit change.
200 training points in an annular sector (color: angle) and their embedding using diffusion maps (ε=0.3\varepsilon = 0.3, α=1\alpha = 1) or LLE (k=10k = 10). Drag the magenta point on the left: its Nyström image moves live on the right. On release, the method is refit with the point included, the result aligned to the original embedding by Procrustes, and the ring marks where refitting would place it. Readouts compare the discrepancy with how much the training points themselves move when refitting, as a percentage of embedding diameter. Diffusion coordinates are approximately cosines of angle and radius (Neumann modes of the sector), so points accumulate near embedding boundaries. Enable the batch of 20 new points to see the average, and move the point far from the sector: Nyström sticks it to the nearest data point.

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.

[ ]Nyström extension for diffusion maps and LLEBrowser
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 6.0×10−156.0\times 10^{-15}, 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 nn, because refitting is cubic in nn and extension linear). Finally, the distant point (−3,0)(-3, 0) lands at (0.646,−1.918)(0.646, -1.918), almost on its nearest training point’s image divided by λ\lambda, (0.658,−1.911)(0.658, -1.911): 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 kk-neighbor graph and measures trustworthiness T(10)T(10) and continuity C(10)C(10): TT penalizes false neighbors in the embedding (points brought together that were not neighbors) and CC penalizes lost neighbors.

InteractiveEmbedding benchmark
Datos
PCAT 0.939 · C 0.977
IsomapT 0.998 · C 0.998
LLET 0.987 · C 0.988
Mapas propiosT 0.955 · C 0.982
Diffusion mapsT 0.948 · C 0.978
  • parameter start
  • middle
  • end
Data
10
PCA only projects: it sees the spiral but does not unroll it. Isomap unfolds the rectangle and LLE nearly does, with its characteristic normalization curvature. Eigenmaps and diffusion maps form a horseshoe: their second coordinate is the second length harmonic, not height. Against true coordinates, Isomap and LLE approach T = 1 while the horseshoe is lower. Increase k to 20 for shortcuts; with very small k the graph disconnects.
Five datasets (a one-turn Swiss roll, shorter and lower than scikit-learn's so 260 points sample it without shortcuts, the S-curve, moons and sphere, with 260 points each; and 250 8×8 digits) and five two-dimensional methods, all calculated in your browser with the same kk-neighbor graph: PCA, Isomap, LLE (reg=10−3\texttt{reg} = 10^{-3}), Laplacian eigenmaps and diffusion maps (α=1\alpha = 1, t=1t = 1, ε\varepsilon equal to the median squared distance to the kkth neighbor). Above each panel, T(10)T(10) and C(10)C(10) against the original data or, if enabled, against true Swiss-roll and S-curve coordinates; the best in each column is green. Colors show the intrinsic parameter or class. PCA and Isomap use equal axis scales because their coordinates are distances; the other three use free scales because their coordinates are normalized.

Given what you have seen, these differences matter:

IsomapLLEEigenmapsDiffusion maps
Information usedall-pairs geodesicslocal reconstructionsgraph edgespaths of length tt
Matrixdense n×nn \times nsparse (≈nk2\approx nk^2)sparse (≈nk\approx nk)dense with Gaussian kernel (sparse if truncated)
Eigenvectorslargestsmallest nontrivialsmallest nontriviallargest nontrivial
Coordinate scalemetric (distances)forced variance 1forced Y⊤DY=I\mat{Y}\T\mat{D}\mat{Y} = \mat{I}λlt\lambda_l^t: reflects time scale
Parameterskkkk, regkk or ε\varepsilon, weightsε\varepsilon, α\alpha, tt
New pointsNyström (MDS formula)reconstruction weightsNyströmNyström
Fails withshortcuts, poorly estimated geodesicsnoise, poor reg, proportionsdisconnected graphs, harmonicspoor ε\varepsilon, 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 α=1\alpha = 1 and inspect more than two coordinates: discard those that are functions of earlier ones (harmonics).
  • For clustering, use eigenmaps or diffusion maps with α=0\alpha = 0, followed by k-means: this is spectral clustering.
  • For structure at multiple scales, use diffusion maps at several values of tt.
  • 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 TT and CC, but remember what they measure: neighborhoods. In the benchmark, the Laplacian-eigenmap and diffusion-map horseshoe on the Swiss roll has TT 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. TT and CC do not detect harmonics; inspect coordinates or test whether each can be predicted from earlier ones, as Dsilva and coauthors propose.

Common mistakes

Exercises

ProofLLE weights do not see similarities
Prove: Let xi\vb{x}_i and its neighbors xj1,…,xjk\vb{x}_{j_1}, \dots, \vb{x}_{j_k} have invertible local Gram matrix C\mat{C}, and let T(x)=sQx+bT(\vb{x}) = s\mat{Q}\vb{x} + \vb{b} with orthogonal Q\mat{Q} and s≠0s \neq 0. The optimal reconstruction weights with ∑awa=1\sum_a w_a = 1 are the same for the transformed points.
0
Write ηa=xi−xja\vb{\eta}_a = \vb{x}_i - \vb{x}_{j_a} and recall that w⋆=C−11/(1⊤C−11)\vb{w}^\star = \mat{C}\inv\vb{1}/(\vb{1}\T\mat{C}\inv\vb{1}) with Cab=ηa⊤ηbC_{ab} = \vb{\eta}_a\T\vb{\eta}_b.

Step 1 of 5. What role does the constraint ∑awa=1\sum_a w_a = 1 play in the residual's form?

ProofFrom smoothness to the generalized problem
Prove: Minimizing 12∑i,jwij∥yi−yj∥2\frac12\sum_{i,j}w_{ij}\|\vb{y}_i - \vb{y}_j\|^2 over Y∈Rn×d\mat{Y} \in \R^{n \times d} with Y⊤DY=Id\mat{Y}\T\mat{D}\mat{Y} = \mat{I}_d and Y⊤D1=0\mat{Y}\T\mat{D}\vb{1} = \vb{0} leads to the generalized problem Ly=λDy\mat{L}\vb{y} = \lambda\mat{D}\vb{y}, and the minimum is λ2+⋯+λd+1\lambda_2 + \cdots + \lambda_{d+1} (connected graph, di>0d_i > 0).
0
Let L=D−W\mat{L} = \mat{D} - \mat{W} with symmetric W\mat{W} of nonnegative weights.

Step 1 of 4. What is ∑i,jwij(fi−fj)2\sum_{i,j}w_{ij}(f_i - f_j)^2 for a vector f\vb{f}?

QuizThe discarded eigenvector
Laplacian eigenmaps compute the generalized eigenvectors Ly=λDy\mat{L}\vb{y} = \lambda\mat{D}\vb{y} with smallest eigenvalues and discard the first. Why?
NumericWeight of the first coordinate
A dataset's diffusion operator has eigenvalues λ0=1\lambda_0 = 1, λ1=0.9\lambda_1 = 0.9 and λ2=0.5\lambda_2 = 0.5 (the rest are smaller). With t=10t = 10, what factor multiplies ψ1\psi_1 in diffusion map Ψ10\Psi_{10}?
NumericReconstruction with two neighbors
In the plane, xi=(0,1)\vb{x}_i = (0, 1) has two neighbors, a=(−1,0)\vb{a} = (-1, 0) and b=(2,0)\vb{b} = (2, 0). What is the LLE weight of a\vb{a} (without regularization)?
NumericDiffusion distance on a two-node graph
A two-node graph has weights w11=3w_{11} = 3, w12=w21=1w_{12} = w_{21} = 1 and w22=1w_{22} = 1 (with self-loops). Calculate diffusion distance D2(1,2)D_2(1, 2) at time t=2t = 2.
NumericWhen does height appear?
Eigenmaps of a densely and uniformly sampled flat 10×310 \times 3 strip approximate Neumann eigenfunctions cos⁡(πkx/10)cos⁡(πly/3)\cos(\pi k x/10)\cos(\pi l y/3). Numbering nontrivial coordinates by increasing eigenvalue (1,2,3,…1, 2, 3, \dots), which is the first to depend on height yy?
NumericDiffusion dimension
A diffusion operator has eigenvalues 1,0.99,0.95,0.8,0.51, 0.99, 0.95, 0.8, 0.5 and the rest below 0.50.5. With t=20t = 20 and precision δ=0.1\delta = 0.1, how many coordinates does the diffusion map have, q(t)=#{l≥1:λlt>δλ1t}q(t) = \#\{l \ge 1 : \lambda_l^t > \delta\lambda_1^t\}?
QuizWhat α = 1 corrects
You sample a manifold at very uneven density. What does diffusion-map normalization α=1\alpha = 1 achieve?
QuizA point far from everything
You fit diffusion maps with a Gaussian kernel and apply Nyström extension to a point x\vb{x} far from the entire sample. Where does it land?
QuizTwo runs that disagree
You fit two-dimensional Laplacian eigenmaps twice to uniformly distributed points on a sphere, with different ARPACK seeds. The embeddings look different. What is most likely?
QuizWhat the unified view says
Which statements are true?

More than one answer may be correct.

QuizChoosing a method
You have 5000 records from a sensor following a slow trajectory in 50-dimensional space, sampled much more often in some phases than others, with moderate noise. You want a coordinate measuring where each record lies on the trajectory and to assign it to new records each day. What do you choose?

Summary

Key idea
Local spectral methods convert neighborhood information (how each point is reconstructed, which points are connected, where a random walk leads) into an eigenvalue problem whose eigenvectors are the smoothest functions on the data. They are all kernel PCA with a kernel built from the sample, and the same eigenvalue equation allows new points to be embedded with Nyström.
  • 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 (I−W)⊤(I−W)(\mat{I} - \mat{W})\T(\mat{I} - \mat{W}). With kk greater than the dimension, regularize.
  • Laplacian eigenmaps minimize ∑wij∥yi−yj∥2\sum w_{ij}\norm{\vb{y}_i - \vb{y}_j}^2 subject to Y⊤DY=I\mat{Y}\T\mat{D}\mat{Y} = \mat{I}: the generalized problem Ly=λDy\mat{L}\vb{y} = \lambda\mat{D}\vb{y}, 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 λlt\lambda_l^t: Euclidean distance between their coordinates is diffusion distance, summing over all paths and robust to shortcuts. tt sets the scale and α=1\alpha = 1 removes the effect of density.
  • Unified view: with M1=0\mat{M}\vb{1} = \vb{0}, smallest eigenvectors of M\mat{M} are largest eigenvectors of cI−Mc\mat{I} - \mat{M} or M+\mat{M}\pinv; 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.