---
title: "MDS vs. Laplacian Eigenmaps"
subtitle: "Bend the data. Watch what each method keeps."
date: 2026-11-11
number-sections: false
jupyter: python3
format:
html:
toc: false
code-fold: true
code-tools: true
out-width: "100%"
column: page
execute:
echo: true
draft: false
---
Let's investigate the difference between MDS and Laplacian Eigenmaps!
Here, **classical MDS** uses all pairwise Euclidean distances; **Laplacian Eigenmaps** uses a graph of nearby points.
Color records position along the chain and is never given to either method.
```{python}
#| code-summary: "Make a bendable chain and compute both embeddings"
import numpy as np
import plotly.graph_objects as go
from plotly.subplots import make_subplots
n = 81
s = np.linspace(0, 1, n)
bends = np.arange(0, 301, 30)
def bend_chain(degrees):
"""Bend a unit-length segment into a circular arc, preserving arc length."""
theta = np.deg2rad(degrees)
if degrees == 0:
return np.column_stack((s - 0.5, np.zeros(n)))
angle = theta * (s - 0.5)
return np.column_stack((np.sin(angle), 1 - np.cos(angle))) / theta
def classical_mds(distances):
squared = distances**2
gram = -0.5 * (
squared - squared.mean(axis=0)[None, :]
- squared.mean(axis=1)[:, None] + squared.mean()
)
values, vectors = np.linalg.eigh(gram)
return vectors[:, -1] * np.sqrt(max(values[-1], 0))
def laplacian_eigenmap(weights):
degree = weights.sum(axis=1)
laplacian = np.eye(n) - weights / np.sqrt(np.outer(degree, degree))
values, vectors = np.linalg.eigh(laplacian)
return vectors[:, 1] / np.sqrt(degree)
def display_coordinate(y):
# Fix the arbitrary reflection, then use a common display range.
if y[-1] < y[0]:
y = -y
return (y - y.min()) / np.ptp(y)
states = []
for degrees in bends:
X = bend_chain(degrees)
distances = np.linalg.norm(X[:, None, :] - X[None, :, :], axis=2)
# This fixed radius joins consecutive points at every bend shown.
weights = ((distances > 0) & (distances < 1.1 / (n - 1))).astype(float)
states.append(dict(
X=X,
weights=weights,
mds=display_coordinate(classical_mds(distances)),
eigenmap=display_coordinate(laplacian_eigenmap(weights)),
))
initial = list(bends).index(270)
```
## Bend a line into a horseshoe
**Move the slider from $0^\circ$ to $300^\circ$.**
The grey edges show the radius-neighbour graph: the chain bends, but its connections stay the same.
```{python}
#| code-summary: "Draw the interactive comparison"
#| label: fig-bending-chain
#| fig-cap: "Both outputs are one-dimensional; their display ranges are rescaled to [0, 1]. MDS folds the color sequence once the bend exceeds 180°. The eigenmap stays unchanged because the neighbour graph stays unchanged. Hover to identify points."
#| fig-alt: "An interactive horseshoe-shaped point cloud, colored from purple to gold, beside two horizontal embeddings. The MDS embedding mixes colors near its ends; the Laplacian eigenmap keeps the colors in order. A bend-angle slider changes the input from a straight line to a nearly closed arc."
INK = "#808080"
GRID = "rgba(128,128,128,0.22)"
EDGE = "rgba(128,128,128,0.45)"
MDS_COLOR = "#df7955"
LE_COLOR = "#27a9a0"
CONFIG = dict(displayModeBar=False, responsive=True)
customdata = np.column_stack((np.arange(n), s))
hover = "Point %{customdata[0]:.0f}<br>Along chain: %{customdata[1]:.2f}<extra></extra>"
def style(fig, height):
fig.update_layout(
template="simple_white",
paper_bgcolor="rgba(0,0,0,0)",
plot_bgcolor="rgba(0,0,0,0)",
font=dict(family="Arial, sans-serif", size=13, color=INK),
height=height,
margin=dict(l=35, r=35, t=70, b=35),
showlegend=False,
hovermode="closest",
)
fig.update_annotations(font=dict(size=15, color=INK))
fig.update_xaxes(zeroline=False, showgrid=False, linecolor=GRID)
fig.update_yaxes(zeroline=False, showgrid=False, linecolor=GRID)
return fig
def colored_points(x, y, size=10):
return go.Scatter(
x=x, y=y, mode="markers",
marker=dict(
color=s, colorscale="Viridis", cmin=0, cmax=1, size=size,
line=dict(color="rgba(255,255,255,0.65)", width=0.5),
),
customdata=customdata,
hovertemplate=hover,
)
def comparison_traces(state):
X = state["X"]
i, j = np.where(np.triu(state["weights"], 1))
edges = np.stack((X[i], X[j], np.full_like(X[i], np.nan)), axis=1)
edges = edges.reshape(-1, 2)
return [
go.Scatter(
x=edges[:, 0], y=edges[:, 1], mode="lines",
line=dict(color=EDGE, width=2), hoverinfo="skip",
),
colored_points(X[:, 0], X[:, 1], size=8),
colored_points(state["mds"], np.zeros(n)),
colored_points(state["eigenmap"], np.zeros(n)),
]
fig = make_subplots(
rows=2, cols=2,
specs=[[dict(rowspan=2), {}], [None, {}]],
column_widths=[0.46, 0.54],
horizontal_spacing=0.10, vertical_spacing=0.32,
subplot_titles=(
"<b>The data</b> · two dimensions",
"<b>Classical MDS</b> · one dimension",
"<b>Laplacian Eigenmaps</b> · one dimension",
),
)
for trace, (row, col) in zip(
comparison_traces(states[initial]), [(1, 1), (1, 1), (1, 2), (2, 2)]
):
fig.add_trace(trace, row=row, col=col)
fig.frames = [
go.Frame(name=str(degrees), data=comparison_traces(state), traces=[0, 1, 2, 3])
for degrees, state in zip(bends, states)
]
style(fig, height=510)
fig.update_xaxes(range=[-0.55, 0.55], visible=False, row=1, col=1)
fig.update_yaxes(
range=[-0.15, 0.8], visible=False, scaleanchor="x", scaleratio=1,
row=1, col=1,
)
for row in (1, 2):
fig.update_xaxes(
range=[-0.06, 1.06], tickvals=[0, 0.5, 1], fixedrange=True,
row=row, col=2,
)
fig.update_yaxes(range=[-1, 1], visible=False, fixedrange=True, row=row, col=2)
fig.add_hline(y=0, line_color=GRID, line_width=1, layer="below", row=row, col=2)
fig.update_layout(
margin=dict(l=25, r=25, t=55, b=110),
sliders=[dict(
active=initial, x=0.05, len=0.9, y=-0.12,
currentvalue=dict(prefix="Bend: ", font=dict(size=15)),
pad=dict(t=25), tickcolor=GRID,
steps=[dict(
label=f"{degrees}°",
value=f"{degrees}°", method="animate",
args=[[str(degrees)], dict(
mode="immediate", frame=dict(duration=0, redraw=True),
transition=dict(duration=0),
)],
) for degrees in bends],
)],
)
fig.show(config=CONFIG)
```
## Keeping order is not keeping distance
At $270^\circ$, the MDS coordinate doubles back; the eigenmap coordinate increases throughout, but squeezes the ends of the chain.
The dotted diagonal would preserve distance along the chain exactly.
```{python}
#| code-summary: "Compare order and spacing at a fixed 270° bend"
#| label: fig-order-and-spacing
#| fig-cap: "A fixed 270° bend. Each curve follows points in chain order. A monotone curve preserves that order; a straight diagonal also preserves relative spacing along the chain."
#| fig-alt: "Two plots of embedding coordinate against position along the chain. The classical MDS curve turns backward near both ends. The Laplacian eigenmap curve is increasing but S-shaped, flattening near the ends instead of following the dotted diagonal."
spacing = make_subplots(
rows=1, cols=2, horizontal_spacing=0.13,
subplot_titles=("<b>MDS</b> · order folds", "<b>Eigenmap</b> · spacing changes"),
)
for col, (key, color) in enumerate((("mds", MDS_COLOR), ("eigenmap", LE_COLOR)), 1):
spacing.add_trace(go.Scatter(
x=[0, 1], y=[0, 1], mode="lines",
line=dict(color=INK, width=1.5, dash="dot"), hoverinfo="skip",
), row=1, col=col)
spacing.add_trace(go.Scatter(
x=s, y=states[initial][key], mode="lines",
line=dict(color=color, width=3), hoverinfo="skip",
), row=1, col=col)
points = colored_points(s, states[initial][key], size=6)
points.hovertemplate = hover.replace(
"<extra>", "<br>Embedding: %{y:.2f}<extra>"
)
spacing.add_trace(points, row=1, col=col)
style(spacing, height=360)
spacing.update_xaxes(
title_text="Position along the chain", range=[-0.04, 1.04],
tickvals=[0, 0.5, 1], fixedrange=True,
)
spacing.update_yaxes(
range=[-0.04, 1.04], tickvals=[0, 0.5, 1], fixedrange=True,
)
spacing.update_yaxes(title_text="Embedding coordinate (rescaled)", row=1, col=1)
spacing.show(config=CONFIG)
```
For the formulas: [classical MDS](../../lectures/lecture-18.qmd#alg-classical-mds) and [Laplacian Eigenmaps](../../lectures/lecture-17.qmd#def-laplacian-eigenmap).