Module contents
Lesson 15 of 24Core 100 min

Multidimensional scaling, kernel PCA and Isomap

Multidimensional scaling, kernel PCA, Isomap and embedding quality.

After this lesson you can

  • Derive classical and metric multidimensional scaling.
  • Explain kernel PCA and nonlinear embeddings.
  • Apply Isomap and assess embedding quality.

Before you start

Motivation: from distances to a map

A table of flight distances between cities has no coordinates, yet anyone can draw an approximate map: place two cities, add a third at the table’s distances, and continue until everything fits. This lesson solves that general problem: given a dissimilarity matrix δij\delta_{ij} between nn objects, find points y1,…,yn∈Rd\vb{y}_1, \dots, \vb{y}_n \in \R^d with ∥yi−yj∥≈δij\norm{\vb{y}_i - \vb{y}_j} \approx \delta_{ij}. With d=2d = 2 or 33 this visualizes data; with larger dd, it compresses them.

Three reasons favor distances over coordinates:

  • Data may have no coordinates. Dissimilarities for mixed data (Gower, Jaccard, edit distance) produce a table of δij\delta_{ij} for nonvector objects. Multidimensional scaling bridges that table to a drawable, clusterable space.
  • PCA is linear. It seeks the subspace preserving most variance. If data lie on a curved surface (the manifold hypothesis: pp-dimensional data live near a manifold of intrinsic dimension d≪pd \ll p), planar projection crushes separate layers together. Face images with varying pose and lighting are the classic example: Tenenbaum, de Silva and Langford (2000) used 698 synthetic 64-by-64 images, 698 points in R4096\R^{4096}, varying only left-to-right pose, up-down pose and light direction. With Isomap and 6 neighbors, each axis of their three-dimensional embedding correlated strongly with one degree of freedom.
  • The kernel trick makes any method using only dot products nonlinear. This is kernel machines’ idea applied to PCA.

The lesson develops four pieces, each building on the previous:

