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 between objects, find points with . With or this visualizes data; with larger , 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 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: -dimensional data live near a manifold of intrinsic dimension ), 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 , 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:
| Method | Input | Central object | Nonlinear? |
|---|---|---|---|
| Classical MDS | distances | and spectrum | no: with Euclidean distances it is PCA |
| Metric MDS (SMACOF) | distances (and weights) | stress , minimized by majorization | yes, but optimization is nonconvex |
| Kernel PCA | kernel | and spectrum | yes, via feature space |
| Isomap | neighbor graph | graph geodesic distances, then classical MDS | yes, 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.
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 ‘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:
If we could isolate we would have the Gram matrix , from which coordinates follow by spectral decomposition. Terms and get in the way, but depend only on row or column. Subtracting each row and column mean removes them: double centering.
Proof
Let and be the squared-norm vector. The identity above for all pairs reads . Multiply left and right by . Since and , the first two terms vanish: , namely . If , then .
∎Immediate consequence: with Euclidean distances, is positive semidefinite with rank at most , and reproduces original dot products projected onto their first principal axes. Follow each calculation on a hand-checkable example.
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, . This is a spectral decomposition of : eigenvectors are columns of and eigenvalues . Thus , and since those coordinates are . Finally .
∎This is the same versus duality used by high-dimensional PCA: diagonalizing the dot-product matrix or covariance matrix agrees up to factor , 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 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 .
Proof
If comes from points, is a Gram matrix by the preceding theorem and is positive semidefinite. Conversely, let and write with , (spectral decomposition with square roots of eigenvalues). Show row distances of are . Let and . Expanding double centering, ; with , . Then . The left-hand side is . For minimum dimension: any exact configuration, after centering, has Gram matrix and rank .
∎Practical consequence: a negative eigenvalue of certifies dissimilarities are not Euclidean, and negative mass measures the departure. The double-centering figure showed a useful identity: trace of , sum of all eigenvalues, is (from , , and ).
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:
- Ignore them, as classical MDS does: keep the largest positive eigenvalues. Reasonable if negative mass is small relative to retained axes.
- Add a constant off diagonal. Lingoes (1971) adds it to squared dissimilarities, , with equal to the absolute value of ‘s most negative eigenvalue (double centering yields , shifting every eigenvalue of except that of by ); Cailliez (1983) adds it to dissimilarities, , and proved the smallest making them Euclidean is the largest eigenvalue of a matrix. Both change geometry by equally inflating small distances.
- Do not require semidefiniteness: directly minimize discrepancy between and , 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.
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 and distances reproduce exactly. Cities show two effects: has five negative eigenvalues, totaling 17.7% of spectral mass (the largest, , exceeds half the third positive eigenvalue, ), 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 , 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: is nonconvex with local minima. It does not require Euclidean dissimilarities, and large- and small-distance errors have equal weight (other 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 and centered (zero-mean columns, without changing distances),
Treat the three terms separately.
- The first is constant.
- The second is quadratic: for centered .
- The third is hard because is a norm. Write it as a quadratic form. Define with if and (and if ), and . It resembles a graph Laplacian weighted by , and for any two configurations . With that sum is exactly .
Cauchy-Schwarz, , after division by and multiplication by , gives (if the majorizer term is and the inequality trivial). Sum over pairs:
Iteration needs no learning step size and decreases stress each step. If is bounded below by 0 and nonincreasing, it converges; De Leeuw (1988) proves accumulation points of the sequence are stationary points of . 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.
Nonmetric MDS
When only dissimilarity order matters (for example subjective similarity ratings), replace by disparities , with monotone increasing fitted alongside configuration (isotonic regression), and minimize stress of against (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
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 (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 to feature space and doing PCA there without ever calculating .
Derivation
Let be a positive semidefinite kernel (common kernels) and its data kernel matrix. First assume feature images are centered, (removed below). Covariance in is (operator ), and seek eigenvectors with .
Four steps lead to the definition.
1. The eigenvector is a combination of images. From with , rearrange , so for coefficients . Only images exist, so there are at most eigenvectors with (actually after centering), even if is infinite-dimensional.
2. The eigenproblem. Project onto each image: for every (equivalent to the original equation because both sides lie in the image span). The left side is and right side . Thus . Any with satisfies it; other solutions differ by a null-space vector of , generating with squared norm , the same . Solve with .
3. Normalization. Require : . If is a unit eigenvector of , use .
4. Projection. A point ‘s component on is , using only the kernel. For a training point, : training scores are columns of , as in classical MDS.
Centering in feature space
Images are not centered and cannot even be calculated, but , with , has a calculable kernel:
On training data it is . A new point must be centered using training means: vector becomes and . Omitting this centering, for training or new points, is the most frequent kernel-PCA implementation error.
With linear kernel , is the centered Gram matrix and kernel PCA is classical MDS, ordinary PCA. Generally kernel PCA is classical MDS of kernel distance , because double centering holds in any inner-product space and gives (Williams, 2002). The lesson’s three pieces are the same machine with different .
Gaussian kernel on two rings
With , inverse width sets the scale of “similarity.” Two extremes follow from a calculation:
- . , so and . Kernel PCA approaches linear PCA (eigenvalues ). Nonlinearity appears in higher-order terms, giving subsequent components.
- . (distinct points become almost orthogonal in ) and , whose nonzero eigenvalues all equal 1: no preferred directions, projection degenerates.
Between them is a useful range. Find it with the rings.
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.
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 between 0.1 and 1 separation lies in the third component (accuracy 1.00). As the expansion predicted, small makes the first two components linear (eigenvalues 9.44 and 9.35 at , nearly equal because rings are isotropic) and the third the first second-order effect, a function of , radius, separating rings. Increasing raises the radial eigenvalue until it leads, but not abruptly. At 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 radial is first (1.00). At 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 (200 and 1000), no component separates (accuracy 0.64–0.81) and eigenvalues flatten. At , eigenvalues divided by (56.14 and 55.63) match times PCA variances (56.24 and 55.73) within 0.2%, the -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 (component signs are arbitrary, hence absolute-value comparison).
What kernel PCA does not give for free
- Choosing . No unsupervised loss compares it: useful range depends on data scale (with rings 0.65 apart, tested values from 0.1 to 20 except yield a separating component, while 200 does not), chosen using a downstream task or spectrum.
- Preimage. A map point need not be for any (Mika et al., 1999, proposed iterative approximations), so direct “reconstruction” to is unavailable.
- Cost. An eigenproblem (memory , dense time ); each new point needs 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 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: Dijkstra runs, with a suitable heap, memory and diagonalizing an matrix (Lanczos for only the largest eigenvalues). Enough for thousands, not millions; landmark Isomap (de Silva and Tenenbaum, 2003) computes geodesics from only 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 approximates intrinsic distance; MDS reconstructs it only if the manifold can unfold without distortion:
- If is isometric to a convex open subset of , intrinsic distances are that subset’s Euclidean distances, and is (nearly) positive semidefinite of rank : Isomap recovers parameterization up to isometry. The Swiss roll is such a surface: a rolled flat sheet.
- If 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).
Isomap failures
- Shortcuts. One edge joining distinct manifold layers (near in but far on the manifold) shortens many pairs’ geodesics, because paths that went around the sheet now use it. Sensitive to and noise, and possible for any if noise matches layer separation (Balasubramanian and Schwartz, 2002). Spectral symptom: loses low rank and residual variance between graph geodesics and map distances rises.
- Disconnected graph. If is too small or sampling has gaps, some distances are infinite. Check connected components and raise or embed the largest component.
- Nonconvex domains and curvature, discussed above.
- Choosing dimension. Tenenbaum et al. (2000) suggest plotting between and embedding distances against , choosing where the curve stops falling.
New points
Isomap does not define a function , but the same calculation extends to new . Estimate its geodesic distances to data via its neighbors: . Let and be eigenpairs of with . Projection of onto axis is
This follows by expressing the dot product of (centered with training means) with each as , with and , and projecting onto axis ; constant terms cancel because (an eigenvector with nonzero eigenvalue of is orthogonal to ). This is exactly kernel PCA’s new-point formula with kernel 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
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 , and matches PCA variances 54.67, 40.20, 34.37), and this linear projection crushes the spiral. Second, with the graph has no shortcut edges (out of 2357; the cell calls an edge a shortcut if its sheet distance triples its length in ), correlation between map and true-sheet distances is 0.9987, and residual variance against graph geodesics is 0.0017. With 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 and the S-curve (400 points) unfolds well for both values: sheet correlations 0.9988 at and 0.9993 at . Scale, not shape, decides, and the final output measures it: the gap between layers (minimum 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.
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 ). The formula inherits graph defects: if training has shortcuts, new points land on an already broken map.
Sensitivity to 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 prevents it. There is no universal : check each time that the graph is connected, has no shortcuts, and the embedding is stable under varying .
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 be position of in ‘s neighbors sorted by original-space distance (1 = nearest), and the same rank in the embedding. Let and be each space’s nearest-neighbor sets. Two neighbor errors: inventing one (among the map’s but not original : an intruder, ) or losing one (original neighbor pushed away on the map: ).
The normalization is worst case: if each point’s map neighbors were the farthest in original space (ranks ), one point’s penalty sum is , and ensures those ranks exceed . Dividing by makes in the worst case and without intruders.
Three nuances:
- They depend on . Small measures local structure; large , mesoscopic. Examine curves over , not one number.
- Compare with chance. A random embedding preserves expected neighbor fraction . Corrected is 0 for chance and 1 for perfection ( 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 measure global structure; use both families.
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 and retains 99.7% of neighbors versus 2% by chance. PCA has high continuity () and low trustworthiness (): 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 is excellent (, , distance correlation 0.999), while deteriorates (0.9110 and 0.9873; only 49.4% of neighbors retained, sheet correlation falls to 0.628). Mind scale: looks good, but is almost PCA’s 0.9018, which unfolds nothing; compare metrics to a reference, not absolutely. Gaussian kernel PCA with is worst (, 40.1% retained, sheet correlation 0.094): an isotropic kernel in does not know sheet distance matters, so Isomap, estimating it by graph, wins. Our matches sklearn to four decimals.
Common mistakes
Exercises
Step 1 of 4. How is expressed using and ?
Step 1 of 4. Why is in the subspace spanned by the images?
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))More than one answer may be correct.
Summary
- Classical MDS: for Euclidean distances; 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: , with 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 , first at ); as it returns to PCA and as 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 lower sheet correlation from 0.9987 to 0.6276), holes and curvature.
- Quality: penalizes invented neighbors and lost ones; PCA on Swiss roll has but . Always inspect against , chance () 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.