Manifold learning: measure the route before drawing the map
流形学习
Build a small Isomap model, expose a neighborhood shortcut and distinguish accurate spectral computation from correct geometry.
manifold-learningThe gap across a bend is not the route around it
Stand at one end of a U-shaped walkway. The other end is two units away across the open gap, but following the walkway takes six units. Both distances are reasonable. They answer different questions about which movements are allowed.
Manifold learning tries to find lower-dimensional coordinates that preserve a chosen kind of structure in observations. A photograph may contain thousands of pixel values while varying mainly with a few factors such as viewpoint. The number of recorded coordinates is the ambient dimension; the number of local degrees of freedom is the intrinsic dimension. A low intrinsic dimension is an assumption to investigate, not a property guaranteed by having a large dataset.
Our example uses seven points on a bent path in a two-dimensional plane. We will construct a neighborhood graph, measure routes through it and recover coordinates from those distances. Changing one radius turns the long route into a shortcut. The picture is small enough that you can identify the offending edges yourself.
Tenenbaum, de Silva and Langford’s Isomap paper combines neighborhood construction, shortest paths and classical multidimensional scaling (MDS). Its goal is to represent intrinsic geometry estimated from local connections. Original paper, Table 1
Local coordinates do not promise a single flat global map
A d-dimensional manifold locally resembles a region of d-dimensional Euclidean space: around each interior point, a coordinate chart identifies a neighborhood with an open subset of that space. Smooth charts support derivatives and tangent directions. A curve has one local direction even if it bends through many measured coordinates. Points on a boundary need corresponding boundary charts.
For a smooth manifold embedded in Euclidean space, an intrinsic geodesic distance takes the infimum over piecewise smooth paths along it:
The straight ambient segment can leave M. With only sample points, we do not know all paths on M. Isomap replaces them with routes through a neighborhood graph. Our program uses an undirected edge whenever two distinct observations are within a closed radius epsilon, with their ordinary Euclidean distance as edge weight:
Floyd–Warshall computes all such shortest paths. A missing path means the graph is disconnected; our implementation stops instead of inventing a bridge. The fixed scikit-learn guide also describes Isomap through neighbor search, shortest paths and an eigendecomposition. Isomap guide, fixed 1.7.2
From distances to inner products
Let D contain the graph distances. Square its entries, then center from both sides:
The superscript circle means elementwise squaring. This is not the matrix product DD. To see why centering helps, imagine D already came from Euclidean coordinates collected in rows of X. Each squared distance is the sum of two squared norms minus twice an inner product. Multiplication by H removes the separate norm terms, leaving
Thus a Euclidean squared-distance matrix gives a positive semidefinite centered Gram matrix. Conversely, a positive semidefinite B reconstructed from D yields coordinates by taking square roots of its eigenvalues. For ordered eigenpairs with positive retained eigenvalues, the d-dimensional coordinate of record i is
The paper specifies this centering operator in note 17 and the coordinate construction in Table 1. For a symmetric B, retaining its largest positive eigenvalues gives a best rank-at-most-d positive semidefinite approximation in Frobenius norm. This spectral optimization is conditional on the graph already chosen; it does not optimize the neighborhood radius. Original paper, Eq.1, note 17 and Table 1
A graph distance matrix need not be exactly Euclidean. Substantial negative eigenvalues are evidence of that incompatibility, not coordinates whose square roots should be taken anyway. We report them and fit only resolved positive directions. Insufficient positive directions cause an explicit error. When an entire repeated-eigenvalue block is retained, changing its basis rotates coordinates and preserves the represented geometry. If the cutoff splits that block, the optimal retained subspace is also nonunique: equally optimal embeddings can have different pairwise distances. A sign change or a rotation within a fixed retained subspace still preserves geometry.
Expose the graph and its spectrum
This complete Python 3 program uses the standard library. Its teaching domain is 3–12 distinct two-dimensional points, integer or float coordinates of absolute value at most 1,000, radius in (0,10,000], and an integer output dimension between one and n−1. Booleans, nonfinite values and invalid shapes are rejected. Edge thresholds use the actual floating-point distances with a closed comparison; the program does not silently expand the radius.
The eigensolver performs Jacobi rotations and checks the resulting eigenpair residual and orthogonality. It stops on failed numerical checks or an iteration limit. The returned graph, Gram matrix, spectrum and two error measures are available for inspection. This is a small computation, not a scalable Isomap implementation or an out-of-sample transformation API.
import math
def symmetric_eigen(matrix):
# Internal Jacobi solver for the small, finite symmetric Gram matrix.
n=len(matrix);a=[row[:] for row in matrix]
v=[[float(i==j) for j in range(n)] for i in range(n)]
scale=max(1.0,math.sqrt(sum(x*x for row in a for x in row)))
for _ in range(100*n*n):
p,q=max(((i,j) for i in range(n) for j in range(i+1,n)),key=lambda ij:abs(a[ij[0]][ij[1]]))
if abs(a[p][q])<=1e-13*scale:break
tau=(a[q][q]-a[p][p])/(2*a[p][q])
t=math.copysign(1.0,tau)/(abs(tau)+math.hypot(1.0,tau))
c=1/math.sqrt(1+t*t);s=t*c;off=a[p][q]
a[p][p]-=t*off;a[q][q]+=t*off;a[p][q]=a[q][p]=0.0
for k in range(n):
if k not in (p,q):
ap,aq=a[k][p],a[k][q]
a[k][p]=a[p][k]=c*ap-s*aq
a[k][q]=a[q][k]=s*ap+c*aq
vp,vq=v[k][p],v[k][q];v[k][p]=c*vp-s*vq;v[k][q]=s*vp+c*vq
else:raise ArithmeticError('Jacobi iteration limit reached')
order=sorted(range(n),key=lambda j:a[j][j],reverse=True)
eigenvalues=tuple(a[j][j] for j in order)
vectors=[]
for j in order:
col=[v[i][j] for i in range(n)];pivot=max(range(n),key=lambda i:abs(col[i]))
vectors.append(tuple(x if col[pivot]>=0 else -x for x in col))
residual=math.sqrt(sum((sum(matrix[i][j]*u[j] for j in range(n))-lam*u[i])**2
for lam,u in zip(eigenvalues,vectors) for i in range(n)))/scale
orthogonal=max(abs(sum(u[i]*w[i] for i in range(n))-float(j==k))
for j,u in enumerate(vectors) for k,w in enumerate(vectors))
if not residual<=1e-10 or not orthogonal<=1e-10:
raise ArithmeticError('eigenpair certificate failed')
return eigenvalues,tuple(vectors),residual,orthogonal
def isomap(points,radius,dimensions=1):
if type(points) not in (list,tuple) or not 3<=len(points)<=12:
raise ValueError('between three and twelve points required')
if any(type(p) not in (list,tuple) or len(p)!=2 for p in points):
raise ValueError('two coordinates per point required')
if any(type(x) not in (int,float) or abs(x)>1000 or not math.isfinite(x) for p in points for x in p):
raise ValueError('finite real coordinates with absolute value <= 1000 required')
x=tuple(tuple(float(v) for v in p) for p in points);n=len(x)
if len(set(x))!=n:raise ValueError('duplicate points are excluded in this teaching model')
if type(radius) not in (int,float) or not 0<radius<=10000 or not math.isfinite(radius):
raise ValueError('positive finite radius at most 10000 required')
if type(dimensions) is not int or not 1<=dimensions<n:raise ValueError('invalid output dimension')
ambient=tuple(tuple(math.dist(p,q) for q in x) for p in x)
edges=tuple((i,j,ambient[i][j]) for i in range(n) for j in range(i+1,n) if ambient[i][j]<=radius)
graph=[[0.0 if i==j else math.inf for j in range(n)] for i in range(n)]
for i,j,w in edges:graph[i][j]=graph[j][i]=w
for k in range(n):
for i in range(n):
for j in range(n):graph[i][j]=min(graph[i][j],graph[i][k]+graph[k][j])
if any(not math.isfinite(d) for row in graph for d in row):
raise ValueError('radius graph is disconnected; no automatic bridge is inserted')
squared=[[d*d for d in row] for row in graph]
means=[sum(row)/n for row in squared];grand=sum(means)/n
gram=[[-0.5*(squared[i][j]-means[i]-means[j]+grand) for j in range(n)] for i in range(n)]
values,vectors,residual,orthogonal=symmetric_eigen(gram)
tolerance=1e-10*max(1.0,max(abs(v) for v in values))
if values[dimensions-1]<=tolerance:raise ValueError('requested dimension exceeds resolved positive spectrum')
embedding=tuple(tuple(math.sqrt(values[k])*vectors[k][i] for k in range(dimensions)) for i in range(n))
error=sum((gram[i][j]-sum(a*b for a,b in zip(embedding[i],embedding[j])))**2 for i in range(n) for j in range(n))
norm=sum(a*a for row in gram for a in row)
distance_rmse=math.sqrt(sum((graph[i][j]-math.dist(embedding[i],embedding[j]))**2 for i in range(n) for j in range(i+1,n))/(n*(n-1)/2))
return dict(edges=edges,graph_distances=tuple(map(tuple,graph)),gram=tuple(map(tuple,gram)),
eigenvalues=values,embedding=embedding,relative_strain=math.sqrt(error/max(norm,1e-300)),
distance_rmse=distance_rmse,negative_eigenvalues=sum(v < -tolerance for v in values),
eigen_residual=residual,orthogonality_error=orthogonal)
if __name__=='__main__':
points=((0,2),(0,1),(0,0),(1,0),(2,0),(2,1),(2,2))
print('ambient endpoint distance:',math.dist(points[0],points[-1]))
for radius,dimension in [(1,1),(2,1),(3,2)]:
report=isomap(points,radius,dimension)
print('radius / dimensions:',radius,dimension,'edges:',len(report['edges']))
print('endpoint graph / embedding:',round(report['graph_distances'][0][-1],6),
round(math.dist(report['embedding'][0],report['embedding'][-1]),6))
print('strain / distance RMSE / negative spectrum:',round(report['relative_strain'],6),
round(report['distance_rmse'],6),report['negative_eigenvalues'])
try:isomap(points,0.9)
except ValueError as error:print('smaller radius:',error)
Distance construction takes O(n²) work. Floyd–Warshall takes O(n³). The bounded Jacobi routine permits O(n²) rotations and scans O(n²) off-diagonal entries per rotation, giving an O(n⁴) worst-case work bound for this particular solver. Storage is O(n²). Those implementation bounds should not be replaced by a library’s more efficient solver estimates.
We report relative strain, the Frobenius error between B and the embedded Gram matrix divided by the Frobenius norm of B. The distance RMSE directly compares embedded distances with the graph distances:
These are different objectives. The spectral construction optimizes a Gram-matrix approximation. It does not directly minimize this distance RMSE or the original paper’s separately discussed residual-variance diagnostic.
Watch the radius create a shortcut
ambient endpoint distance: 2.0
radius / dimensions: 1 1 edges: 6
endpoint graph / embedding: 6.0 6.0
strain / distance RMSE / negative spectrum: 0.0 0.0 0
radius / dimensions: 2 1 edges: 13
endpoint graph / embedding: 2.0 2.642636
strain / distance RMSE / negative spectrum: 0.628116 0.85936 3
radius / dimensions: 3 2 edges: 21
endpoint graph / embedding: 2.0 2.0
strain / distance RMSE / negative spectrum: 0.0 0.0 0
smaller radius: radius graph is disconnected; no automatic bridge is inserted
At radius one, there are exactly six edges, making one path through all seven records. Its ideal one-dimensional coordinates are the centered path positions −3, −2, −1, 0, 1, 2, 3, up to reflection. Their Gram matrix has one nonzero eigenvalue, 28. Endpoint distance is six in both the graph and its one-dimensional representation. Displayed zero errors are rounded to six decimal places; calculations use floating point.
At radius two, thirteen edges are present. The two endpoints connect directly across the gap, so their graph distance becomes two. The resulting distances have three substantial negative Gram eigenvalues. The one-dimensional Euclidean representation cannot preserve them all: its endpoint distance is about 2.643, and its distance RMSE is about 0.859.
At radius three, the graph is complete. Shortest-path distances are just the original Euclidean distances, and two output dimensions reconstruct the planar geometry up to a rigid transformation. This is no longer an unfolding of the path. At radius 0.9, the graph disconnects and the program reports the problem.
A separate four-point square with radius one makes this distinction concrete. Its cycle graph has centered eigenvalues 2, 2, 0 and −1. Keeping two dimensions includes the whole positive block. Keeping one splits it: for the listed square order (0,0),(1,0),(1,1),(0,1), the program places original records 0 and 2 two units apart; cyclically reordering rows as (1,2,3,0) and mapping back can make that distance zero. Both one-dimensional fits have relative strain sqrt(5)/3. This is a change in the retained subspace, not just a reflection of the same line.
The seven-point walkway is a finite graph example, not evidence that a polygon with sharp corners satisfies a smooth-manifold convergence theorem. Its purpose is to make the local-connection choice visible.
A well-solved embedding can represent the wrong distances
The neighborhood has to be large enough to connect sampled routes but small enough to avoid shortcuts between nearby folds. Sparse sampling, noise or uneven density can make those requirements conflict. The original convergence discussion depends on sampling density, curvature, branch separation and geometric assumptions; it is not a recovery promise for every point cloud. Original paper, convergence discussion and note 18
Local Euclidean structure also does not imply global Euclidean distance geometry. A circle has local one-dimensional charts, but opening it into a line requires a cut and changes some relationships. A low embedding error against a graph says that graph was represented well; it does not establish that the graph matches the unknown generating process.
Scaling and distance choices enter before the graph is built. Changing a measurement’s unit can alter edges, shortest paths and every final coordinate. Record preprocessing, radius, connectivity, the retained spectrum and sensitivity to nearby settings. Inspect actual neighbors across apparent folds rather than relying solely on a visually tidy two-dimensional plot.
The example has no noise model, automatic dimension selection or prediction rule for future points. Adding records and refitting can change the entire embedding. Comparing two runs requires a geometry-aware alignment or an invariant such as pairwise distances; raw axes can flip or rotate without a substantive change.
Check the geometry before trusting the coordinates
1. Why are the endpoints two units apart in one description and six in another?
Answer: Two is the ambient straight-line distance. Six is the route length in the radius-one neighborhood graph. The embedding targets the second quantity because that graph defines the paths we permit.
2. Does a tiny eigenpair residual prove the neighborhood radius was correct?
Answer: No. It checks the numerical eigendecomposition of the chosen Gram matrix. An accurately solved matrix can come from a graph containing the wrong shortcut.
3. What do the three negative eigenvalues at radius two tell us?
Answer: Beyond the declared numerical tolerance, the centered graph-distance matrix is not positive semidefinite. Those distances cannot all be realized exactly by Euclidean coordinates of any dimension. Discarding negative directions produces an approximation with measurable error.
4. A second run negates every one-dimensional coordinate. Was the geometry lost?
Answer: No. Reflection preserves all pairwise distances and inner products. Compare those invariants or align coordinates before judging a change. A genuinely changed graph can, however, alter the geometry itself.
The preserved relationship distinguishes the method
Isomap’s contribution is a global geometric representation built from local connectivity and graph route lengths. The neighborhood-to-graph step connects it to shortest-path search; the final centered spectrum connects it to PCA and kernel PCA. Those connections explain the computation more precisely than calling every nonlinear picture an “unfolded manifold.”
Other methods preserve different relations. The fixed guide presents locally linear embedding through local reconstruction weights and a global eigenproblem. Isomap instead feeds estimated global route distances into MDS. The choice of what to preserve is part of the model, not merely a faster or slower implementation choice. Manifold guide, Isomap and LLE sections
A useful next experiment is to compare the graph and embedding as a few sample points are removed near a bend. Report connectivity, shortcuts and distortion, then ask whether the retained coordinates help the downstream task. Cluster evaluation explains why an attractive grouping in an embedding is not, by itself, evidence of the desired categories.
Make a prediction, then check
The eigenpair residual is tiny after a neighborhood shortcut is added. What does that establish?
Learning objectives
- Distinguish ambient distance, graph routes and an assumed manifold’s geodesics.
- Derive double centering and reconstruct an embedding from positive eigenpairs.
- Diagnose shortcuts, disconnected graphs and non-Euclidean graph distances.
Prerequisites & connections
Explore related knowledge →References
- A Global Geometric Framework for Nonlinear Dimensionality Reduction
Joshua B. Tenenbaum; Vin de Silva; John C. Langford · 2000 - scikit-learn 1.7 — Manifold learning
scikit-learn developers
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-05 · Codex technical check: primary-source locations, original runnable models, independent mathematical and computational references, bilingual review and second-agent cross-checks; not independent human peer review.
- Six tests pass. Six path models match exact graph distances, centered coordinate outer products and the closed nonzero eigenvalue n(n²−1)/12. Three complete graphs match direct centered-coordinate Gram matrices and independent two-by-two scatter polynomial roots, as well as all reconstructed distances.
- Independent priority-queue shortest paths match four graph reports. A four-cycle circulant Fourier calculation gives eigenvalues 2,2,0,-1, relative strain 1/3 and distance RMSE sqrt(2/3)(sqrt(2)-1), testing negative spectrum and a repeated positive eigenspace without relying on a Jacobi implementation.
- Verified six-to-thirteen edge shortcut, endpoint graph distance six-to-two, three negative directions, disconnected radius, unresolved output rank, duplicates, huge integers, nonfinite data, booleans and input preservation. The full main program prints eleven verified lines; displayed zeros are rounded floating results.
- Both full articles share six displays, six standard anchors, four answered exercises and identical complete Python. Strict MDX/KaTeX with the shared fatal guard and actual React HTML pass. Source-process details remain metadata; established Humanizer editing preserves concrete geometry and conditions. Written pending independent peer review.
- Peer review prompted an explicit piecewise-smooth path convention and a distinction between rotations of a fully retained repeated eigenspace and a cutoff through a repeated block. A four-cycle row-permutation regression gives mapped pair distances 2 versus 0 while both optimal relative strains equal sqrt(5)/3. Program unchanged; both languages and the existing Fourier test now cover this case.
- Six final author tests pass. Independent enumeration of 75 simple legal paths and four exact Leibniz characteristic polynomials check eight fits on stars, a 2-by-3 grid and a bent path. Verified graph edges and all distances, anchored-and-centered Gram matrices, full spectra, negative counts, retained eigen-equations, and eight optimal PSD truncation-error certificates plus distance RMSE. This does not repeat Floyd, heap shortest paths, Jacobi rotations, 2-by-2 scatter spectra or a Fourier cycle oracle.
- Fully reread both articles, code, six formulas, four answered exercises and final metadata. Checked manifold/graph distinction, smoothness and sampling assumptions, double centering and positive-spectrum conditions, radius boundaries, numerical guards, budgeted eigensolver work and original diagnostic scope. Independent strict MDX/KaTeX plus actual React HTML/MathML passes six matching displays, six anchors and four answers.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
- Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
Source locations checked:
- A Global Geometric Framework for Nonlinear Dimensionality Reduction · Actually read five-page original reprint text on the mirror. Title/authors begin at lines 57–60; earlier references and received date belong to the preceding article and are not attributed to Isomap. Science footer gives 22 December 2000. Read method lines 126–166, eigen construction 194–199, scope 207–226, Table 1 lines 412–435, notes 16–18 lines 338–365 (Floyd, elementwise squared distances and double centering, sampling/curvature/branch-separation conditions), and diagnostic note 42 lines 464–469. No visual figure inspection or full supplementary proof claimed. MIT archive URL failed with verified HTTP 404; its alternative path also failed. Original figures/data are not reused. Our relative Frobenius strain and direct distance RMSE are explicitly distinct from the paper’s residual variance.
- scikit-learn 1.7 — Manifold learning · Actually read fixed /1.7/ guide displaying 1.7.2: lines 90–91 nonlinear structure framing; Isomap lines 104–126, neighborhood, shortest paths, spectrum and original citation; LLE lines 127–140, weights and eigenproblem. Did not adopt guide complexity estimates for our distinct Jacobi implementation, and did not adopt its informal local-distance description as a full definition of LLE. Fixed Isomap API fetch failed and is not counted as a read source. No sklearn program run.
- A Global Geometric Framework for Nonlinear Dimensionality Reduction · Independently opened the five-page original Science reprint on the stated mirror. Read title/authors beginning at line 57 and 22 December 2000 footer (not the preceding article’s received date), neighborhood/graph/MDS steps at lines 137–166, geometric scope and convergence at 194–222, notes 16–18 (338–365) and Table 1 (412–435). Text extraction only; no original figure or supplementary-proof inspection and no original experiment reproduced. Distinguish Gram strain, distance RMSE and residual variance.
- scikit-learn 1.7 — Manifold learning · Independently read fixed /1.7 guide displaying 1.7.2, Isomap stages and citation (104–126), LLE reconstruction/eigenproblem description (127–140). No library runtime; tutorial solver complexity remains its own bounded Jacobi O(n^4) count.
Related topics