MethodInputCentral objectNonlinear?
Classical MDSdistances δij\delta_{ij}B=−12JD(2)J\mat{B} = -\tfrac12\mat{J}\mat{D}^{(2)}\mat{J} and spectrumno: with Euclidean distances it is PCA
Metric MDS (SMACOF)distances (and weights)stress ∑(δij−dij)2\sum (\delta_{ij} - d_{ij})^2, minimized by majorizationyes, but optimization is nonconvex
Kernel PCAkernel k(x,x′)k(\vb{x}, \vb{x}')K~=JKJ\tilde{\mat{K}} = \mat{J}\mat{K}\mat{J} and spectrumyes, via feature space
Isomapneighbor graphgraph geodesic distances, then classical MDSyes, via geodesics

Finally we study measures for judging any embedding: a pretty picture does not prove that it preserves anything.

Classical MDS: from double centering to the Gram matrix

First see the result. The figure takes 14 cities, computes pairwise distances (Earth-surface distance or the chord through the planet), and asks classical MDS for a flat map reproducing them. The algorithm knows no latitude or longitude: only the table.

InteractiveA map from distances
Map reconstructed by classical MDS from the table (units of 1,000 km)
MadLisParLonDubAmsBerRomVieVarEstAteOslHel
  • city under MDS (reflected and rotated for orientation)
  • selected pair
Eigenvalues of B=−12JD(2)J\mat{B} = -\tfrac12\mat{J}\mat{D}^{(2)}\mat{J} (signed logarithmic scale)
  • the two map axes
  • other positive eigenvalues
  • negative eigenvalues
Cityes
Distance
0 %
Normalized 2D map stress0.0019
Mass of first 2 axes99.9 %
Negative spectral mass0.29 %
Mad to Ber: table · map (km)1869 · 1869
Tiny negative eigenvalues (0.29 % of mass): at this scale Earth’s surface is nearly flat and its distances nearly Euclidean.
Left: classical MDS map (rotated and reflected for orientation, since distances determine neither). Right: eigenvalues of B=−12JD(2)J\mat{B} = -\tfrac12\mat{J}\mat{D}^{(2)}\mat{J} on signed logarithmic scale: blue map axes, green other positive, red negative. Geographic coordinates are approximate and distances use haversine (radius 6371 km), not a table. Try four things: (1) Europe with '3D chord': distances are exactly Euclidean in R3\R^3 and no eigenvalues are negative; (2) 'World' with chord: three large eigenvalues appear because Earth is three-dimensional and the flat map keeps only two; (3) 'World' with 'Great circle': large negative eigenvalues appear because these distances cannot come from any Euclidean point set; (4) increase relative noise σ\sigma: perturbed distances cease to be Euclidean and negative mass appears.

Two phenomena the figure reveals and this section explains: Europe’s map is very good (at that scale Earth is nearly flat), the world map is not, and in that case B\mat{B}‘s spectrum has negative eigenvalues. To understand why, open the machine.

Coordinates are in dot products

A set of points is determined by distances only up to isometries (translations, rotations and reflections), so fix translation by putting the centroid at the origin. Write squared distance using dot products:

δij2=∥xi−xj∥2=∥xi∥2+∥xj∥2−2 xi⊤xj.\delta_{ij}^2 = \norm{\vb{x}_i - \vb{x}_j}^2 = \norm{\vb{x}_i}^2 + \norm{\vb{x}_j}^2 - 2\,\vb{x}_i\T\vb{x}_j.

If we could isolate xi⊤xj\vb{x}_i\T\vb{x}_j we would have the Gram matrix G=XX⊤\mat{G} = \mat{X}\mat{X}\T, from which coordinates follow by spectral decomposition. Terms ∥xi∥2\norm{\vb{x}_i}^2 and ∥xj∥2\norm{\vb{x}_j}^2 get in the way, but depend only on row or column. Subtracting each row and column mean removes them: double centering.

Proof

Let G=XX⊤\mat{G} = \mat{X}\mat{X}\T and q=(G11,…,Gnn)⊤\vb{q} = (G_{11}, \dots, G_{nn})\T be the squared-norm vector. The identity above for all pairs reads D(2)=q1⊤+1q⊤−2G\mat{D}^{(2)} = \vb{q}\vb{1}\T + \vb{1}\vb{q}\T - 2\mat{G}. Multiply left and right by J\mat{J}. Since J1=0\mat{J}\vb{1} = \vb{0} and 1⊤J=0⊤\vb{1}\T\mat{J} = \vb{0}\T, the first two terms vanish: JD(2)J=−2JGJ\mat{J}\mat{D}^{(2)}\mat{J} = -2\mat{J}\mat{G}\mat{J}, namely B=JGJ=(JX)(JX)⊤\mat{B} = \mat{J}\mat{G}\mat{J} = (\mat{J}\mat{X})(\mat{J}\mat{X})\T. If 1⊤X=0\vb{1}\T\mat{X} = \vb{0}, then JX=X−1n1(1⊤X)=X\mat{J}\mat{X} = \mat{X} - \tfrac1n\vb{1}(\vb{1}\T\mat{X}) = \mat{X}.

∎

Immediate consequence: with Euclidean distances, B\mat{B} is positive semidefinite with rank at most min⁡(p,n−1)\min(p, n - 1), and V1:dΛ1:d1/2\mat{V}_{1:d}\mat{\Lambda}_{1:d}^{1/2} reproduces original dot products projected onto their first dd principal axes. Follow each calculation on a hand-checkable example.

InteractiveDouble centering step by step
Step 1.D=(δij)\text{Step 1.}\quad \mat{D} = (\delta_{ij})
Distance table
044.473.612
4023.614.47
4.47202.244
3.613.612.2402.24
24.4742.240
Table of n=5n = 5 points. It comes from coordinates unseen by the method.
Distance set
Step 1 of 7: Distance table
Trace of B\mat{B} · 1n∑i<jδij2\frac1n\sum_{i<j}\delta_{ij}^223.200 · 23.200
Eigenvalues of B\mat{B}
16.007.20000
This is all the method knows: neither coordinates nor axes.
Three distance sets: three points on a line (x=0,1,3x = 0, 1, 3), five plane points, and 'Impossible distances' (δ12=δ23=1\delta_{12} = \delta_{23} = 1 and δ13=3\delta_{13} = 3, violating triangle inequality). Advance: square distances, subtract each column mean, each row mean, multiply by −12-\tfrac12 and diagonalize. In the first two sets B\mat{B} is the centered points' Gram matrix and eigenvalues are nonnegative; the third has a negative eigenvalue. Check also that trace of B\mat{B} equals 1n∑i<jδij2\tfrac1n\sum_{i<j}\delta_{ij}^2.

Classical MDS is PCA

If data are vectors and distances Euclidean, classical MDS does nothing PCA did not already do.

Proof

By the previous theorem, B=XX⊤=US2U⊤\mat{B} = \mat{X}\mat{X}\T = \mat{U}\mat{S}^2\mat{U}\T. This is a spectral decomposition of B\mat{B}: eigenvectors are columns of U\mat{U} and eigenvalues sj2s_j^2. Thus V1:dΛ1:d1/2=U1:dS1:d\mat{V}_{1:d}\mat{\Lambda}_{1:d}^{1/2} = \mat{U}_{1:d}\mat{S}_{1:d}, and since XW=US\mat{X}\mat{W} = \mat{U}\mat{S} those coordinates are XW1:d\mat{X}\mat{W}_{1:d}. Finally X⊤X=WS2W⊤\mat{X}\T\mat{X} = \mat{W}\mat{S}^2\mat{W}\T.

∎

This is the same nn versus pp duality used by high-dimensional PCA: diagonalizing the n×nn \times n dot-product matrix or p×pp \times p covariance matrix agrees up to factor n−1n - 1, so choose the smaller. Now we also know the solution is best possible in a precise sense:

Notice the objective: dot-product error, quadratic in distances. A large distance contributes far more than a small one, so when no exact map exists classical MDS prioritizes large distances. This motivates metric MDS, measuring errors in distances themselves.

When B\mat{B} has negative eigenvalues

When does a configuration exactly reproduce a distance table? Schoenberg’s theorem (1935), as formulated by Young and Householder (1938), answers using B\mat{B}.

Proof

If Δ\mat{\Delta} comes from points, B\mat{B} is a Gram matrix by the preceding theorem and is positive semidefinite. Conversely, let B⪰0\mat{B} \succeq \mat{0} and write B=YY⊤\mat{B} = \mat{Y}\mat{Y}\T with Y∈Rn×r\mat{Y} \in \R^{n \times r}, r=rank⁡Br = \rank\mat{B} (spectral decomposition with square roots of eigenvalues). Show row distances of Y\mat{Y} are δij\delta_{ij}. Let mi=1n∑lδil2m_i = \tfrac1n\sum_l\delta_{il}^2 and m=1n2∑l,l′δll′2m = \tfrac1{n^2}\sum_{l,l'}\delta_{ll'}^2. Expanding double centering, Bij=−12(δij2−mi−mj+m)B_{ij} = -\tfrac12\big(\delta_{ij}^2 - m_i - m_j + m\big); with δii=0\delta_{ii} = 0, Bii=mi−m2B_{ii} = m_i - \tfrac m2. Then Bii+Bjj−2Bij=(mi+mj−m)+δij2−mi−mj+m=δij2B_{ii} + B_{jj} - 2B_{ij} = (m_i + m_j - m) + \delta_{ij}^2 - m_i - m_j + m = \delta_{ij}^2. The left-hand side is ∥yi−yj∥2\norm{\vb{y}_i - \vb{y}_j}^2. For minimum dimension: any exact configuration, after centering, has Gram matrix B\mat{B} and rank B\mat{B}.

∎

Practical consequence: a negative eigenvalue of B\mat{B} certifies dissimilarities are not Euclidean, and negative mass measures the departure. The double-centering figure showed a useful identity: trace of B\mat{B}, sum of all eigenvalues, is 1n∑i<jδij2\tfrac1n\sum_{i<j}\delta_{ij}^2 (from Bii=mi−m/2B_{ii} = m_i - m/2, tr⁡B=∑imi−nm2=nm2\tr\mat{B} = \sum_i m_i - \tfrac{nm}{2} = \tfrac{nm}{2}, and nm/2=1n∑i<jδij2nm/2 = \tfrac1n\sum_{i<j}\delta_{ij}^2).

Typical causes of negative eigenvalues are noisy dissimilarities, a non-Euclidean metric (Manhattan, edit or great-circle distance…) or a dissimilarity that is not even a distance (violating the triangle inequality). Options:

  1. Ignore them, as classical MDS does: keep the dd largest positive eigenvalues. Reasonable if negative mass is small relative to retained axes.
  2. Add a constant off diagonal. Lingoes (1971) adds it to squared dissimilarities, δ~ij2=δij2+2c\tilde\delta_{ij}^2 = \delta_{ij}^2 + 2c, with cc equal to the absolute value of B\mat{B}‘s most negative eigenvalue (double centering −12⋅2c(11⊤−I)-\tfrac12\cdot 2c(\vb{1}\vb{1}\T - \mat{I}) yields cJc\mat{J}, shifting every eigenvalue of B\mat{B} except that of 1\vb{1} by cc); Cailliez (1983) adds it to dissimilarities, δij+c\delta_{ij} + c, and proved the smallest cc making them Euclidean is the largest eigenvalue of a 2n2n matrix. Both change geometry by equally inflating small distances.
  3. Do not require semidefiniteness: directly minimize discrepancy between δij\delta_{ij} and dij(Z)d_{ij}(\mat{Z}), metric MDS in the next section.

The next lab implements classical MDS from scratch, checks the theorem with Euclidean points and applies it to 12 cities with great-circle distances.

[ ]Classical MDS from scratch: Euclidean points and 12 citiesBrowser
import numpy as np
from scipy.spatial.distance import pdist, squareform

def classical_mds(D, d):
    """MDS clásico: doble centrado de D^2, autovalores en orden decreciente, coordenadas V_d sqrt(lambda_d)."""
    n = len(D)
    J = np.eye(n) - np.ones((n, n)) / n
    B = -0.5 * J @ (D ** 2) @ J
    lam, V = np.linalg.eigh(B)
    o = np.argsort(lam)[::-1]
    lam, V = lam[o], V[:, o]
    return V[:, :d] * np.sqrt(np.maximum(lam[:d], 0.0)), lam

# 1) con distancias euclídeas recupera la configuración salvo isometría
rng = np.random.default_rng(0)
X = rng.standard_normal((30, 3)) @ np.diag([3.0, 2.0, 0.5])
D = squareform(pdist(X))
Y, lam = classical_mds(D, 3)
print("autovalores de B (3 mayores, resto):", np.round(lam[:3], 3), f"{abs(lam[3:]).max():.1e}")
print("error máximo en las distancias:", f"{np.abs(squareform(pdist(Y)) - D).max():.1e}")

# 2) con distancias de círculo máximo entre 12 ciudades (coordenadas aproximadas)
CIT = {"Madrid": (40.42, -3.70), "Nueva York": (40.71, -74.01), "São Paulo": (-23.55, -46.63),
       "Tokio": (35.68, 139.65), "Sídney": (-33.87, 151.21), "El Cabo": (-33.92, 18.42),
       "Moscú": (55.76, 37.62), "Bombay": (19.08, 72.88), "Los Ángeles": (34.05, -118.24),
       "El Cairo": (30.04, 31.24), "Pekín": (39.90, 116.41), "Buenos Aires": (-34.60, -58.38)}
names = list(CIT)
ll = np.radians(np.array([CIT[c] for c in names]))
la, lo = ll[:, 0], ll[:, 1]
h = np.sin((la[:, None] - la[None]) / 2) ** 2 + np.cos(la)[:, None] * np.cos(la)[None] * np.sin((lo[:, None] - lo[None]) / 2) ** 2
Dc = 2 * 6371 * np.arcsin(np.sqrt(h)) / 1000          # miles de km
Yc, lamc = classical_mds(Dc, 2)
print("autovalores de B:", np.round(lamc, 1))
print(f"masa negativa: {-lamc[lamc < 0].sum() / abs(lamc).sum():.1%} de la masa espectral")
print("traza de B =", round(lamc.sum(), 2), "y (1/n) sum_i<j d^2 =", round((Dc[np.triu_indices(12, 1)] ** 2).sum() / 12, 2))
print("distancia Madrid-Pekín: tabla", round(Dc[0, 10] * 1000), "km, mapa", round(np.linalg.norm(Yc[0] - Yc[10]) * 1000), "km")

With Euclidean points, remaining eigenvalues are zero up to rounding errors of order 10−1310^{-13} and distances reproduce exactly. Cities show two effects: B\mat{B} has five negative eigenvalues, totaling 17.7% of spectral mass (the largest, −104.2-104.2, exceeds half the third positive eigenvalue, 192.0192.0), and the flat map distorts: Madrid and Beijing are 9222 km apart in the table and 11725 km on the map. This is not an algorithm failure. Great-circle distance lives on a sphere with positive Gaussian curvature, and Gauss’s theorema egregium says a nonzero-curvature surface cannot be flattened without distorting distances. No flat Earth map is exact; choose which distances to sacrifice. Negative eigenvalues say something stronger: by Schoenberg’s criterion, no set of 12 points in any Euclidean space of any dimension has those surface distances. Chords through the planet are Euclidean in R3\R^3, and their negative mass disappears (the figure’s ‘3D chord’ option).

Metric MDS and stress: SMACOF as majorization

Classical MDS minimizes a convenient quantity (strain, leading to an eigenproblem) that is less natural: it penalizes large-distance errors more and squares distances. The direct formulation minimizes error in distances themselves.

Unlike classical MDS, this is not an eigenproblem: σ\sigma is nonconvex with local minima. It does not require Euclidean dissimilarities, and large- and small-distance errors have equal weight (other wijw_{ij} can emphasize nearby ones). The classic algorithm is SMACOF (Scaling by MAjorizing a COmplicated Function), an MM instance: replace the function by a quadratic majorizer touching at the current point, minimize it easily, repeat.

Deriving the majorizer

With wij=1w_{ij} = 1 and centered Z\mat{Z} (zero-mean columns, without changing distances),

σ(Z)=∑i<jδij2+∑i<jdij2(Z)−2∑i<jδijdij(Z).\sigma(\mat{Z}) = \sum_{i<j}\delta_{ij}^2 + \sum_{i<j}d_{ij}^2(\mat{Z}) - 2\sum_{i<j}\delta_{ij}d_{ij}(\mat{Z}).

Treat the three terms separately.

  1. The first is constant.
  2. The second is quadratic: ∑i<jdij2(Z)=n∑i∥zi∥2−∥∑izi∥2=n∥Z∥F2\sum_{i<j}d_{ij}^2(\mat{Z}) = n\sum_i\norm{\vb{z}_i}^2 - \norm{\sum_i\vb{z}_i}^2 = n\norm{\mat{Z}}_F^2 for centered Z\mat{Z}.
  3. The third is hard because dij(Z)d_{ij}(\mat{Z}) is a norm. Write it as a quadratic form. Define B(Z)\mat{B}(\mat{Z}) with Bij(Z)=−δij/dij(Z)B_{ij}(\mat{Z}) = -\delta_{ij}/d_{ij}(\mat{Z}) if i≠ji \ne j and dij(Z)>0d_{ij}(\mat{Z}) > 0 (and 00 if dij=0d_{ij} = 0), and Bii=−∑j≠iBijB_{ii} = -\sum_{j\ne i}B_{ij}. It resembles a graph Laplacian weighted by δij/dij\delta_{ij}/d_{ij}, and for any two configurations tr⁡(Z⊤B(Y)Y)=∑i<jδijdij(Y)⟨zi−zj,yi−yj⟩\tr(\mat{Z}\T\mat{B}(\mat{Y})\mat{Y}) = \sum_{i<j}\frac{\delta_{ij}}{d_{ij}(\mat{Y})}\inner{\vb{z}_i - \vb{z}_j}{\vb{y}_i - \vb{y}_j}. With Y=Z\mat{Y} = \mat{Z} that sum is exactly ∑i<jδijdij(Z)\sum_{i<j}\delta_{ij}d_{ij}(\mat{Z}).

Cauchy-Schwarz, dij(Z) dij(Y)≥⟨zi−zj,yi−yj⟩d_{ij}(\mat{Z})\,d_{ij}(\mat{Y}) \ge \inner{\vb{z}_i - \vb{z}_j}{\vb{y}_i - \vb{y}_j}, after division by dij(Y)>0d_{ij}(\mat{Y}) > 0 and multiplication by δij≥0\delta_{ij} \ge 0, gives −δijdij(Z)≤−δij⟨zi−zj,yi−yj⟩/dij(Y)-\delta_{ij}d_{ij}(\mat{Z}) \le -\delta_{ij}\inner{\vb{z}_i - \vb{z}_j}{\vb{y}_i - \vb{y}_j}/d_{ij}(\mat{Y}) (if dij(Y)=0d_{ij}(\mat{Y}) = 0 the majorizer term is 00 and the inequality trivial). Sum over pairs:

Iteration Zt+1=1nB(Zt)Zt\mat{Z}_{t+1} = \tfrac1n\mat{B}(\mat{Z}_t)\mat{Z}_t needs no learning step size and decreases stress each step. If σ(Zt)\sigma(\mat{Z}_t) is bounded below by 0 and nonincreasing, it converges; De Leeuw (1988) proves accumulation points of the sequence are stationary points of σ\sigma. It does not guarantee a global minimum, and in practice fails in two ways: convergence to another stationary point with higher stress, or such slow progress on a plateau that hundreds of iterations appear to stop.

InteractiveSMACOF: the majorizer in action
Configuration at iteration 0 (start: random 2); trail of each city
MadNYCSPaTokSydCabMosBomLACDMXCaiPekBsAsLag
Stress per iteration (log scale)
  • SMACOF stress
  • best of 4 starts
  • classical MDS (iteration 0)
Majorizer at the current step: α=0\alpha = 0 is Zt\mat{Z}_t and α=1\alpha = 1 is Zt+1\mat{Z}_{t+1}
  • stress σ
  • majorizer τ(·, Zₜ)
Initial configuration
Iteration 0 of 150
Raw stress σ(Zt)\sigma(\mat{Z}_t) (10⁶ km²)3639.27
Normalized stress σ/∑δ2\sqrt{\sigma/\sum\delta^2}0.5947
Majorizer at next step, τ(Zt+1,Zt)\tau(\mat{Z}_{t+1}, \mat{Z}_t)2397.58
Stress at next step, σ(Zt+1)\sigma(\mat{Z}_{t+1})1985.57
After 3000 iterations: this start · best272.96 · 272.96
Starting stress: 3639.3. Press play and see the majorizer touch stress at α = 0 and reach its minimum at α = 1.
Great-circle distances between the previous interactive's 14 cities are non-Euclidean, so minimum planar stress is positive. Play 150 Guttman iterations from four starts: classical MDS and three random normal configurations. Right top: stress per iteration; bottom: current stress σ\sigma and majorizer τ\tau along the line from Zt\mat{Z}_t to Zt+1\mat{Z}_{t+1}: majorizer touches σ\sigma at α=0\alpha = 0, stays above and is minimized at α=1\alpha = 1. Initial start 'Random 2' is slow: take it to iteration 150 and compare with the others; the readout says where it ends after 3000.

Nonmetric MDS

When only dissimilarity order matters (for example subjective similarity ratings), replace δij\delta_{ij} by disparities d^ij=f(δij)\hat d_{ij} = f(\delta_{ij}), with monotone increasing ff fitted alongside configuration (isotonic regression), and minimize stress of dij(Z)d_{ij}(\mat{Z}) against d^ij\hat d_{ij} (Shepard, 1962; Kruskal, 1964). Alternate a Guttman transform and isotonic regression. In sklearn this is MDS(metric=False); we do not implement it here.

Lab: SMACOF from scratch

[ ]SMACOF with the Guttman transformBrowser
import numpy as np

iu = np.triu_indices(len(Dc), 1)
def dist(Z):
    return np.sqrt(((Z[:, None] - Z[None]) ** 2).sum(-1))

def stress(D, Z):
    return ((D - dist(Z))[iu] ** 2).sum()

def guttman(D, Z):
    """Transformada de Guttman con pesos unitarios: Z+ = B(Z) Z / n."""
    d = dist(Z)
    with np.errstate(divide="ignore", invalid="ignore"):
        B = np.where(d > 0, -D / d, 0.0)
    np.fill_diagonal(B, 0.0)
    np.fill_diagonal(B, -B.sum(1))
    return B @ Z / len(Z)

def smacof(D, Z0, iters):
    Z = Z0 - Z0.mean(0)
    hist = [stress(D, Z)]
    for _ in range(iters):
        Z = guttman(D, Z)
        hist.append(stress(D, Z))
    return Z, np.array(hist)

S2 = (Dc[iu] ** 2).sum()
Z, hist = smacof(Dc, Yc, 300)
print(f"desde el MDS clásico: stress {hist[0]:.1f} -> {hist[-1]:.1f}; normalizado {np.sqrt(hist[0]/S2):.3f} -> {np.sqrt(hist[-1]/S2):.3f}")
print("¿monótono no creciente?", bool(np.all(np.diff(hist) <= 1e-12)))
rng = np.random.default_rng(0)
finales, pasos = [], []
for s in range(6):
    Z0 = rng.standard_normal((12, 2))
    Zs, hs = smacof(Dc, Z0, 500)
    finales.append(hs[-1])
    pasos.append(np.abs(guttman(Dc, Zs) - Zs).max())          # tamaño del paso siguiente: ~0 en un punto fijo
    assert np.all(np.diff(hs) <= 1e-12)
print("stress final desde 6 arranques aleatorios:", np.round(sorted(finales), 1))
print(f"mayor desplazamiento en una iteración más: {max(pasos):.0e}")
from sklearn.manifold import smacof as sk_smacof
Zk, stk = sk_smacof(Dc, metric=True, n_components=2, init=Yc.copy(), n_init=1, max_iter=300, eps=1e-12, normalized_stress=False)[:2]
print("sklearn.manifold.smacof desde el mismo arranque:", round(stk, 1), "| el nuestro:", round(hist[-1], 1))
Zb, stb = sk_smacof(Dc, metric=True, n_components=2, n_init=8, max_iter=500, eps=1e-9, random_state=0, normalized_stress=False)[:2]
print("sklearn.manifold.smacof, mejor de 8 arranques aleatorios:", round(stb, 1))

Three readings. First, stress never increases for any of 7 starts (the assertion checks it): the theorem. Second, starting from classical MDS, normalized stress 0.258, and refining with SMACOF lowers it to 0.177. This is standard: classical MDS supplies a good start and SMACOF refines distances rather than strain. Third, random starts end at three distinct values (243.4, 251.7 and 367.0), not because iteration stopped early: one more iteration moves points at most 3⋅10−93 \cdot 10^{-9} (in thousands of km), essentially nothing. They are distinct stationary points, and the start determines which is reached. Thus practitioners repeat SMACOF from several starts and keep the best: n_init in sklearn.manifold.MDS and smacof, which with 8 random starts finds 243.4 here. Our result also matches sklearn from the same start, 243.4. The preceding figure shows the other failure with 14 cities: all four starts eventually reach the same stress, but one takes much longer than 150 iterations.

Kernel PCA

PCA projects onto linear directions. For two concentric rings no direction separates inner from outer, because both share a center: any line mixes them. What distinguishes them is radius, a nonlinear coordinate function. Schölkopf, Smola and Müller (1998) proposed applying nonlinear transformation ϕ\phi to feature space H\mathcal{H} and doing PCA there without ever calculating ϕ\phi.

Derivation

Let k(x,x′)=⟨ϕ(x),ϕ(x′)⟩k(\vb{x}, \vb{x}') = \inner{\phi(\vb{x})}{\phi(\vb{x}')} be a positive semidefinite kernel (common kernels) and K=(k(xi,xj))\mat{K} = (k(\vb{x}_i, \vb{x}_j)) its data kernel matrix. First assume feature images are centered, ∑iϕ(xi)=0\sum_i\phi(\vb{x}_i) = \vb{0} (removed below). Covariance in H\mathcal{H} is C=1n∑iϕ(xi)ϕ(xi)⊤\mathcal{C} = \tfrac1n\sum_i\phi(\vb{x}_i)\phi(\vb{x}_i)\T (operator v↦1n∑i⟨ϕ(xi),v⟩ϕ(xi)\vb{v} \mapsto \tfrac1n\sum_i\inner{\phi(\vb{x}_i)}{\vb{v}}\phi(\vb{x}_i)), and seek eigenvectors Cv=λv\mathcal{C}\vb{v} = \lambda\vb{v} with λ>0\lambda > 0.

