5 Multidimensional Scaling
R code for this chapter: mds_figures.R (data and figures) and _common.R (shared helpers). Save both in one folder and run source("mds_figures.R"); every figure is then one function call, as shown under the Code buttons.
Slides for this chapter: mds_slides.html (opens in a new tab; use the arrow keys to move between slides).
So far every analysis started from a data matrix \(\mathbf X\): \(n\) observations, each measured on \(p\) variables. Some data arrive in a different form, as distances between the observations: travel times between places, how differently two members of Congress vote, how rarely two words are used together. Multidimensional scaling (MDS) turns such a table of distances into coordinates, a map. This chapter starts from the loop road of the Introduction, asks how much a table of distances reveals about the coordinates behind it, shows that MDS lands directly on the principal component scores of Chapter 4, connects the idea to the embeddings of modern AI, and then moves from straight-line distances to other kinds.
Notation: \(d_{st}\) is the distance between observations \(s\) and \(t\), and the \(n\times n\) table of all of them is the distance matrix \(\mathbf D\), bold like the data matrix \(\mathbf X\) because it holds data. (It has nothing to do with the diagonal matrix \(D\) of Chapter 4.)
5.1 Travel times on a loop road
Picture again the town of the Introduction, whose eight places all sit on one loop road. For getting around, what matters is not the straight line between two places but the driving time along the road. At 30 km/h a full loop takes 41 minutes. MDS is given only the table of travel times between the places, and it looks for points in the plane whose straight-line distances reproduce the table as closely as possible.
With no waiting, MDS finds a ring, with the places in driving order. Now a construction site between the Stadium and the Church makes everybody who drives through it wait. Drag the slider to add waiting time: the ring stretches open at the construction site, and once the wait passes 27.9 minutes nobody drives through the site any more, and MDS returns a line: one dimension is enough. (Classical MDS lays the line along its first dimension; Section 5.3 explains why.)
D_wait <- function(w) { # travel times (minutes) with a wait of w minutes at the site
a <- abs(outer(s_min, s_min, "-"))
D <- pmin(a, T_loop - a + w)
dimnames(D) <- list(places$place, places$place); D
}
fig_loop <- function(height = 660) {
pair <- c("Stadium", "Grocery")
c_frac <- 0.95
site <- tibble(east = approx(road$s, road$east, c_frac * L_road)$y,
north = approx(road$s, road$north, c_frac * L_road)$y)
w_grid <- sort(unique(c(0:36, round(w_star, 1))))
wlab <- function(w) sprintf("%.1f", w)
theta <- 2 * pi * places$frac
prev <- cbind(cos(theta), sin(theta)) * T_loop / (2 * pi)
mds_frames <- purrr::map_dfr(w_grid, function(w) {
Y <- suppressWarnings(cmdscale(as.dist(D_wait(w)), k = 2)) # classical MDS as it comes
if (ncol(Y) < 2) Y <- cbind(Y, 0) # a line: the second eigenvalue is zero
Y <- sweep(Y, 2, ifelse(colSums(Y * prev) < 0, -1, 1), "*"); prev <<- Y # signs are arbitrary: keep them steady
line <- max(abs(Y[, 2])) < 1e-6 # a line: alternate the labels above and below it
tp <- if (line) c("top center", "bottom center")[rank(Y[, 1], ties.method = "first") %% 2 + 1] else
dplyr::case_when(abs(Y[, 1]) >= abs(Y[, 2]) & Y[, 1] >= 0 ~ "middle right", abs(Y[, 1]) >= abs(Y[, 2]) ~ "middle left",
Y[, 2] >= 0 ~ "top center", TRUE ~ "bottom center") # a ring: labels point outwards
gap <- mean(abs(dist(Y) - as.dist(D_wait(w)))) # how far the map distances are from the table
places |> dplyr::select(place) |> mutate(d1 = Y[, 1], d2 = Y[, 2], k = wlab(w), tp = tp, gap = gap)
})
fit_txt <- mds_frames |> dplyr::distinct(k, gap) |>
mutate(x = 0, y = -16, txt = ifelse(gap < 0.005, "average distance error: 0 min (exact)",
sprintf("average distance error: %.1f min", gap)))
road_mds <- mds_frames |> group_by(k) |>
dplyr::group_modify(~ dplyr::bind_rows(.x, .x[1, ])) |> ungroup()
pair_mds <- mds_frames |> dplyr::filter(place %in% pair)
pr <- places |> dplyr::filter(place %in% pair)
p_map <- plot_ly() |>
add_trace(data = road, x = ~east, y = ~north, type = "scatter", mode = "lines", color = I("grey80"),
line = list(color = "#cccccc", width = 10), hoverinfo = "skip") |>
add_trace(x = pr$east, y = pr$north, type = "scatter", mode = "lines", color = I(col_a2),
line = list(color = col_a2, dash = "dash", width = 1.5), hoverinfo = "skip") |>
add_trace(data = places, x = ~east, y = ~north, type = "scatter", mode = "markers+text",
text = ~place, color = I("#2c3e50"),
textposition = dplyr::case_when(places$east > 3.5 ~ "middle right", places$east < -3.5 ~ "middle left",
places$north > 0 ~ "top center", TRUE ~ "bottom center"),
marker = list(color = "#2c3e50", size = 9), textfont = list(size = 12), hoverinfo = "skip") |>
add_trace(data = site, x = ~east, y = ~north, type = "scatter", mode = "markers+text",
text = "construction", textposition = "bottom right", color = I(col_wait),
marker = list(symbol = "x", color = col_wait, size = 16, line = list(width = 2)),
textfont = list(color = col_wait, size = 12), hoverinfo = "skip")
p_mds <- plot_ly() |>
add_trace(data = road_mds, x = ~d1, y = ~d2, frame = ~k, type = "scatter", mode = "lines",
color = I("grey80"), line = list(color = "#cccccc", width = 6), hoverinfo = "skip") |>
add_trace(data = mds_frames, x = ~d1, y = ~d2, frame = ~k, text = ~place, type = "scatter",
mode = "markers+text", textposition = ~tp, color = I("#2c3e50"),
marker = list(color = "#2c3e50", size = 9), textfont = list(size = 12),
hovertemplate = "%{text}<extra></extra>") |>
add_trace(data = fit_txt, x = ~x, y = ~y, frame = ~k, text = ~txt, type = "scatter", mode = "text",
textfont = list(size = 12, color = col_wait), hoverinfo = "skip") |>
add_trace(data = pair_mds, x = ~d1, y = ~d2, frame = ~k, type = "scatter", mode = "lines",
color = I(col_a2), line = list(color = col_a2, dash = "dash", width = 1.5), hoverinfo = "skip")
p <- subplot(p_map, p_mds, widths = c(0.42, 0.58), margin = 0.05) |>
layout(showlegend = FALSE, margin = list(t = 90),
xaxis = list(title = "west - east (km)", range = c(-7, 8.5), zeroline = FALSE),
yaxis = list(title = "south - north (km)", range = c(-5, 5), scaleanchor = "x", zeroline = FALSE),
xaxis2 = list(title = "MDS dimension 1 (minutes)", range = c(-22, 22), zeroline = FALSE),
yaxis2 = list(title = "MDS dimension 2", range = c(-20, 20), scaleanchor = "x2", zeroline = FALSE),
annotations = list(
list(x = 0, xanchor = "left", y = 1.09, xref = "paper", yref = "paper", showarrow = FALSE,
align = "left", font = list(size = 15),
text = sprintf("On the map<br><span style='font-size:12px'>Stadium to Grocery: %.1f km apart, %.1f km by road</span>",
D_straight["Stadium", "Grocery"], D_drive["Stadium", "Grocery"])),
list(x = 1, xanchor = "right", y = 1.09, xref = "paper", yref = "paper", showarrow = FALSE,
align = "right", font = list(size = 15),
text = "Rebuilt from travel times (MDS)<br><span style='font-size:12px'>grey line: the road, in driving order</span>"))) |>
animation_opts(frame = 150, transition = 0, redraw = TRUE) |>
animation_slider(currentvalue = list(prefix = "waiting time at the construction site: ", suffix = " minutes"))
fig <- finalize_animation(p, list(), start_frame = wlab(0), prefix = "waiting time at the construction site: ",
suffix = " minutes")
fig$x$layout$updatemenus <- head(fig$x$layout$updatemenus, -1)
fig$height <- height
fig
}
# draw the figure
fig_loop()Here is what MDS was given: two distance matrices \(\mathbf D\), one without waiting (left) and one with a wait of 15 minutes (right). The entry \(d_{st}\) in row \(s\) and column \(t\) is the travel time between places \(s\) and \(t\):
f0 <- function(x) formatC(x, format = "f", digits = 0, big.mark = ",")
D_wait <- function(w) { # travel times (minutes) with a wait of w minutes at the site
a <- abs(outer(s_min, s_min, "-"))
D <- pmin(a, T_loop - a + w)
dimnames(D) <- list(places$place, places$place); D
}
fig_loop_tables <- function(w = w_show, title = TRUE) {
lev <- places$place
tab <- function(D, ttl) {
d <- as_tibble(as.table(D), .name_repair = ~ c("from", "to", "min")) |>
mutate(from = factor(from, levels = rev(lev)), to = factor(to, levels = lev))
d
}
d0 <- tab(D_wait(0)) |> mutate(panel = "No waiting")
d1 <- tab(D_wait(w)) |> mutate(panel = sprintf("Wait of %d minutes at the site", w))
d1$changed <- abs(d1$min - d0$min) > 1e-8
d0$changed <- FALSE
d <- bind_rows(d0, d1) |> mutate(panel = factor(panel, levels = unique(panel)))
ggplot(d, aes(to, from)) +
geom_tile(aes(fill = min), colour = "white", linewidth = 0.6) +
geom_tile(data = filter(d, changed), fill = NA, colour = col_wait, linewidth = 1.1) +
geom_text(aes(label = f0(min), colour = min > 18), size = 3.4) +
scale_colour_manual(values = c(`TRUE` = "white", `FALSE` = "black"), guide = "none") +
scale_fill_gradient(low = "#f7fbff", high = "#08306b", name = expression(italic(d)[st] ~ "(min)")) +
facet_wrap(~ panel) + coord_equal() +
labs(x = expression("column" ~ italic(t)), y = expression("row" ~ italic(s)),
title = if (title) expression("Two distance matrices" ~ bold(D) * ": the travel time" ~ italic(d)[st] ~
"between places" ~ italic(s) ~ "and" ~ italic(t))) +
theme(axis.text.x = element_text(angle = 45, hjust = 1), panel.grid = element_blank(),
strip.text = element_text(size = 13, face = "bold"), plot.title = element_text(size = 14))
}
# draw the figure
fig_loop_tables()
This is what a distance matrix looks like. The diagonal is zero, since getting from a place to itself takes no time, and the matrix is symmetric: the trip from the Church to the School takes as long as the trip back. Without waiting, each trip takes the shorter way around the loop. With the wait, the trips outlined in orange get longer: exactly those whose shortest way passes the site. A trip gets longer only until going around the other way is quicker; after that, the trip avoids the site.
MDS never saw the map of the town, only such a distance matrix. Yet it recovered what matters for travel: the order of the places around the loop, and roughly how far apart they are in minutes. Only roughly, though: no map, in any number of dimensions, has travel times around a loop as its straight-line distances (Section 5.6.3 shows why). The ring is the best two-dimensional approximation that classical MDS finds, and without waiting its distances are 2.0 minutes off the travel times on average (the average distance error under the map). With a long wait, the travel times become distances along a line, and the line reproduces every one of them exactly. The rest of the chapter explains how this works, what MDS can and cannot recover, and where else the idea turns up.
Check your understanding
- MDS starts from
- a data matrix of \(n\) observations on \(p\) variables
- a table of distances between the observations
- a covariance matrix
- a set of unit-variance shocks
- With a long wait at the construction site, MDS of the travel times returns a line because
- the places lie on a straight road
- nobody drives through the site, so the trips run along one stretch of road, like distances on a line
- the travel times are all equal
- MDS can only find one dimension
Answers
1 b. 2 b.5.2 The distance matrix
5.2.1 Distances from coordinates
When the observations have coordinates, the straight-line distance between two of them is the Euclidean distance of Chapter 2,
\[ d_{st}=\lVert \mathbf x_s-\mathbf x_t\rVert=\sqrt{\sum_{j=1}^p (x_{sj}-x_{tj})^2} . \]
Collecting all of them gives the \(n\times n\) distance matrix \(\mathbf D\), with entry \(d_{st}\) in row \(s\) and column \(t\), just like the travel-time matrices of Section 5.1. Every distance matrix has zeros on the diagonal (\(d_{tt}=0\)), is symmetric (\(d_{st}=d_{ts}\)), has no negative entries, and satisfies the triangle inequality, \(d_{su}\le d_{st}+d_{tu}\): a detour through \(t\) is never shorter. So the table holds \(n(n-1)/2\) distinct numbers, the entries above the diagonal.
For an example with a known answer, take the 48 contiguous states (without Alaska and Hawaii), each represented
by its centre (R’s state.center), and put the centres on a flat map in km, east and north of the middle of the
country. On this map the distances are Euclidean. Here are five of them:
us_D <- as.matrix(dist(us_X)) # all 48 x 48 distances between the state centres (km)
round(us_D[c("WA", "CA", "TX", "FL", "ME"), c("WA", "CA", "TX", "FL", "ME")])
## WA CA TX FL ME
## WA 0 1204 2529 3925 4374
## CA 1204 0 1894 3415 4485
## TX 2529 1894 0 1522 3009
## FL 3925 3415 1522 0 2246
## ME 4374 4485 3009 2246 05.2.2 Can we go back?
Suppose we are given only the table \(\mathbf D\): the 1,128 distances between the 48 states, and no map. Can we find the coordinates of the states? There is plenty of information: a map with two coordinates per state needs 96 numbers, and the table holds 1,128. Classical MDS (explained in the next section) does exactly this. Here is its answer next to the real map:
us_panel <- function(R = diag(2), title = NULL, subtitle = NULL, xl = "east (km)", yl = "north (km)",
lim = 2900, col = "#2c3e50", ylim_frac = 0.72) {
P <- us_X %*% R; B <- as.matrix(us_borders[, c("east", "north")]) %*% R
ggplot() +
geom_path(data = tibble(x = B[, 1], y = B[, 2], g = us_borders$group), aes(x, y, group = g),
colour = "grey80", linewidth = 0.3) +
geom_text(data = tibble(x = P[, 1], y = P[, 2], lab = us48$abb), aes(x, y, label = lab),
size = 2.5, colour = col, fontface = "bold") +
coord_equal(xlim = c(-lim, lim), ylim = c(-lim, lim) * ylim_frac) +
labs(title = title, subtitle = subtitle, x = xl, y = yl) +
theme(plot.title = element_text(size = 13, face = "bold"), plot.subtitle = element_text(size = 10))
}
fig_us_recover <- function() {
us_panel(title = "The map", subtitle = "state centres, km from the middle of the country") +
us_panel(us_R, title = "Rebuilt from the distances alone", subtitle = "classical MDS of the 48 x 48 table",
xl = "MDS dimension 1 (km)", yl = "MDS dimension 2 (km)", col = col_a1)
}
# draw the figure
fig_us_recover()
The shape is perfect: measured on the rebuilt map, no distance differs from the table by more than 7e-12 km, a rounding error. But the map came out upside down, flipped over from top to bottom: Florida at the top, Washington and Maine at the bottom, and the west still on the left. That is no mistake. Turning the map, or flipping it over, changes no distance at all, so all three of these maps have exactly the distances of the table:
us_panel <- function(R = diag(2), title = NULL, subtitle = NULL, xl = "east (km)", yl = "north (km)",
lim = 2900, col = "#2c3e50", ylim_frac = 0.72) {
P <- us_X %*% R; B <- as.matrix(us_borders[, c("east", "north")]) %*% R
ggplot() +
geom_path(data = tibble(x = B[, 1], y = B[, 2], g = us_borders$group), aes(x, y, group = g),
colour = "grey80", linewidth = 0.3) +
geom_text(data = tibble(x = P[, 1], y = P[, 2], lab = us48$abb), aes(x, y, label = lab),
size = 2.5, colour = col, fontface = "bold") +
coord_equal(xlim = c(-lim, lim), ylim = c(-lim, lim) * ylim_frac) +
labs(title = title, subtitle = subtitle, x = xl, y = yl) +
theme(plot.title = element_text(size = 13, face = "bold"), plot.subtitle = element_text(size = 10))
}
fig_us_versions <- function() {
turn <- function(deg) rotation_matrix(deg * pi / 180)
sub <- "every distance as in the table"
one <- function(R, ttl) us_panel(R, title = ttl, subtitle = sub, xl = "dimension 1", yl = "dimension 2",
col = col_a1, lim = 2800, ylim_frac = 1)
one(us_R, "As computed") + one(us_R %*% turn(90), "Turned by 90°") + one(us_R %*% diag(c(1, -1)), "Mirrored") +
plot_layout(nrow = 1)
}
# draw the figure
fig_us_versions()
Flipping the computed map over (right) happens to give back the real map, turned by only 2°. Nothing in the table could have told MDS to do that. Turn the rebuilt map with the slider: at every angle it fits the 1,128 distances equally well, so the table cannot tell which way is north. The computed map is a mirror image of the real one, so no angle brings back the real map: that takes a flip. (The other two numbers above the map come back in Section 5.3.)
pct <- function(x, d = 0) paste0(formatC(100 * x, format = "f", digits = d), "%")
f0 <- function(x) formatC(x, format = "f", digits = 0, big.mark = ",")
fig_us_rotate <- function(step = 10) {
angs <- seq(0, 360 - step, by = step)
P0 <- us_X %*% us_R; O0 <- us_outline %*% us_R
fr_pts <- purrr::map_dfr(angs, function(a) { P <- P0 %*% rotation_matrix(a * pi / 180)
tibble(x = P[, 1], y = P[, 2], lab = us48$abb, k = a) })
fr_out <- purrr::map_dfr(angs, function(a) { O <- O0 %*% rotation_matrix(a * pi / 180)
tibble(x = O[, 1], y = O[, 2], k = a) })
# What changes with the angle: the correlation of the two coordinates and the share of the spread on dimension 1
fr_txt <- purrr::map_dfr(angs, function(a) { P <- P0 %*% rotation_matrix(a * pi / 180); v <- apply(P, 2, var)
r <- sub("^-(0\\.00)$", "\\1", sprintf("%.2f", cor(P[, 1], P[, 2])))
tibble(x = 0, y = 0, k = a,
txt = sprintf("At every angle: the same %s distances<br>correlation of the coordinates: %s; dimension 1 carries %s of the spread",
f0(choose(48, 2)), r, pct(v[1] / sum(v)))) })
jump <- function(lab, a) list(label = lab, method = "animate",
args = list(list(as.character(a)), list(mode = "immediate",
frame = list(duration = 0, redraw = TRUE), transition = list(duration = 0))))
txt_panel <- plot_ly() |>
add_trace(data = fr_txt, x = ~x, y = ~y, frame = ~k, text = ~txt, type = "scatter", mode = "text",
textfont = list(size = 12, color = "#2c3e50"), hoverinfo = "skip", showlegend = FALSE)
map_panel <- plot_ly() |>
add_trace(data = fr_out, x = ~x, y = ~y, frame = ~k, type = "scatter", mode = "lines",
line = list(color = "#bbbbbb", width = 1.5), hoverinfo = "skip", showlegend = FALSE) |>
add_trace(data = fr_pts, x = ~x, y = ~y, frame = ~k, text = ~lab, type = "scatter", mode = "text",
textfont = list(size = 11, color = col_a1), hoverinfo = "skip", showlegend = FALSE)
subplot(txt_panel, map_panel, nrows = 2, heights = c(0.1, 0.9), margin = 0.01, titleX = TRUE, titleY = TRUE) |>
layout(xaxis = list(visible = FALSE, range = c(-1, 1), fixedrange = TRUE),
yaxis = list(visible = FALSE, range = c(-1, 1), fixedrange = TRUE),
xaxis2 = list(title = "dimension 1 (km)", range = c(-3000, 3000), zeroline = TRUE, zerolinecolor = "#e5e5e5"),
yaxis2 = list(title = "dimension 2 (km)", range = c(-3000, 3000), scaleanchor = "x2", zeroline = TRUE,
zerolinecolor = "#e5e5e5"),
margin = list(t = 50)) |>
animation_opts(frame = 120, transition = 0, redraw = TRUE) |>
animation_slider(currentvalue = list(prefix = "turned by ", suffix = "°")) |>
animation_button(label = "Play") |>
finalize_animation(list(jump("as computed", 0), jump("turned 90°", 90), jump("turned 180°", 180)),
start_frame = "0", prefix = "turned by ", suffix = "°")
}
# draw the figure
fig_us_rotate()A distance matrix \(\mathbf D\) determines the points up to a shift, a rotation and a reflection, the movements that keep every distance the same. To pin down the actual coordinates, we need assumptions from outside the table: where the middle is, which way is north, which side is east.
How many such assumptions it takes depends on the number of dimensions. A map in two dimensions can be turned in only one way, so one angle, which way is north, fixes it; one more fact, which side is east, rules out the mirror image. Points in three dimensions can be turned in three ways, like an aeroplane:
- Roll tilts the wings left or right.
- Pitch points the nose up or down.
- Yaw points the nose left or right.
rot2 <- function(P, deg) { a <- deg * pi / 180; P %*% t(rbind(c(cos(a), -sin(a)), c(sin(a), cos(a)))) }
fig_attitude <- function(roll = 30, pitch = 25, yaw = 35) {
top <- rbind(c(2.3, 0), c(2.0, -0.18), c(0.55, -0.18), c(-0.35, -2.5), c(-0.7, -2.5), c(-0.4, -0.18),
c(-1.6, -0.15), c(-1.95, -0.95), c(-2.2, -0.95), c(-2.15, -0.1))
top <- rbind(top, top[nrow(top):2, ] %*% diag(c(1, -1))) # mirror the right half to the left
top <- cbind(-top[, 2], top[, 1]) # seen from above: nose up, left wing left
side_body <- rbind(c(2.3, 0.02), c(2.0, 0.17), c(-1.6, 0.17), c(-2.2, 0.08), c(-2.2, -0.06), c(-1.6, -0.14),
c(1.9, -0.17), c(2.3, -0.04)) # seen from the side: nose to the right
side_fin <- rbind(c(-1.5, 0.15), c(-2.05, 1.05), c(-2.25, 1.05), c(-2.18, 0.1))
back_wing <- rbind(c(-2.5, 0.04), c(2.5, 0.04), c(2.5, -0.04), c(-2.5, -0.04)) # seen from behind
back_fin <- rbind(c(-0.06, 0), c(0.06, 0), c(0.04, 1.05), c(-0.04, 1.05))
back_stab <- rbind(c(-0.95, 0.32), c(0.95, 0.32), c(0.95, 0.27), c(-0.95, 0.27))
t_c <- seq(0, 2 * pi, length.out = 40); body <- cbind(0.22 * cos(t_c), 0.22 * sin(t_c))
poly <- function(P, id) tibble(x = P[, 1], y = P[, 2], id = id)
panel <- function(shapes, deg, dots, title, sub, arc) {
ghost <- bind_rows(lapply(seq_along(shapes), function(i) poly(shapes[[i]], i)))
turned <- bind_rows(lapply(seq_along(shapes), function(i) poly(rot2(shapes[[i]], deg), i)))
D1 <- rot2(as.matrix(dots[, c("x", "y")]), deg)
ggplot() +
geom_polygon(data = ghost, aes(x, y, group = id), fill = NA, colour = "#bbbbbb", linetype = "22",
linewidth = 0.5) +
geom_polygon(data = turned, aes(x, y, group = id), fill = "#2c3e50", colour = "#2c3e50", linewidth = 0.4) +
geom_point(data = tibble(x = D1[, 1], y = D1[, 2], k = dots$k), aes(x, y, colour = k), size = 2.8,
show.legend = FALSE) +
annotate("curve", x = arc[1], y = arc[2], xend = arc[3], yend = arc[4], curvature = arc[5],
arrow = arrow(length = unit(0.18, "cm"), type = "closed"), colour = col_a2, linewidth = 0.7) +
scale_colour_manual(values = c(left = "#d62728", right = "#2ca02c", nose = col_wait)) +
coord_equal(xlim = c(-2.9, 2.9), ylim = c(-2.6, 2.6)) + theme_void() +
labs(title = title, subtitle = sub) +
theme(plot.title = element_text(size = 13, face = "bold", hjust = 0.5),
plot.subtitle = element_text(size = 10.5, hjust = 0.5, colour = "grey30"))
}
p_roll <- panel(list(back_wing, back_fin, back_stab, body), roll,
tibble(x = c(-2.5, 2.5), y = 0, k = c("left", "right")),
"Roll", "tilts the wings left or right\n(seen from behind)", c(2.6, 0.9, 2.0, 1.9, 0.3))
p_pitch <- panel(list(side_body, side_fin), pitch, tibble(x = 2.3, y = 0, k = "nose"),
"Pitch", "points the nose up or down\n(seen from the side)", c(2.6, 0.5, 2.0, 1.55, 0.3))
p_yaw <- panel(list(top), yaw, tibble(x = 0, y = 2.3, k = "nose"),
"Yaw", "points the nose left or right\n(seen from above)", c(0.5, 2.55, -0.8, 2.35, 0.3))
p_roll + p_pitch + p_yaw + plot_layout(nrow = 1)
}
# draw the figure
fig_attitude()
None of the three changes the distance between any two points of the plane. So a table of distances between, say, its nose, its wing tips and its tail fixes the shape of the plane but not how it is turned: that takes three facts from outside the table, one for each angle. In \(p\) dimensions a rotation has \(p(p-1)/2\) angles: one in two dimensions, three in three, six in four. It is the same count as the free angles of \(A\) in Section 3.7, where the shocks could be turned without changing \(\Sigma\).
This is the same problem as in the Introduction. There, many matrices \(A\) gave the same covariance matrix \(\Sigma\), and they differed by a rotation of the shocks. Here, many maps give the same distance matrix \(\mathbf D\), and they differ by a rotation (or reflection) of the map.
Check your understanding
- A distance matrix of \(n=10\) observations holds how many distinct distances?
- 10
- 45
- 90
- 100
- Turning a map by 30 degrees changes
- every distance
- only the distances to the centre
- no distance
- the distances along the direction of the turn
- From a table of distances alone, we can find
- the exact coordinates, including which way is north
- the coordinates up to a shift, a rotation and a reflection
- only the order of the points along a line
- nothing, without the original data
Answers
1 b (\(10\cdot 9/2\)). 2 c. 3 b.5.3 How classical MDS finds the coordinates
5.3.1 From distances to inner products
Classical MDS does not turn the distances into coordinates directly. It takes a detour through inner products, which are easy to split into coordinates (Section 5.3.2). A small example shows what they are: three points on a map, \(\mathbf x_1=(-4,-1)'\), \(\mathbf x_2=(2,-1)'\) and \(\mathbf x_3=(2,2)'\), placed so that their mean, the centre, is at the origin.
fig_inner <- function() {
P <- tibble(id = rownames(ex3_X), x = ex3_X[, 1], y = ex3_X[, 2], b = diag(ex3_B))
P$lab <- sprintf("italic(b)[%s%s] == %d", P$id, P$id, P$b)
pr <- tibble(s = c(1, 2, 1), t = c(2, 3, 3)) |>
mutate(x = ex3_X[s, 1], y = ex3_X[s, 2], xend = ex3_X[t, 1], yend = ex3_X[t, 2],
d2 = round(ex3_D[cbind(s, t)]^2),
lab = ifelse(sqrt(d2) == round(sqrt(d2)), sprintf("italic(d)[%d%d] == %d", s, t, round(sqrt(d2))),
sprintf("italic(d)[%d%d] == sqrt(%d)", s, t, d2)),
lx = c(-1, 2.3, -1.25), ly = c(-1.38, 0.5, 0.95), hj = c(0.5, 0, 0.5))
ggplot() + axes0 +
geom_segment(data = pr, aes(x, y, xend = xend, yend = yend), linetype = "dashed", colour = "grey55") +
geom_text(data = pr, aes(lx, ly, label = lab, hjust = hj), parse = TRUE, size = 4.2, colour = "grey30") +
geom_segment(data = P, aes(0, 0, xend = x, yend = y), colour = col_a1, linewidth = 1,
arrow = arrow(length = unit(0.22, "cm"), type = "closed")) +
geom_point(data = P, aes(x, y), size = 3, colour = "#2c3e50") +
geom_text(data = P, aes(x, y, label = id), nudge_x = c(-0.3, 0.3, 0.3), nudge_y = c(0, -0.15, 0.15),
size = 5, fontface = "bold", colour = "#2c3e50") +
geom_text(data = P, aes(x + c(-0.3, 0.3, 0.3), y + c(-0.42, -0.55, 0.55), label = lab), parse = TRUE,
size = 4, colour = col_a1, hjust = c(0.8, 0, 0)) +
annotate("point", x = 0, y = 0, shape = 3, size = 4, stroke = 1.2) +
annotate("text", x = -0.15, y = 0.32, label = "centre", hjust = 1, size = 4, colour = "grey30") +
scale_x_continuous(breaks = -5:3) + scale_y_continuous(breaks = -2:3) +
coord_equal(xlim = c(-5.2, 3.9), ylim = c(-1.8, 2.9)) +
labs(x = "coordinate 1", y = "coordinate 2",
subtitle = expression("arrows from the centre, with squared lengths" ~ italic(b)[tt] *
"; dashed: distances" ~ italic(d)[st]))
}
# draw the figure
fig_inner()
The inner product of two points multiplies their coordinates one by one and adds up the products:
\[ b_{st}=\mathbf x_s'\mathbf x_t=x_{s1}x_{t1}+x_{s2}x_{t2} . \]
For points 1 and 3, \(b_{13}=(-4)(2)+(-1)(2)=-10\). The inner product of a point with itself is its squared length, the squared distance from the centre: \(b_{11}=(-4)^2+(-1)^2=17\). All inner products together form the \(n\times n\) matrix \(B\), here
\[ B=\begin{pmatrix} 17 & -7 & -10\\ -7 & 5 & 2\\ -10 & 2 & 8\end{pmatrix} . \]
In matrix notation, \(B=\mathbf X\mathbf X'\), where row \(t\) of the data matrix \(\mathbf X\) holds the coordinates of point \(t\). The inner product measures how much the arrows from the centre to two points point the same way: \(b_{st}=\lVert\mathbf x_s\rVert\,\lVert\mathbf x_t\rVert\cos\theta_{st}\), where \(\theta_{st}\) is the angle between the arrows. It is positive when they point in similar directions (points 2 and 3), negative when they point in roughly opposite directions (point 1 against points 2 and 3), and zero at a right angle.
Inner products and distances are linked by the law of cosines of school geometry. Multiplying out \(d_{st}^2=(\mathbf x_s-\mathbf x_t)'(\mathbf x_s-\mathbf x_t)\) gives
\[ d_{st}^2=b_{ss}+b_{tt}-2\,b_{st} . \]
For points 1 and 3, \(d_{13}^2=17+8-2(-10)=45\), so \(d_{13}=\sqrt{45}\approx 6.7\), as in the figure.
Now suppose only the distances are known. Solved for the inner product, the law of cosines reads
\[ b_{st}=\tfrac12\left(b_{ss}+b_{tt}-d_{st}^2\right), \]
so we need the squared lengths \(b_{tt}\) first. The centre is not in the table, but because it is the mean of the points, the squared lengths follow from the distances as well:
\[ b_{tt}=\bar d^{\,2}_{t\cdot}-\tfrac12\,\bar d^{\,2}_{\cdot\cdot} , \]
where \(\bar d^{\,2}_{t\cdot}\) is the average squared distance from point \(t\) to all points (the row mean of the squared distances) and \(\bar d^{\,2}_{\cdot\cdot}\) is the average over the whole table. To see why, average the law of cosines over \(s\). The \(b_{ss}\) average to the mean squared length \(\bar b\), and the \(b_{st}\) average to zero, because \(\sum_s\mathbf x_s'\mathbf x_t=(\sum_s\mathbf x_s)'\mathbf x_t\) and the points add up to the centre, \(\mathbf 0\). So \(\bar d^{\,2}_{t\cdot}=\bar b+b_{tt}\), and averaging once more over \(t\) gives \(\bar d^{\,2}_{\cdot\cdot}=2\bar b\).
For the three points, square the distances and take the means:
| \(d_{st}^2\) | \(t=1\) | \(t=2\) | \(t=3\) | row mean |
|---|---|---|---|---|
| \(s=1\) | 0 | 36 | 45 | 27 |
| \(s=2\) | 36 | 0 | 9 | 15 |
| \(s=3\) | 45 | 9 | 0 | 18 |
The overall mean is 20. So \(b_{11}=27-10=17\), \(b_{22}=15-10=5\) and \(b_{33}=18-10=8\), and then, for example, \(b_{13}=\tfrac12(17+8-45)=-10\). Every entry of \(B\) comes back, from the distances alone.
The two steps combine into one formula,
\[ b_{st}=-\tfrac12\left(d_{st}^2-\bar d^{\,2}_{s\cdot}-\bar d^{\,2}_{\cdot t}+\bar d^{\,2}_{\cdot\cdot}\right). \]
In words: square the distances, subtract the row and column means, add back the overall mean, and multiply by \(-\tfrac12\). This is called double centring. In matrix form,
\[ B=-\frac12\,J\,\mathbf D^{(2)}J , \]
where \(\mathbf D^{(2)}\) holds the squared distances (each entry squared, not the matrix product \(\mathbf D\mathbf D\)) and \(J=I-\frac1n\mathbf 1\mathbf 1'\) subtracts means. Shifting all points changes no distance, so the table cannot know where the origin was; double centring simply puts it at the centre, the mean of the points. In R:
X3 <- rbind(c(-4, -1), c(2, -1), c(2, 2)) # three points, centred
D3 <- as.matrix(dist(X3)) # their distance matrix
J <- diag(3) - 1/3 # subtracts means
round(-0.5 * J %*% D3^2 %*% J, 10) # double centring: B from the distances
## [,1] [,2] [,3]
## [1,] 17 -7 -10
## [2,] -7 5 2
## [3,] -10 2 8
X3 %*% t(X3) # B from the coordinates: the same
## [,1] [,2] [,3]
## [1,] 17 -7 -10
## [2,] -7 5 2
## [3,] -10 2 85.3.2 From inner products to coordinates
\(B\) is symmetric, so it has an eigendecomposition like the covariance matrix in Chapter 4, \(B=V\Lambda V'\), with the eigenvectors as the columns of \(V\) and the eigenvalues \(\lambda_1\ge\lambda_2\ge\dots\) in the diagonal matrix \(\Lambda\). (Chapter 4 called the eigenvectors \(Q\); here \(Q\) is kept for a rotation of the map.) Coordinates that reproduce \(B\) are
\[ \hat{\mathbf X}=V\Lambda^{1/2},\qquad\text{since}\qquad \hat{\mathbf X}\hat{\mathbf X}'=V\Lambda^{1/2}\Lambda^{1/2}V'=B . \]
Since \(B\) comes from \(\mathbf D\) alone, this is how the maps of this chapter were made from the distances only: double centring gives \(B\), and its eigendecomposition gives the coordinates. But \(\hat{\mathbf X}\) is not the only answer. Turn it with any rotation or reflection \(Q\), so that \(Q'Q=I\). The turned coordinates \(\hat{\mathbf X}Q\) give
\[ (\hat{\mathbf X}Q)(\hat{\mathbf X}Q)'=\hat{\mathbf X}QQ'\hat{\mathbf X}'=\hat{\mathbf X}\hat{\mathbf X}'=B , \]
the same inner products, and so the same distances. Geometrically, turning the points around the centre changes neither the lengths of the arrows nor the angles between them. So the coordinates are identified only up to a rotation or reflection, as the maps of the states in Section 5.2 showed.
Each eigenvalue gives one dimension of the map. Distances computed from \(p\) coordinates give at most \(p\) positive eigenvalues, and the rest are zero. For the three points, the eigenvalues of \(B\) are 25.8, 4.2 and 0. For the states, the eigenvalues of \(B\) are 76,952,297 and 12,861,163, followed by zeros, so two dimensions rebuild the table exactly. To draw a map in \(m\) dimensions, keep the \(m\) largest eigenvalues. In R:
5.3.3 Which map MDS returns: the principal component scores
All turned maps \(\hat{\mathbf X}Q\) fit the distances equally well, so which one does classical MDS return? Its coordinates \(V\Lambda^{1/2}\) have a special property. They have mean zero, since the map is centred, and their covariance matrix is
\[ \frac{1}{n-1}\hat{\mathbf X}'\hat{\mathbf X}=\frac{1}{n-1}\Lambda^{1/2}V'V\Lambda^{1/2}=\frac{1}{n-1}\Lambda , \]
because the eigenvectors are perpendicular and have length one (\(V'V=I\)). This matrix is diagonal. So the coordinates of the MDS map are uncorrelated, and dimension \(j\) has the variance \(\lambda_j/(n-1)\): the first dimension carries the most spread, the second the most of what is left, and so on. Turning the map would mix the coordinates and make them correlated. The slider in Section 5.2 shows it. The correlation of the two coordinates is zero only when the map lines up with the long and the short axis of the country (at 0°, 90°, 180° and 270°), and dimension 1 carries the largest share of the spread only at 0° and 180°, where it runs along the long axis.
This is exactly the rule by which PCA chooses its rotation in Chapter 4: the principal component scores are uncorrelated, the first has the largest variance, the second the largest of what is left, and so on. So MDS and PCA line up the points in the same way and return the same coordinates. Only the sign of each column is open, since flipping a column keeps the coordinates uncorrelated and their variances unchanged; that is why the states came out upside down.
The algebra confirms this. Write the coordinates as in Chapter 4, \(\mathbf x_t=\Gamma\mathbf f_t\), with the rotation \(\Gamma\) and the principal component scores \(\mathbf f_t\). In rows, \(\mathbf X=\mathbf F\Gamma'\), where \(\mathbf F\) holds the scores. Then
\[ B=\mathbf X\mathbf X'=\mathbf F\Gamma'\Gamma\mathbf F'=\mathbf F\mathbf F' : \]
the rotation cancels. The columns of \(\mathbf F\) are uncorrelated scores with mean zero, so they are perpendicular, and each one, scaled to length one, is an eigenvector of \(B\) (for a column \(\mathbf f_j\) of \(\mathbf F\), \(B\mathbf f_j=\mathbf F(\mathbf F'\mathbf f_j)=\lVert\mathbf f_j\rVert^2\mathbf f_j\)). The eigenvalue is \(\lVert\mathbf f_j\rVert^2\), which is \(n-1\) times the variance of the scores. So \(V\Lambda^{1/2}=\mathbf F\):
Classical MDS of Euclidean distances returns the principal component scores of the coordinates (up to the signs of the columns): the orientation in which the coordinates are uncorrelated, with the largest variance first. This is why it is also called principal coordinates analysis (Gower 1966).
For the three points, PCA of the coordinates and MDS of the distances give the same map, up to signs:
round(prcomp(X3)$x, 3) # PCA scores of the three points
## PC1 PC2
## [1,] -4.118 0.202
## [2,] 1.624 -1.537
## [3,] 2.494 1.335
round(cmdscale(D3, k = 2), 3) # classical MDS of their distances: the same, up to signs
## [,1] [,2]
## 1 4.118 0.202
## 2 -1.624 -1.537
## 3 -2.494 1.335That is why the rebuilt map of the states lies flat: its first dimension is the direction of greatest spread, the long east-west axis of the country, as PCA would choose. The same holds with more variables. MDS of the Euclidean distances between the 50 states on the six standardised indicators of Chapter 4 (distances between their profiles, not their locations; Section 5.6 looks at them) returns their first two principal component scores, up to rounding errors (5e-14).
Check your understanding
- The inner product of the points \((1,2)'\) and \((3,-1)'\) is
- 1
- 5
- \(-1\)
- 7
- Double centring turns
- squared distances into inner products
- coordinates into distances
- a covariance matrix into a correlation matrix
- a rotation into a reflection
- Distances computed from three coordinates give a matrix \(B\) with
- one positive eigenvalue
- at most three positive eigenvalues, the rest zero
- \(n\) positive eigenvalues
- negative eigenvalues
- Classical MDS of Euclidean distances returns
- the original coordinates, including their orientation
- the principal component scores, up to signs
- the standardised shocks
- a random rotation of the coordinates
- The coordinates of a map from classical MDS are
- correlated, with equal variances
- uncorrelated, with the largest variance first
- always on a circle
- the same as the original coordinates
Answers
1 a (\(1\cdot3+2\cdot(-1)=1\)). 2 a. 3 b. 4 b. 5 b.5.4 From distances to latent coordinates: two steps or one
5.4.1 Two steps
Coming from a distance matrix, there is a long way to the latent coordinates of Chapter 4, in two steps:
- From \(\mathbf D\) to coordinates. Rebuild a map, which needs assumptions from outside the table: where the middle is, which way is north, which side is east.
- From the coordinates to latent coordinates. Write \(\mathbf x_t=A\boldsymbol\varepsilon_t=\Gamma\mathbf f_t\) and choose \(A\) and its split \(A=\Gamma D\), which needs the assumptions of Chapter 4. For PCA, the restriction is that the first column of \(A\) is as long as possible, and the normalisation that the columns of \(\Gamma\) have length one. The latent coordinates are then the principal component scores \(\mathbf f_t\).
5.4.2 The second step undoes the first
Suppose step 1 had chosen a different orientation, coordinates \(\tilde{\mathbf x}_t=Q\mathbf x_t\) for some rotation \(Q\). Their covariance matrix is \(QSQ'=(Q\Gamma)D^2(Q\Gamma)'\), so PCA finds the directions \(Q\Gamma\) and the scores
\[ \tilde{\mathbf f}_t=(Q\Gamma)'\tilde{\mathbf x}_t=\Gamma'Q'Q\mathbf x_t=\Gamma'\mathbf x_t=\mathbf f_t : \]
the same as before. Whatever orientation step 1 picks, step 2 turns it back, and the same holds for a reflection (\(Q'Q=I\) is all the argument used). The centre does not matter either, because PCA subtracts the mean anyway. Try it: the slider chooses the orientation of step 1 (left), and the PCA scores of step 2 (right) do not move.
us_scores <- function(X) { # PCA scores, signs fixed (Maine positive on both)
p <- prcomp(X); Fs <- p$x
sg <- sign(Fs["ME", ]); sweep(Fs, 2, sg, "*")
}
fig_two_steps <- function(step = 15, titles = c("Step 1: coordinates, in some orientation", "Step 2: their PCA scores"),
slider = "orientation chosen in step 1: ") {
angs <- seq(0, 360 - step, by = step)
fr <- purrr::map(angs, function(a) {
Q <- rotation_matrix(a * pi / 180)
Xa <- us_X %*% Q; Fa <- us_scores(Xa)
Ga <- solve(crossprod(Xa), crossprod(Xa, Fa)) # the PCA rotation for these coordinates
Oa <- us_outline %*% Q; OF <- Oa %*% Ga
list(pts = tibble(x = c(Xa[, 1], Fa[, 1]), y = c(Xa[, 2], Fa[, 2]), lab = rep(us48$abb, 2),
panel = rep(c("map", "scores"), each = nrow(Xa)), k = a),
out = tibble(x = c(Oa[, 1], OF[, 1]), y = c(Oa[, 2], OF[, 2]),
panel = rep(c("map", "scores"), each = nrow(Oa)), k = a))
})
pts <- bind_rows(purrr::map(fr, "pts")); out <- bind_rows(purrr::map(fr, "out"))
one <- function(pn, col) plot_ly() |>
add_trace(data = filter(out, panel == pn), x = ~x, y = ~y, frame = ~k, type = "scatter", mode = "lines",
line = list(color = "#bbbbbb", width = 1.2), hoverinfo = "skip", showlegend = FALSE) |>
add_trace(data = filter(pts, panel == pn), x = ~x, y = ~y, frame = ~k, text = ~lab, type = "scatter",
mode = "text", textfont = list(size = 9, color = col), hoverinfo = "skip", showlegend = FALSE)
ax <- function(t) list(title = t, range = c(-3000, 3000), zeroline = TRUE, zerolinecolor = "#e5e5e5")
subplot(one("map", "#2c3e50"), one("scores", col_a1), margin = 0.06, titleX = TRUE, titleY = TRUE) |>
layout(xaxis = ax("coordinate 1 (km)"), yaxis = c(ax("coordinate 2 (km)"), scaleanchor = "x"),
xaxis2 = ax("PCA score 1 (km)"), yaxis2 = c(ax("PCA score 2 (km)"), scaleanchor = "x2"),
margin = list(t = 80),
annotations = list(
list(x = 0.235, y = 1.02, xref = "paper", yref = "paper", showarrow = FALSE, xanchor = "center",
yanchor = "bottom", font = list(size = 14), text = titles[1]),
list(x = 0.765, y = 1.02, xref = "paper", yref = "paper", showarrow = FALSE, xanchor = "center",
yanchor = "bottom", font = list(size = 14), text = titles[2]))) |>
animation_opts(frame = 150, transition = 0, redraw = TRUE) |>
animation_slider(currentvalue = list(prefix = slider, suffix = "°")) |>
animation_button(label = "Play") |>
finalize_animation(list(), start_frame = "0", prefix = slider, suffix = "°")
}
# draw the figure
fig_two_steps()