Four steps lead to the definition.

1. The eigenvector is a combination of images. From Cv=λv\mathcal{C}\vb{v} = \lambda\vb{v} with λ>0\lambda > 0, rearrange v=1nλ∑i⟨ϕ(xi),v⟩ϕ(xi)\vb{v} = \tfrac1{n\lambda}\sum_i\inner{\phi(\vb{x}_i)}{\vb{v}}\phi(\vb{x}_i), so v=∑iαiϕ(xi)\vb{v} = \sum_i\alpha_i\phi(\vb{x}_i) for coefficients αi\alpha_i. Only nn images exist, so there are at most nn eigenvectors with λ>0\lambda > 0 (actually n−1n - 1 after centering), even if H\mathcal{H} is infinite-dimensional.

2. The eigenproblem. Project onto each image: ⟨ϕ(xl),Cv⟩=λ⟨ϕ(xl),v⟩\inner{\phi(\vb{x}_l)}{\mathcal{C}\vb{v}} = \lambda\inner{\phi(\vb{x}_l)}{\vb{v}} for every ll (equivalent to the original equation because both sides lie in the image span). The left side is 1n∑ik(xl,xi)∑mαmk(xi,xm)=1n(K2α)l\tfrac1n\sum_i k(\vb{x}_l, \vb{x}_i)\sum_m\alpha_m k(\vb{x}_i, \vb{x}_m) = \tfrac1n(\mat{K}^2\vb{\alpha})_l and right side λ(Kα)l\lambda(\mat{K}\vb{\alpha})_l. Thus K2α=nλKα\mat{K}^2\vb{\alpha} = n\lambda\mat{K}\vb{\alpha}. Any α\vb{\alpha} with Kα=nλα\mat{K}\vb{\alpha} = n\lambda\vb{\alpha} satisfies it; other solutions differ by a null-space vector β\vb{\beta} of K\mat{K}, generating ∑iβiϕ(xi)\sum_i\beta_i\phi(\vb{x}_i) with squared norm β⊤Kβ=0\vb{\beta}\T\mat{K}\vb{\beta} = 0, the same v\vb{v}. Solve Kα=μα\mat{K}\vb{\alpha} = \mu\vb{\alpha} with μ=nλ\mu = n\lambda.

3. Normalization. Require ∥v∥=1\norm{\vb{v}} = 1: 1=v⊤v=α⊤Kα=μ∥α∥21 = \vb{v}\T\vb{v} = \vb{\alpha}\T\mat{K}\vb{\alpha} = \mu\norm{\vb{\alpha}}^2. If α^\hat{\vb{\alpha}} is a unit eigenvector of K\mat{K}, use α=α^/μ\vb{\alpha} = \hat{\vb{\alpha}}/\sqrt\mu.

4. Projection. A point x\vb{x}‘s component on vj\vb{v}_j is ⟨vj,ϕ(x)⟩=∑iαjik(xi,x)\inner{\vb{v}_j}{\phi(\vb{x})} = \sum_i\alpha_{ji}k(\vb{x}_i, \vb{x}), using only the kernel. For a training point, zj(xl)=(Kαj)l=μjαjl=μj α^jlz_j(\vb{x}_l) = (\mat{K}\vb{\alpha}_j)_l = \mu_j\alpha_{jl} = \sqrt{\mu_j}\,\hat\alpha_{jl}: training scores are columns of A^M1/2\hat{\mat{A}}\mat{M}^{1/2}, as in classical MDS.

Centering in feature space

Images ϕ(xi)\phi(\vb{x}_i) are not centered and cannot even be calculated, but ϕ~(x)=ϕ(x)−ϕˉ\tilde\phi(\vb{x}) = \phi(\vb{x}) - \bar\phi, with ϕˉ=1n∑lϕ(xl)\bar\phi = \tfrac1n\sum_l\phi(\vb{x}_l), has a calculable kernel:

k~(x,x′)=k(x,x′)−1n∑lk(x,xl)−1n∑lk(xl,x′)+1n2∑l,mk(xl,xm).\tilde k(\vb{x}, \vb{x}') = k(\vb{x}, \vb{x}') - \tfrac1n\sum_l k(\vb{x}, \vb{x}_l) - \tfrac1n\sum_l k(\vb{x}_l, \vb{x}') + \tfrac1{n^2}\sum_{l,m}k(\vb{x}_l, \vb{x}_m).

On training data it is K~=JKJ\tilde{\mat{K}} = \mat{J}\mat{K}\mat{J}. A new point must be centered using training means: vector k(x)=(k(x,xi))i\vb{k}(\vb{x}) = (k(\vb{x}, \vb{x}_i))_i becomes k~(x)=k(x)−(1n1⊤k(x))1−1nK1+(1n21⊤K1)1\tilde{\vb{k}}(\vb{x}) = \vb{k}(\vb{x}) - \big(\tfrac1n\vb{1}\T\vb{k}(\vb{x})\big)\vb{1} - \tfrac1n\mat{K}\vb{1} + \big(\tfrac1{n^2}\vb{1}\T\mat{K}\vb{1}\big)\vb{1} and zj(x)=αj⊤k~(x)z_j(\vb{x}) = \vb{\alpha}_j\T\tilde{\vb{k}}(\vb{x}). Omitting this centering, for training or new points, is the most frequent kernel-PCA implementation error.

With linear kernel k(x,x′)=x⊤x′k(\vb{x}, \vb{x}') = \vb{x}\T\vb{x}', K~\tilde{\mat{K}} is the centered Gram matrix and kernel PCA is classical MDS, ordinary PCA. Generally kernel PCA is classical MDS of kernel distance dk2(x,x′)=k(x,x)+k(x′,x′)−2k(x,x′)=∥ϕ(x)−ϕ(x′)∥2d_k^2(\vb{x}, \vb{x}') = k(\vb{x}, \vb{x}) + k(\vb{x}', \vb{x}') - 2k(\vb{x}, \vb{x}') = \norm{\phi(\vb{x}) - \phi(\vb{x}')}^2, because double centering holds in any inner-product space and gives −12JDk(2)J=K~-\tfrac12\mat{J}\mat{D}_k^{(2)}\mat{J} = \tilde{\mat{K}} (Williams, 2002). The lesson’s three pieces are the same machine with different B\mat{B}.

Gaussian kernel on two rings

With k(x,x′)=e−γ∥x−x′∥2k(\vb{x}, \vb{x}') = e^{-\gamma\norm{\vb{x} - \vb{x}'}^2}, inverse width γ\gamma sets the scale of “similarity.” Two extremes follow from a calculation:

  • γ→0\gamma \to 0. e−γδ2=1−γδ2+O(γ2)e^{-\gamma\delta^2} = 1 - \gamma\delta^2 + \bigO(\gamma^2), so K≈11⊤−γD(2)\mat{K} \approx \vb{1}\vb{1}\T - \gamma\mat{D}^{(2)} and K~≈−γJD(2)J=2γB\tilde{\mat{K}} \approx -\gamma\mat{J}\mat{D}^{(2)}\mat{J} = 2\gamma\mat{B}. Kernel PCA approaches linear PCA (eigenvalues ≈2γλj(B)\approx 2\gamma\lambda_j(\mat{B})). Nonlinearity appears in higher-order terms, giving subsequent components.
  • γ→∞\gamma \to \infty. K→I\mat{K} \to \mat{I} (distinct points become almost orthogonal in H\mathcal{H}) and K~→J\tilde{\mat{K}} \to \mat{J}, whose n−1n - 1 nonzero eigenvalues all equal 1: no preferred directions, projection degenerates.

Between them is a useful range. Find it with the rings.

InteractiveKernel PCA on rings
Data in R2\R^2; background colors component 1 at each point in the plane
  • outer ring
  • inner ring
  • new point
Puntuaciones: componente 1 (horizontal) frente a componente 2 (vertical)
3.16
Horizontal component (and background color)
Vertical component
Eigenvalues μ1,…,μ4\mu_1, \dots, \mu_4 of K~=JKJ\tilde{\mat{K}} = \mat{J}\mat{K}\mat{J}
1: 22.412: 18.213: 17.804: 9.77
Best-threshold accuracy by component (green means separating)
1: 1.002: 0.633: 0.614: 0.69
Projection of the new point (za,zb)(z_a, z_b)(−0.12, −0.05)
The first component separates rings with one threshold: in feature space, distance to the center becomes a maximum-variance direction.
160 points in two concentric rings (radii 1 and 0.35, radial noise standard deviation 0.04). Slide γ\gamma and choose components to plot: background colors the plane by the first of the two. Inspect 'best threshold accuracy per component': at 1, that component alone separates rings. With initial γ≈3\gamma \approx 3 it is first; lower γ\gamma to 0.1 and separation moves to third, behind two linear components; raise it to 10 and it returns to third; near 50 none separates and all four eigenvalues converge. Disable 'Center kernel matrix': the first eigenvalue almost doubles because it captures mean of ϕ(xi)\phi(\vb{x}_i) images, not variance. Drag the black point: its projection (ring) uses the new-point formula with kernel centered by training means.

The lab quantifies the same on 200 points, checks the implementation against sklearn.decomposition.KernelPCA and measures what happens without centering the new-point kernel.

[ ]Kernel PCA from scratch and comparison with sklearnBrowser
import numpy as np
from scipy.spatial.distance import pdist, squareform
from sklearn.datasets import make_circles
from sklearn.decomposition import PCA, KernelPCA

def sq_dists(A, B):
    return np.maximum((A ** 2).sum(1)[:, None] + (B ** 2).sum(1)[None, :] - 2 * A @ B.T, 0.0)

class KPCA:
    """Kernel PCA con núcleo gaussiano exp(-gamma |x - y|^2): centrado en el espacio de características."""
    def __init__(self, gamma, d):
        self.gamma, self.d = gamma, d
    def fit(self, X):
        n = len(X)
        self.X = X
        self.K = np.exp(-self.gamma * sq_dists(X, X))
        J = np.eye(n) - np.ones((n, n)) / n
        mu, A = np.linalg.eigh(J @ self.K @ J)            # K~ alpha = mu alpha, mu = n lambda
        o = np.argsort(mu)[::-1][: self.d]
        self.mu, self.A = mu[o], A[:, o]
        self.alpha = self.A / np.sqrt(self.mu)             # alpha^T K~ alpha = 1
        return self
    def transform(self, Xn, center=True):
        kn = np.exp(-self.gamma * sq_dists(Xn, self.X))    # k(x, x_i), una fila por punto nuevo
        if center:
            kn = kn - kn.mean(1, keepdims=True) - self.K.mean(0, keepdims=True) + self.K.mean()
        return kn @ self.alpha
    def scores(self):
        return self.A * np.sqrt(self.mu)

X, y = make_circles(200, noise=0.05, factor=0.35, random_state=0)

def best_threshold_accuracy(z, y):
    """Precisión del mejor umbral sobre una sola coordenada (con el signo que más convenga)."""
    o = np.argsort(z)
    ys = y[o]
    ones_left = np.concatenate([[0], np.cumsum(ys)])
    i = np.arange(len(z) + 1)
    acc = (ones_left + (len(z) - i) - (ys.sum() - ones_left)) / len(z)   # izquierda = 0, derecha = 1
    return max(acc.max(), 1 - acc.min())

zp = PCA(2).fit_transform(X)
print("PCA lineal, precisión de la mejor componente:", max(best_threshold_accuracy(zp[:, j], y) for j in range(2)))
print("gamma | cuatro primeros autovalores de K~ | precisión por componente")
for g in (0.1, 1, 2, 5, 20, 200, 1000):
    m = KPCA(g, 4).fit(X)
    acc = [best_threshold_accuracy(m.scores()[:, j], y) for j in range(4)]
    print(f"{g:6g} | {np.round(m.mu, 2)} | {np.round(acc, 2)}")
z20 = KPCA(20, 2).fit(X).scores()
print("gamma = 20, varianza de las componentes 1 y 2 en el anillo interior / en el exterior:", np.round(z20[y == 1].var(0) / z20[y == 0].var(0)))

m = KPCA(2.0, 2).fit(X)
Xn = np.array([[0.3, 0.2], [1.0, 0.0]])
ref = KernelPCA(2, kernel="rbf", gamma=2.0).fit(X)
sg = np.sign((m.scores() * ref.transform(X)).sum(0))
print("puntuaciones de entrenamiento vs sklearn:", f"{np.abs(m.scores() * sg - ref.transform(X)).max():.1e}")
print("puntos nuevos vs sklearn (módulo):", f"{np.abs(np.abs(m.transform(Xn)) - np.abs(ref.transform(Xn))).max():.1e}")
print("módulo de las puntuaciones de los puntos nuevos SIN centrar el núcleo:", np.round(np.abs(m.transform(Xn, center=False)), 2).tolist(), "frente a", np.round(np.abs(m.transform(Xn)), 2).tolist())
mu_sin, A_sin = np.linalg.eigh(m.K)                        # el mismo problema con K sin centrar
print("autovalor mayor de K sin centrar:", round(mu_sin[-1], 2), "| mayor de K~:", round(m.mu[0], 2), "| autovector mayor de K sin centrar con entradas del mismo signo:", bool(np.all(A_sin[:, -1] > 0) or np.all(A_sin[:, -1] < 0)))
g0 = 1e-3
m0 = KPCA(g0, 2).fit(X)
print("gamma -> 0: autovalores / (2 gamma) =", np.round(m0.mu / (2 * g0), 2), "| (n-1) x varianzas de PCA =", np.round(199 * PCA(2).fit(X).explained_variance_, 2))

Linear PCA never exceeds 69% accuracy with either component. With kernel PCA, for γ\gamma between 0.1 and 1 separation lies in the third component (accuracy 1.00). As the expansion predicted, small γ\gamma makes the first two components linear (eigenvalues 9.44 and 9.35 at γ=0.1\gamma = 0.1, nearly equal because rings are isotropic) and the third the first second-order effect, a function of ∥x∥2\norm{\vb{x}}^2, radius, separating rings. Increasing γ\gamma raises the radial eigenvalue until it leads, but not abruptly. At γ=2\gamma = 2 the first three eigenvalues nearly coincide (26.64, 26.16 and 25.87), and near-equal eigenvectors can mix: radial direction splits between components and neither separates completely (best 0.96). At γ=5\gamma = 5 radial is first (1.00). At γ=20\gamma = 20 it is third again: the kernel is so narrow that first components describe variation within the denser inner ring and are nearly constant outside (inner variance is hundreds of thousands of times outer). With large γ\gamma (200 and 1000), no component separates (accuracy 0.64–0.81) and eigenvalues flatten. At γ=0.001\gamma = 0.001, eigenvalues divided by 2γ2\gamma (56.14 and 55.63) match (n−1)(n - 1) times PCA variances (56.24 and 55.73) within 0.2%, the γ2\gamma^2-order term.

An uncentered new point projects differently (absolute value 0.81 instead of 0.55 on the first point’s second component, and 0.23 instead of 0.02 on the second’s), placing it incorrectly; centered, it matches sklearn to 10−1410^{-14} (component signs are arbitrary, hence absolute-value comparison).

What kernel PCA does not give for free

  • Choosing γ\gamma. No unsupervised loss compares it: useful range depends on data scale (with rings 0.65 apart, tested values from 0.1 to 20 except γ=2\gamma = 2 yield a separating component, while 200 does not), chosen using a downstream task or spectrum.
  • Preimage. A map point z\vb{z} need not be ϕ(x)\phi(\vb{x}) for any x\vb{x} (Mika et al., 1999, proposed iterative approximations), so direct “reconstruction” to Rp\R^p is unavailable.
  • Cost. An n×nn \times n eigenproblem (memory O(n2)\bigO(n^2), dense time O(n3)\bigO(n^3)); each new point needs nn kernel evaluations.
  • Part of a family. Ham et al. (2004) showed Isomap, LLE and Laplacian eigenmaps (next lesson) are also kernel PCA with data-built kernels. Isomap kernel −12JDG(2)J-\tfrac12\mat{J}\mat{D}_G^{(2)}\mat{J} need not be positive semidefinite.

Isomap: geodesic distances and MDS

PCA cannot solve a rolled sheet. In a Swiss roll, straight distances cross air between neighboring layers, while what matters is distance on the sheet. Isomap (Tenenbaum, de Silva and Langford, 2000) estimates geodesic distance with a graph and passes it to MDS.

Cost lies in step 2 and the dense matrix: nn Dijkstra runs, O(n2(k+log⁡n))\bigO(n^2(k + \log n)) with a suitable heap, O(n2)\bigO(n^2) memory and diagonalizing an n×nn \times n matrix (Lanczos for only the largest dd eigenvalues). Enough for thousands, not millions; landmark Isomap (de Silva and Tenenbaum, 2003) computes geodesics from only m≪nm \ll n points.

Why and when it works

Graph edges are straight chords between near neighbors; with dense sampling a short chord nearly equals the manifold arc. Summed chords approximate arc length, and between distant points the graph shortest path approximates the geodesic. The precise statement:

(Constants depending on curvature and manifold minimum branch separation are omitted.) This guarantees DG\mat{D}^G approximates intrinsic distance; MDS reconstructs it only if the manifold can unfold without distortion:

  • If M\mathcal{M} is isometric to a convex open subset of Rd\R^d, intrinsic distances are that subset’s Euclidean distances, and B\mat{B} is (nearly) positive semidefinite of rank dd: Isomap recovers parameterization up to isometry. The Swiss roll is such a surface: a rolled flat sheet.
  • If M\mathcal{M} is curved (like a sphere), no isometric unfolding exists (Gauss’s egregium again), and the map distorts.
  • If the domain is nonconvex (a sheet with a hole), geodesics go around the hole and are longer than straight lines in the flat domain: intrinsic distances are no longer those of any planar configuration and unfolding distorts (Donoho and Grimes, 2003, identify this Isomap limitation).
InteractiveUnrolling the Swiss roll
The 600 points in R3\R^3, colored by position along the sheet
  • straight line between AA and BB (through air)
  • shortest graph path
  • bridge edge between layers
Two-dimensional Isomap embedding (rotated and reflected to align with the true sheet)
10
60
Straight line ∥A−B∥\lVert A - B\rVert en R3\R^36.9
Graph geodesic57.8
True distance on sheet56.8
Bridge edges · components0 · 1
Distance correlation with the sheet0.9999
Residual variance 1−R21 - R^2 versus geodesic0.0002
Without shortcuts, the shortest graph path follows the sheet and its length, 57.8, approaches the true sheet distance, 56.8. The straight spatial line, 6.9, crosses several layers.
A flat sheet (length 89.4, height 21) rolled in R3\R^3 with 600 points and a kk-neighbor graph (enable 'Draw graph'). Drag to rotate the 3D scene. Choose point BB on the sheet: the straight line crosses air between layers, graph geodesic follows the sheet. Below: Isomap embedding aligned with the true sheet. Initially k=10k = 10, with a dense regular enough mesh for no shortcuts and almost 1 correlation with the sheet. Raise kk until red edges appear (shortcuts: connect points over 5 units apart and more than 2.2 times their sheet distance, close in R3\R^3 but far on the sheet), and watch correlation and unfolding fall. Return to k=10k = 10 and enable the hole: move BB across it and the shortest path goes around; geodesic no longer equals the sheet's straight line and correlation falls without any shortcut.

Isomap failures

  • Shortcuts. One edge joining distinct manifold layers (near in Rp\R^p but far on the manifold) shortens many pairs’ geodesics, because paths that went around the sheet now use it. Sensitive to kk and noise, and possible for any kk if noise matches layer separation (Balasubramanian and Schwartz, 2002). Spectral symptom: B\mat{B} loses low rank and residual variance 1−R21 - R^2 between graph geodesics and map distances rises.
  • Disconnected graph. If kk is too small or sampling has gaps, some distances are infinite. Check connected components and raise kk or embed the largest component.
  • Nonconvex domains and curvature, discussed above.
  • Choosing dimension. Tenenbaum et al. (2000) suggest plotting 1−R21 - R^2 between DG\mat{D}^G and embedding distances against dd, choosing where the curve stops falling.

New points

Isomap does not define a function Rp→Rd\R^p \to \R^d, but the same calculation extends to new x\vb{x}. Estimate its geodesic distances to data via its kk neighbors: δi=min⁡j∈Nk(x)(∥x−xj∥+DjiG)\delta_i = \min_{j \in N_k(\vb{x})}\big(\norm{\vb{x} - \vb{x}_j} + D^G_{ji}\big). Let ri=1n∑l(DilG)2r_i = \tfrac1n\sum_l (D^G_{il})^2 and (λj,vj)(\lambda_j, \vb{v}_j) be eigenpairs of B\mat{B} with λj>0\lambda_j > 0. Projection of x\vb{x} onto axis jj is

yj(x)=−12λj∑ivji(δi2−ri).y_j(\vb{x}) = -\frac{1}{2\sqrt{\lambda_j}}\sum_i v_{ji}\big(\delta_i^2 - r_i\big).

This follows by expressing the dot product of x\vb{x} (centered with training means) with each xi\vb{x}_i as −12(δi2−ri−δˉ2+m)-\tfrac12(\delta_i^2 - r_i - \bar\delta^2 + m), with δˉ2=1n∑lδl2\bar\delta^2 = \tfrac1n\sum_l\delta_l^2 and m=1n2∑DilG 2m = \tfrac1{n^2}\sum D_{il}^{G\,2}, and projecting onto axis jj; constant terms cancel because ∑ivji=0\sum_i v_{ji} = 0 (an eigenvector with nonzero eigenvalue of B\mat{B} is orthogonal to 1\vb{1}). This is exactly kernel PCA’s new-point formula with kernel −12(DG)(2)-\tfrac12(\mat{D}^G)^{(2)} centered using training means, and exact Euclidean distances return the new point’s PCA score. The second lab cell checks it against sklearn.manifold.Isomap.transform.

Lab: Isomap from scratch

[ ]Isomap from scratch and comparison with sklearn.manifold.IsomapBrowser
import numpy as np
from scipy.sparse.csgraph import shortest_path, connected_components
from sklearn.datasets import make_swiss_roll, make_s_curve
from sklearn.manifold import Isomap

def knn_graph(X, k):
    """Grafo de k vecinos con pesos euclídeos, simetrizado por unión."""
    D = np.sqrt(sq_dists(X, X))
    n = len(X)
    G = np.zeros((n, n))
    nb = np.argsort(D, axis=1)[:, 1 : k + 1]
    rows = np.repeat(np.arange(n), k)
    G[rows, nb.ravel()] = D[rows, nb.ravel()]
    return np.maximum(G, G.T)

def isomap(X, k, d):
    G = knn_graph(X, k)
    ncomp, _ = connected_components(G, directed=False)
    if ncomp > 1:
        raise ValueError(f"el grafo de {k} vecinos tiene {ncomp} componentes conexas")
    DG = shortest_path(G, method="D", directed=False)      # Dijkstra desde cada nodo
    Y, lam = classical_mds(DG, d)
    return Y, DG, G

X, t = make_swiss_roll(500, noise=0.0, random_state=0)
s = 0.5 * (t * np.sqrt(1 + t ** 2) + np.arcsinh(t))      # longitud de arco de la espiral
S = np.c_[s, X[:, 1]]                                      # la hoja plana (arco, altura)
dS = pdist(S)
print("hoja:", round(np.ptp(S[:, 0]), 1), "x", round(np.ptp(S[:, 1]), 1))

Ymds, lam = classical_mds(squareform(pdist(X)), 2)
Ypca = PCA(2).fit_transform(X)
sg = np.sign((Ymds * Ypca).sum(0))
print("MDS clásico = PCA:", f"{np.abs(Ymds * sg - Ypca).max():.1e}", "| autovalores de B / (n-1):", np.round(lam[:3] / 499, 2), "| varianzas de PCA:", np.round(PCA(3).fit(X).explained_variance_, 2))
for k in (8, 10):
    Y, DG, G = isomap(X, k, 2)
    Yk = Isomap(n_neighbors=k, n_components=2).fit_transform(X)
    sg = np.sign((Y * Yk).sum(0))
    i, j = np.nonzero(np.triu(G))
    puentes = int((np.hypot(*(S[i] - S[j]).T) > 3 * G[i, j]).sum())
    r2g = np.corrcoef(squareform(DG, checks=False), pdist(Y))[0, 1] ** 2
    print(f"k = {k}: aristas {len(i)}, puente {puentes}, 1 - R2 (geodésicas vs mapa) = {1 - r2g:.4f}, correlación con la hoja = {np.corrcoef(pdist(Y), dS)[0, 1]:.4f}, diferencia con sklearn.Isomap = {np.abs(Y * sg - Yk).max():.1e}")

# la S-curve: hoja de ancho 2 y arco t, enrollada en S
Xs, ts = make_s_curve(400, noise=0.0, random_state=0)
Ss = np.c_[ts, Xs[:, 1]]
for k in (8, 10):
    Y, DG, G = isomap(Xs, k, 2)
    print(f"S-curve, k = {k}: correlación con la hoja = {np.corrcoef(pdist(Y), pdist(Ss))[0, 1]:.4f}")

# la escala que decide: hueco entre capas frente a la distancia a los vecinos
for nombre, (A, H) in {"Swiss roll": (X, S), "S-curve": (Xs, Ss)}.items():
    de, dh = pdist(A), pdist(H)
    hueco = de[dh > 3 * de].min()                  # menor distancia en R^3 entre puntos lejanos sobre la hoja
    d10 = np.sort(squareform(de), axis=1)[:, 10]   # distancia de cada punto a su 10.º vecino
    print(f"{nombre}: hueco entre capas {hueco:.2f} | distancia al 10.º vecino: mediana {np.median(d10):.2f}, máxima {d10.max():.2f}")

Notice three things. First, classical MDS of Euclidean Swiss roll distances is PCA (difference 10−1310^{-13}, and λj/(n−1)\lambda_j/(n - 1) matches PCA variances 54.67, 40.20, 34.37), and this linear projection crushes the spiral. Second, with k=8k = 8 the graph has no shortcut edges (out of 2357; the cell calls an edge a shortcut if its sheet distance triples its length in R3\R^3), correlation between map and true-sheet distances is 0.9987, and residual variance against graph geodesics is 0.0017. With k=10k = 10 there are 4 shortcuts among 2920, enough to lower sheet correlation to 0.6276 and raise residual variance to 0.1102: four edges ruin the unfolding. Residual variance is calculated without knowing the sheet, a symptom monitorable on real data. Third, results match sklearn.manifold.Isomap to 10−1210^{-12} and the S-curve (400 points) unfolds well for both kk values: sheet correlations 0.9988 at k=8k = 8 and 0.9993 at k=10k = 10. Scale, not shape, decides, and the final output measures it: the gap between layers (minimum R3\R^3 distance between points more than three times as far on the sheet) versus each point’s distance to its 10th neighbor. In the S-curve the gap, 1.25, triples median 10th-neighbor distance (0.41) and comfortably exceeds maximum (0.74): no edge can jump it. In the Swiss roll the gap is 6.23, less than twice median (3.46) and below maximum (7.30): in sparse areas a point’s 10th neighbor may already lie on the next layer.

The second cell projects new points with the preceding formula.

[ ]Isomap: projecting new pointsBrowser
def isomap_nuevos(Xtr, DG, Y, lam, Xn, k):
    """y_j(x) = -(1 / 2 sqrt(lambda_j)) sum_i v_ji (delta_i^2 - r_i), con delta_i estimada por los k vecinos de x."""
    Dn = np.sqrt(sq_dists(Xn, Xtr))
    nb = np.argsort(Dn, axis=1)[:, :k]
    delta = (np.take_along_axis(Dn, nb, 1)[:, :, None] + DG[nb]).min(1)     # (m, n): geodésica estimada a cada x_i
    r = (DG ** 2).mean(0)
    s = np.sqrt(lam[: Y.shape[1]])
    V = Y / s                                                                   # autovectores v_j de B
    return -0.5 * ((delta ** 2 - r) @ V) / s

arc = lambda t: 0.5 * (t * np.sqrt(1 + t ** 2) + np.arcsinh(t))
X, t = make_swiss_roll(500, noise=0.0, random_state=0)
Xn, tn = make_swiss_roll(50, noise=0.0, random_state=1)                         # 50 puntos que el ajuste no ha visto
S, Sn = np.c_[arc(t), X[:, 1]], np.c_[arc(tn), Xn[:, 1]]
Y, DG, G = isomap(X, 8, 2)
lam = classical_mds(DG, 2)[1]
Yn = isomap_nuevos(X, DG, Y, lam, Xn, 8)
ref = Isomap(n_neighbors=8, n_components=2).fit(X)
sg = np.sign((Y * ref.embedding_).sum(0))
print("frente a sklearn.manifold.Isomap.transform:", f"{np.abs(Yn * sg - ref.transform(Xn)).max():.1e}")
print("correlación de distancias de los puntos nuevos con la hoja:", round(np.corrcoef(pdist(Yn), pdist(Sn))[0, 1], 4))

The formula matches sklearn to rounding, and 50 new points land where they belong: their embedded distances correlate with sheet distances at 0.999, like training points (0.9987 at k=8k = 8). The formula inherits graph defects: if training has shortcuts, new points land on an already broken map.

Sensitivity to kk is not an example-specific detail. Shortcut thresholds depend on density and noise: more sheet points mean closer neighbors and less chance of jumping layers; with noise comparable to layer separation, no kk prevents it. There is no universal kk: check each time that the graph is connected, has no shortcuts, and the embedding is stable under varying kk.

Measuring embedding quality

A map may look good or bad, but the eye is no criterion: this lesson’s and the next lesson’s methods can produce convincing pictures despite distortion. We need measures comparing neighborhoods in original and embedded spaces.

Let r(i,j)r(i, j) be position of jj in ii‘s neighbors sorted by original-space distance (1 = nearest), and r^(i,j)\hat r(i, j) the same rank in the embedding. Let NK(i)N_K(i) and N^K(i)\hat N_K(i) be each space’s KK nearest-neighbor sets. Two neighbor errors: inventing one (among the map’s KK but not original KK: an intruder, UK(i)=N^K(i)∖NK(i)U_K(i) = \hat N_K(i) \setminus N_K(i)) or losing one (original neighbor pushed away on the map: VK(i)=NK(i)∖N^K(i)V_K(i) = N_K(i) \setminus \hat N_K(i)).

The normalization is worst case: if each point’s KK map neighbors were the KK farthest in original space (ranks n−1,…,n−Kn - 1, \dots, n - K), one point’s penalty sum is ∑l=0K−1(n−1−l−K)=K(2n−3K−1)2\sum_{l=0}^{K-1}(n - 1 - l - K) = \tfrac{K(2n - 3K - 1)}{2}, and K<n/2K < n/2 ensures those ranks exceed KK. Dividing by nK(2n−3K−1)2\tfrac{nK(2n - 3K - 1)}{2} makes T=0T = 0 in the worst case and T=1T = 1 without intruders.

Three nuances:

  • They depend on KK. Small KK measures local structure; large KK, mesoscopic. Examine curves over KK, not one number.
  • Compare with chance. A random embedding preserves expected neighbor fraction K/(n−1)K/(n - 1). Corrected RNX(K)=(n−1)Q(K)−Kn−1−KR_{NX}(K) = \frac{(n - 1)Q(K) - K}{n - 1 - K} is 0 for chance and 1 for perfection (QQ and rank analysis are Lee and Verleysen, 2009; the corrected version is used by Lee, Peluffo-Ordóñez and Verleysen, 2015).
  • They are local. They do not see whether two map islands are correctly placed relative to one another. Pairwise-distance correlation (Pearson or rank-based Spearman) and residual variance 1−R21 - R^2 measure global structure; use both families.
InteractiveSix embeddings, three measures
PCA: neighborhood of point 300 (K = 10)
  • selected point
  • its true K neighbors in R³ (ring)
  • false neighbor: close in embedding, far in R³
Trustworthiness T(K) de cada incrustación
  • True sheet
  • PCA
  • kPCA
  • Isomap 10
  • Isomap 14
  • Isomap 20
Incrustaciones calculadas: 0 de 6
10
300
Curve metric
Trustworthiness T(10)T(10)...
Continuity C(10)C(10)...
Fraction of 10 neighbors preserved...
Distance correlation with the true sheet...
False neighbors of point 300...
Computing embeddings in your browser...
The same 600-point Swiss roll (50-by-12 grid with position noise, fixed seed) and six 2D embeddings computed in your browser: true sheet, PCA, Gaussian kernel PCA with γ=0.01\gamma = 0.01, and Isomap with k=10,14k = 10, 14 and 2020. Choose one and move KK: curves show T(K)T(K), C(K)C(K) and retained-neighbor fraction. The magenta point is selected by the second slider; its KK true neighbors are ringed and false map neighbors are red. Initial PCA at K=10K = 10 shows flattening: high CC, low TT, and false neighbors from another layer. Compare Isomap k=10k = 10 (no shortcuts on this grid: all three measures near 1) with k=14k = 14 and 2020, which have shortcuts: TT and retained fraction fall toward PCA values while CC falls much less, because broken unfolding folds the sheet over itself, another kind of flattening.
[ ]Trustworthiness, continuity and preserved neighbors from scratchBrowser
from sklearn.manifold import trustworthiness as sk_trust

def rank_matrix(Dm):
    """r[i, j] = posición de j entre los vecinos de i (1 = el más cercano); r[i, i] = 0."""
    D = Dm.copy()
    np.fill_diagonal(D, -1.0)
    return np.argsort(np.argsort(D, axis=1), axis=1)

def quality(X, Z, K):
    n = len(X)
    rx, rz = rank_matrix(sq_dists(X, X)), rank_matrix(sq_dists(Z, Z))
    nx, nz = (rx >= 1) & (rx <= K), (rz >= 1) & (rz <= K)       # vecindades de K puntos
    norm = 2.0 / (n * K * (2 * n - 3 * K - 1))
    T = 1 - norm * np.where(nz & ~nx, rx - K, 0).sum()             # intrusos: vecinos falsos en el mapa
    C = 1 - norm * np.where(nx & ~nz, rz - K, 0).sum()             # extruidos: vecinos verdaderos perdidos
    keep = (nx & nz).sum() / (n * K)
    return T, C, keep

X, t = make_swiss_roll(500, noise=0.0, random_state=0)
sheet = np.c_[0.5 * (t * np.sqrt(1 + t ** 2) + np.arcsinh(t)), X[:, 1]]
emb = {"PCA": PCA(2).fit_transform(X),
       "kernel PCA (gamma=0.01)": KPCA(0.01, 2).fit(X).scores(),
       "Isomap k=8": isomap(X, 8, 2)[0],
       "Isomap k=10": isomap(X, 10, 2)[0],
       "hoja real": sheet}
K = 10
print(f"base aleatoria de la fracción conservada: K/(n-1) = {K / 499:.3f}")
for name, Z in emb.items():
    T, C, keep = quality(X, Z, K)
    print(f"{name:26s} T(10)={T:.4f}  C(10)={C:.4f}  vecinos conservados={keep:.3f}  corr. distancias con la hoja={np.corrcoef(pdist(Z), pdist(sheet))[0, 1]:.3f}")
print("T de sklearn para Isomap k=10:", round(sk_trust(X, emb["Isomap k=10"], n_neighbors=10), 4))

Read output with definitions at hand. The true sheet, the correct solution, has T(10)=1.0000T(10) = 1.0000 and retains 99.7% of neighbors versus 2% by chance. PCA has high continuity (C=0.9898C = 0.9898) and low trustworthiness (T=0.9018T = 0.9018): flattening layers does not lose neighbors (original neighbors remain together), but invents many (points from different layers overlap). Looking at only one measure misleads. Isomap with k=8k = 8 is excellent (T=0.9985T = 0.9985, C=0.9977C = 0.9977, distance correlation 0.999), while k=10k = 10 deteriorates (0.9110 and 0.9873; only 49.4% of neighbors retained, sheet correlation falls to 0.628). Mind scale: T=0.91T = 0.91 looks good, but is almost PCA’s 0.9018, which unfolds nothing; compare metrics to a reference, not absolutely. Gaussian kernel PCA with γ=0.01\gamma = 0.01 is worst (T=0.8880T = 0.8880, 40.1% retained, sheet correlation 0.094): an isotropic kernel in R3\R^3 does not know sheet distance matters, so Isomap, estimating it by graph, wins. Our TT matches sklearn to four decimals.

Common mistakes

Exercises

ProofDouble centering gives the Gram matrix, and classical MDS is PCA
Prove: Let X∈Rn×p\mat{X} \in \mathbb{R}^{n \times p} satisfy 1⊤X=0\mathbf{1}^\top\mat{X} = \mathbf{0}, let D(2)\mat{D}^{(2)} be squared Euclidean distances between rows, and J=I−1n11⊤\mat{J} = \mat{I} - \tfrac1n\mathbf{1}\mathbf{1}^\top. Then −12JD(2)J=XX⊤-\tfrac12\mat{J}\mat{D}^{(2)}\mat{J} = \mat{X}\mat{X}^\top and, if X=USW⊤\mat{X} = \mat{U}\mat{S}\mat{W}^\top is its SVD, dd-dimensional classical MDS returns XW1:d\mat{X}\mat{W}_{1:d}, the PCA scores.
0
Write G=XX⊤\mat{G} = \mat{X}\mat{X}^\top and q=(G11,…,Gnn)⊤\mathbf{q} = (G_{11}, \dots, G_{nn})^\top.

Step 1 of 4. How is D(2)\mat{D}^{(2)} expressed using G\mat{G} and q\vb{q}?

ProofThe kernel PCA eigenvalue problem and its normalization
Prove: Let ϕ(xi)\phi(\mathbf{x}_i) be centered images (∑iϕ(xi)=0\sum_i\phi(\mathbf{x}_i) = \mathbf{0}), K=(⟨ϕ(xi),ϕ(xj)⟩)\mat{K} = (\langle\phi(\mathbf{x}_i), \phi(\mathbf{x}_j)\rangle), C=1n∑iϕ(xi)ϕ(xi)⊤\mathcal{C} = \tfrac1n\sum_i\phi(\mathbf{x}_i)\phi(\mathbf{x}_i)^\top, and let v\mathbf{v} be an eigenvector of C\mathcal{C} with eigenvalue λ>0\lambda > 0. Prove that v=∑iαiϕ(xi)\mathbf{v} = \sum_i\alpha_i\phi(\mathbf{x}_i) with Kα=nλα\mat{K}\boldsymbol{\alpha} = n\lambda\boldsymbol{\alpha} and that ∥v∥=1\lVert\mathbf{v}\rVert = 1 is equivalent to ∥α∥=1/nλ\lVert\boldsymbol{\alpha}\rVert = 1/\sqrt{n\lambda} when α\boldsymbol{\alpha} is an eigenvector of K\mat{K}.
0
Write μ=nλ\mu = n\lambda.

Step 1 of 4. Why is v\vb{v} in the subspace spanned by the images?

NumericThe sole eigenvalue of three points on a line
Points on a line at x=0x = 0, 11 and 33 have distances δ12=1\delta_{12} = 1, δ23=2\delta_{23} = 2 and δ13=3\delta_{13} = 3. Calculate the only nonzero eigenvalue of B=−12JD(2)J\mat{B} = -\tfrac12\mat{J}\mat{D}^{(2)}\mat{J}.
NumericThe negative eigenvalue of impossible distances
Three objects have dissimilarities δ12=δ23=1\delta_{12} = \delta_{23} = 1 and δ13=3\delta_{13} = 3, violating the triangle inequality. Calculate the smallest (negative) eigenvalue of B=−12JD(2)J\mat{B} = -\tfrac12\mat{J}\mat{D}^{(2)}\mat{J}.
NumericOne step of the Guttman transform
Three objects have δ12=δ13=δ23=1\delta_{12} = \delta_{13} = \delta_{23} = 1. Start from Z=[001020]\mat{Z} = \begin{bmatrix} 0 & 0 \\ 1 & 0 \\ 2 & 0 \end{bmatrix} (raw stress σ=1\sigma = 1), apply one SMACOF iteration with unit weights, Z+=1nB(Z)Z\mat{Z}^+ = \tfrac1n\mat{B}(\mat{Z})\mat{Z}, and calculate the raw stress σ(Z+)\sigma(\mat{Z}^+).
NumericA new point with the centered kernel
You train kernel PCA with linear kernel k(x,y)=xyk(x, y) = xy on the one-dimensional data 1,3,81, 3, 8 and retain the sole component. Calculate the absolute score of the new point x=5x = 5 using the kernel centered with the training means.
CodeIsomap from scratch
Implement isomap(X, n_neighbors, d), returning an array (n, d) with the Isomap embedding: a graph of n_neighbors neighbors weighted by Euclidean distances (symmetrized by union), geodesic distances with scipy.sparse.csgraph.shortest_path, and classical MDS in dimension d (eigenvalues in descending order). If the graph is disconnected, raise ValueError. The tests check on an S-curve that embedding distances correlate with flat-sheet distances, that with n_neighbors = n - 1 it agrees with PCA (in distances), and that a disconnected graph raises an error.
import numpy as np
from scipy.sparse.csgraph import shortest_path, connected_components

def isomap(X, n_neighbors, d):
  """Incrustación de Isomap de X (n, p) en d dimensiones."""
  X = np.asarray(X, dtype=float)
  n = len(X)
  # 1) grafo de vecinos (pesos = distancias euclídeas, simétrico)
  # 2) distancias geodésicas con shortest_path; error si el grafo no es conexo
  # 3) doble centrado de D^2 y los d mayores autovalores
  return np.zeros((n, d))
Shift+Enter to run
QuizLarge negative eigenvalues
You apply classical MDS to a table of dissimilarities and B=−12JD(2)J\mat{B} = -\tfrac12\mat{J}\mat{D}^{(2)}\mat{J} has several negative eigenvalues that account for a quarter of the spectral mass. What does this indicate?
QuizCentering the kernel of a new point
You trained kernel PCA with K~=JKJ\tilde{\mat{K}} = \mat{J}\mat{K}\mat{J} and want to project a new point x\vb{x}. You have the vector k(x)=(k(x,xi))i\vb{k}(\vb{x}) = (k(\vb{x}, \vb{x}_i))_i and training matrix K\mat{K}. Which kernel vector should you multiply by coefficients αj\vb{\alpha}_j?
QuizDiagnosing a broken unfolding
You run Isomap on a Swiss roll of 500 points. With k=8k = 8, the residual variance 1−R21 - R^2 between graph geodesic distances and map distances is 0.0017. With k=10k = 10 it rises to 0.1102 and the correlation between map distances and the known flat-sheet distances falls from 0.9987 to 0.6276. What is the most likely explanation, and what do you check first?
QuizWhat each measure captures
An embedding breaks a connected manifold into two pieces: points that were neighbors in the original space end up on different islands of the map, while neighborhoods within each island remain faithful. Which measure deteriorates, and what is the phenomenon called?
QuizWhat SMACOF guarantees
Which statements about SMACOF with unit weights are correct?

More than one answer may be correct.

Summary

Key idea
A map is built from dot products: classical MDS extracts them from distances by double centering B=−12JD(2)J\mat{B} = -\tfrac12\mat{J}\mat{D}^{(2)}\mat{J} and diagonalizes them (for Euclidean distances it is PCA); kernel PCA replaces them with centered kernel K~=JKJ\tilde{\mat{K}} = \mat{J}\mat{K}\mat{J} and Isomap with double-centered graph geodesic distances. Stress (SMACOF) directly minimizes distance error. Never judge embeddings by eye alone: trustworthiness, continuity and retained neighbors reveal invented and lost neighborhoods.
  • Classical MDS: B=(JX)(JX)⊤\mat{B} = (\mat{J}\mat{X})(\mat{J}\mat{X})\T for Euclidean distances; B⪰0\mat{B} \succeq \mat{0} if and only if dissimilarities are Euclidean (Schoenberg); negative mass measures failure. With 12 cities and great-circle distances it is 17.7%, and Earth cannot be flattened without distortion (Madrid–Beijing: 9222 km in the table, 11725 km on the map).
  • SMACOF: stress is majorized by a convex quadratic touching at the current configuration, minimized by the Guttman transform. Stress does not rise, but local minima exist: 6 random starts ended at three values (243.4, 251.7, 367.0); from classical MDS, normalized stress drops from 0.258 to 0.177.
  • Kernel PCA: K~α=μα\tilde{\mat{K}}\vb{\alpha} = \mu\vb{\alpha}, with ∥α∥=1/μ\norm{\vb{\alpha}} = 1/\sqrt\mu and kernel centered for new points too. On two rings, linear PCA reaches at most 69% while kernel PCA separates with one component (third for small γ\gamma, first at γ=5\gamma = 5); as γ→0\gamma \to 0 it returns to PCA and as γ→∞\gamma \to \infty degenerates.
  • Isomap: neighbor graph, graph geodesics and classical MDS. It recovers parameterization of manifolds isometric to a convex open set; fails with shortcuts (on the 500-point Swiss roll, 4 edges of 2920 at k=10k = 10 lower sheet correlation from 0.9987 to 0.6276), holes and curvature.
  • Quality: T(K)T(K) penalizes invented neighbors and C(K)C(K) lost ones; PCA on Swiss roll has C(10)=0.9898C(10) = 0.9898 but T(10)=0.9018T(10) = 0.9018. Always inspect against KK, chance (K/(n−1)K/(n - 1)) and a global measure.

The next lesson replaces geodesics with what each point knows of immediate neighbors: LLE, Laplacian eigenmaps (also kernel PCA with data-built kernels, as Ham et al., 2004 showed), and diffusion maps.