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\). It is bold like the data matrix \(\mathbf X\) because it has one row for each observation, and so are the other matrices of this chapter with \(n\) rows.
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 \(\mathbf B\), here
\[ \mathbf B=\begin{pmatrix} 17 & -7 & -10\\ -7 & 5 & 2\\ -10 & 2 & 8\end{pmatrix} . \]
In matrix notation, \(\mathbf 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 \(\mathbf 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,
\[ \mathbf B=-\frac12\,\mathbf J\,\mathbf D^{(2)}\mathbf J , \]
where \(\mathbf D^{(2)}\) holds the squared distances (each entry squared, not the matrix product \(\mathbf D\mathbf D\)) and \(\mathbf 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
\(\mathbf B\) is symmetric, so it has an eigendecomposition like the covariance matrix in Chapter 4, \(\mathbf B=\mathbf VK \mathbf V'\), with the eigenvectors as the columns of \(\mathbf V\) and the eigenvalues \(\kappa_1\ge\kappa_2\ge\dots\) in the diagonal matrix \(K\). Coordinates that reproduce \(\mathbf B\) are
\[ \hat{\mathbf X}=\mathbf VK^{1/2},\qquad\text{since}\qquad \hat{\mathbf X}\hat{\mathbf X}'=\mathbf VK^{1/2}K^{1/2}\mathbf V'=\mathbf B . \]
Since \(\mathbf B\) comes from \(\mathbf D\) alone, this is how the maps of this chapter were made from the distances only: double centring gives \(\mathbf 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}'=\mathbf 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 \(\mathbf B\) are 25.8, 4.2 and 0. For the states, the eigenvalues of \(\mathbf B\) are 76,952,297 and 12,861,163, followed by zeros, so two dimensions rebuild the table exactly. To draw a map in \(k\) dimensions, keep the \(k\) 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 \(\mathbf VK^{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}K^{1/2}\mathbf V'\mathbf VK^{1/2}=\frac{1}{n-1}K , \]
because the eigenvectors are perpendicular and have length one (\(\mathbf V'\mathbf V=I\)). This matrix is diagonal. So the coordinates of the MDS map are uncorrelated, and dimension \(l\) has the variance \(\kappa_l/(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 row \(t\) of \(\mathbf F\) holds the scores \(\mathbf f_t'\). Then
\[ \mathbf B=\mathbf X\mathbf X'=\mathbf F\Gamma'\Gamma\mathbf F'=\mathbf F\mathbf F' : \]
the rotation cancels. The scores have mean zero and are uncorrelated, with the variances \(\delta_l^2\) of Chapter 4, so \(\mathbf F'\mathbf F=(n-1)\Delta^2\) is diagonal. Hence \(\mathbf B\mathbf F=\mathbf F(\mathbf F'\mathbf F)=(n-1)\,\mathbf F\Delta^2\): each column of \(\mathbf F\) is an eigenvector of \(\mathbf B\), with the eigenvalue \((n-1)\delta_l^2\), \(n-1\) times the variance of the scores. Scaled to length one, the columns of \(\mathbf F\) are the columns of \(\mathbf V\), so \(\mathbf VK^{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 \(\mathbf 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
Chapter 4 went from the data to latent coordinates by choosing \(A\). Starting from a distance matrix, the natural route has two steps:
- Rebuild a map from \(\mathbf D\). This needs facts from outside the table, such as where the middle is and which way is north (Section 5.2).
- Choose \(A\) on that map, as in Chapter 4.
The distances fix the shape of the cloud, but not which way each variable points in it. So step 1 is needed only if step 2 has to know which axis is which variable.
5.4.1 PCA needs no first step
Suppose step 1 had turned the map by some rotation \(Q\), giving the coordinates \(Q\mathbf x_t\) instead of \(\mathbf x_t\). Their covariance matrix is \(QSQ'=(Q\Gamma)\Delta^2(Q\Gamma)'\), so PCA finds the directions \(Q\Gamma\) and the scores
\[ (Q\Gamma)'Q\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 a reflection changes nothing either, since \(Q'Q=I\) is all the argument uses. 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()So classical MDS skips step 1 and goes straight from \(\mathbf D\) to the scores (Section 5.3). Only the assumptions of PCA remain: the first dimension has the largest variance, the next the largest of the rest, and so on, with the sign of each dimension left open. The loop road has no map to rebuild at all, since travel times along a road are not straight-line distances, and MDS still goes straight to its latent coordinates, the ring.
5.4.2 The roommates need no first step either
The roommates of Chapter 4 were paired at random, so they have no order. Swapping them must therefore leave the cloud of their GPA pairs unchanged, and the line halfway between their two GPA axes must be an axis of symmetry of the cloud. So the GPA axes lie at 45° to the axes of the cloud, and the map that MDS returns shows them:
fig_room_axes <- function() {
E <- t(ellipse_xy(diag(room_sd), r = 2))
ax <- tibble(xend = 1.25 / sqrt(2) * c(1, 1), yend = 1.25 / sqrt(2) * c(1, -1),
lab = c("roommate 1's GPA", "roommate 2's GPA"), vj = c(0, 1))
arc <- function(a0, a1, r = 0.42) { t <- seq(a0, a1, length.out = 30); tibble(x = r * cos(t), y = r * sin(t)) }
ggplot() + axes0 +
geom_point(data = tibble(x = room_map[, 1], y = room_map[, 2]), aes(x, y), colour = "grey60", alpha = 0.55,
size = 1.3) +
geom_path(data = tibble(x = E[, 1], y = E[, 2]), aes(x, y), colour = "#2c3e50", linewidth = 0.8) +
geom_path(data = arc(0, pi / 4), aes(x, y), colour = col_a2, linewidth = 0.6) +
geom_path(data = arc(-pi / 4, 0), aes(x, y), colour = col_a2, linewidth = 0.6) +
annotate("text", x = 0.6 * cos(c(pi / 8, -pi / 8)), y = 0.6 * sin(c(pi / 8, -pi / 8)), label = "45°", size = 3.8,
colour = col_a2) +
geom_segment(data = ax, aes(0, 0, xend = xend, yend = yend), colour = col_a2, linewidth = 1.1,
arrow = arrow(length = unit(0.22, "cm"), type = "closed")) +
geom_text(data = ax, aes(xend + 0.04, yend, label = lab, vjust = vj), hjust = 0, size = 4.2, colour = col_a2,
fontface = "bold") +
annotate("text", x = 2.15, y = 0.04, label = "long axis:\nboth GPAs rise", hjust = 1, vjust = 0, size = 3.6,
colour = "grey35", lineheight = 0.9) +
coord_equal(xlim = c(-1.65, 2.15), ylim = c(-1.15, 1.15)) +
labs(x = "first dimension of the MDS map", y = "second dimension",
title = "The MDS map of 200 pairs of roommates",
subtitle = "No order: the two GPA axes lie at 45° to the axes of the cloud") +
theme(plot.title = element_text(size = 13, face = "bold"), plot.subtitle = element_text(size = 12),
axis.text = element_blank(), panel.grid = element_blank())
}
# draw the figure
fig_room_axes()
The rest follows from the two standard deviations of the map, the principal component standard deviations \(\delta_1=0.6\) and \(\delta_2=0.4\). In GPA coordinates, the axes of the cloud point along \((1,1)'/\sqrt2\), where both GPAs rise, and \((1,-1)'/\sqrt2\). With \(\Gamma\) the matrix of these two columns and \(\Delta=\operatorname{diag}(\delta_1,\delta_2)\), the covariance matrix is \(S=\Gamma\Delta^2\Gamma'\), and its symmetric root is
\[ A=\Gamma\Delta\,\Gamma'=\frac12\begin{pmatrix}\delta_1+\delta_2&\delta_1-\delta_2\\ \delta_1-\delta_2&\delta_1+\delta_2\end{pmatrix}, \]
since this \(A\) is symmetric and \(AA'=\Gamma\Delta^2\Gamma'=S\). With ones on the diagonal of \(C\) (Section 4.1), the peer effect is
\[ c_{12}=c_{21}=\frac{a_{12}}{a_{22}}=\frac{\delta_1-\delta_2}{\delta_1+\delta_2}=\frac{0.6-0.4}{0.6+0.4}=0.20 , \]
the value of Chapter 4, from the distances alone. As with PCA, starting from \(\mathbf D\) adds no assumption: “neither roommate comes first” is the assumption the symmetric root makes anyway. The distances fix the size of the peer effect, though not its sign. They cannot tell whether both GPAs rise along the long axis of the cloud, as drawn, or along the short one, which would mean that the roommates hurt each other.
5.4.3 When the first step is needed
A first step is needed when step 2 has an order, that is, when it must know which axis is which variable. Cholesky always has one, since the regressor comes first. A structural restriction names a particular variable, such as the manual’s fuel flow for the headwind. And the roommates would have an order if one of them came first, say a senior paired with a first-year student. Their GPAs would then differ in how much they vary, their axes could lie at any angle to the axes of the cloud, and every angle would give different peer effects. In each case, information from outside the table must turn the map into place before step 2 can start.
A first step is needed only when step 2 must know which axis is which variable. PCA never needs it, and neither do the roommates, who have no order. From a table of distances, classical MDS goes straight to latent coordinates, with the assumptions of PCA alone.
Check your understanding
- Turning the coordinates by a rotation \(Q\) before running PCA
- turns the scores by \(Q\) as well
- leaves the scores unchanged, because the directions turn by \(Q\) too
- changes the variances of the components
- makes PCA impossible
- Going from distances straight to the scores saves the assumption about
- which component has the largest variance
- the orientation of the map, such as which way is north
- the number of observations
- the units of the distances
- Roommates paired at random have no order. From the distances between their pairs of GPAs,
- their GPA axes lie at 45° to the axes of the cloud, so no first step is needed
- a first step must find which axis is which roommate
- the peer effect is zero
- nothing can be learned about the peer effect
- Starting from a distance matrix, which choice in step 2 needs a first step?
- PCA
- the symmetric root for roommates paired at random
- Cholesky
- none of them
Answers
1 b. 2 b. 3 a. 4 c.5.5 Distances learned from text: embeddings
5.5.1 From words to vectors
The same idea is at the heart of how AI models handle language. A computer cannot calculate with words, so before any learning the text is split into tokens (words or pieces of words, by a tokenizer), and each token of a vocabulary of \(n\) tokens is turned into a vector. This step is the encoding. The simplest version is one-hot encoding: token number \(t\) becomes a one-hot vector, a list of \(n\) numbers with a 1 in place \(t\) and zeros everywhere else (the \(t\)-th unit vector; “one-hot” because exactly one entry is switched on). With three words,
\[ \text{coke}=\begin{pmatrix}1\\0\\0\end{pmatrix},\qquad \text{pepsi}=\begin{pmatrix}0\\1\\0\end{pmatrix},\qquad \text{runway}=\begin{pmatrix}0\\0\\1\end{pmatrix}. \]
These vectors live in a Euclidean space, but its geometry says nothing: every two different words are the same distance \(\sqrt2\) apart, so “coke” is as far from “pepsi” as from “runway”. Meaning has to come from data.
This is the difference between an encoding and an embedding. An encoding describes each object by numbers. An embedding places the objects so that closeness in the space means something. The loop road shows the difference. The position along the road in minutes from the start, one number per place, is an encoding: the Church (minute 1) and the Stadium (minute 36) are far apart as numbers, but only 7 minutes apart by road. The ring that MDS drew is an embedding: places that are close by road are close on it. The one-hot vectors of the words are an encoding as well, and the task is to turn them into an embedding.
5.5.2 Distances from text
A language model is trained on huge amounts of text, and from it, it learns which words go together. The simplest way to turn “go together” into a distance is to measure it in the text itself: two words are close if they usually appear near each other, and far apart if they rarely do. For words \(s\) and \(t\), go to every place in the text where \(s\) appears, count how many words away the nearest \(t\) is, and average over all those places. Do the same from \(t\) to \(s\) and take the mean of the two. The result, \(d_{st}\), is the average distance between the two words in the text, counted in words. Words that often follow each other, the pairs a language model learns to predict, are only one or two words apart.
A small example makes this concrete. Take a made-up text of 4,339 words, written with 18 words from three themes of this course: drinks, flights and campus life (think of a real text with all other words removed). It comes in paragraphs on one theme each, and now and then students and pilots drink coffee. It starts like this:
writeLines(strwrap(paste(word_text[1:40], collapse = " "), width = 100))
## tea cup coffee tea coke sugar pepsi coke cup coke sugar sugar coke airport runway plane fuel fuel
## headwind plane fuel plane fuel airport pilot plane fuel plane exam grade exam student student
## roommate exam exam roommate grade student examMeasured over the whole text, “coke” and “pepsi” are on average 3.2 words apart, and “coke” and “runway” 22.6. The average distances of all pairs of words form a distance matrix \(\mathbf D\), just like the travel times of the loop road:
fig_word_D <- function(title = TRUE) {
lev <- word_vocab
d <- as_tibble(as.table(word_D), .name_repair = ~ c("w1", "w2", "d")) |>
mutate(w1 = factor(w1, levels = rev(lev)), w2 = factor(w2, levels = lev))
ggplot(d, aes(w2, w1, fill = d)) + geom_tile(colour = "white", linewidth = 0.4) +
scale_fill_gradient(low = "#08306b", high = "#f7fbff", name = "words\napart") +
coord_equal() + labs(x = NULL, y = NULL, title = if (title) expression("Distance matrix" ~ bold(D) * ": the average distance" ~
italic(d)[ij] ~ "in the text, in words")) +
theme(axis.text.x = element_text(angle = 60, hjust = 1, colour = col_th[word_theme[lev]]),
axis.text.y = element_text(colour = rev(col_th[word_theme[lev]])), panel.grid = element_blank())
}
# draw the figure
fig_word_D()
5.5.3 The embedding
Classical MDS of this distance matrix gives each word a set of coordinates. In machine learning, these coordinates are the word’s embedding, the number of dimensions is the embedding dimension, and the space they live in is the embedding space (or latent space). Closeness in the embedding space means that the words usually appear near each other:
fig_word_map <- function() {
d <- tibble(word = word_vocab, x = word_Y[, 1], y = word_Y[, 2], theme = word_theme[word_vocab])
ggplot(d, aes(x, y, colour = theme)) + axes0 +
geom_point(size = 2.4) +
geom_text_repel(aes(label = word), size = 4.2, seed = 3, show.legend = FALSE, max.overlaps = 30,
box.padding = 0.35) +
scale_colour_manual(values = col_th, name = "theme\n(not used\nby MDS)") +
coord_equal() + labs(x = "embedding dimension 1", y = "embedding dimension 2")
}
# draw the figure
fig_word_map()
MDS was never told the themes (the colours), yet each theme forms its own group. “Coffee” sits between the drinks and the other two themes, because in this text students and pilots drink coffee too. The dictionary between the two languages:
| MDS | machine learning |
|---|---|
| object (a word) | token |
| distance matrix \(\mathbf D\) | average distances between words in a lot of text |
| small distance \(d_{st}\) | usually near each other |
| coordinates of one object | its embedding vector |
| number of dimensions \(k\) | embedding dimension |
| the map | embedding space, latent space |
| any rotation fits equally well | the axes of an embedding need not mean anything on their own |
5.5.4 What real models do
Real models do not run classical MDS on a table of word pairs. They learn the embeddings while training a neural network to predict words from their neighbours (word2vec, Mikolov et al. 2013) or to predict the next token (the large language models behind today’s AI chatbots). Their training loss, the cross-entropy, is the average “surprise” \(-\log P\) of the word that actually comes next, so a model that has learned which words go together is rarely surprised. The embedding layer is an \(n\times k\) table, with one row for each of the \(n\) tokens in the vocabulary and one column for each of the \(k\) embedding dimensions; row \(t\) is the embedding of token \(t\): multiplying the one-hot vector of token \(t\) by this table picks out row \(t\), so the layer replaces the one-hot vector by a vector learned from data. The embedding dimension is a few hundred for word2vec and runs to many thousands for large language models (12,288 for GPT-3). The goal is the same as here, though: coordinates whose geometry reproduces how words are used. For word2vec this can be made precise. Its training amounts to factorising a table that says, for each pair of words, how much more often they occur together than they would by chance, on a log scale (Levy and Goldberg 2014), much as classical MDS factorises \(\mathbf B\). Directions can carry meaning too: in word2vec, “king” \(-\) “man” \(+\) “woman” lands close to “queen”. To look at a learned embedding, people project it to two dimensions, with PCA or MDS or with non-linear relatives such as t-SNE and UMAP.
And the rotation problem of this chapter applies too. Turning the whole embedding space changes no distance, so the axes of an embedding need not mean anything by themselves; the distances and directions between words do.
Check your understanding
- In one-hot encoding, the distance between two different words is
- small if the words are similar
- always \(\sqrt2\)
- zero
- the number of letters they differ in
- Measured as the average distance in a text, two words are close when they
- are spelled alike
- usually appear near each other
- have the same number of letters
- appear equally often
- Two words that are close in the embedding space
- are spelled alike
- usually appear near each other in the text
- have the same number of letters
- lie on the same axis
Answers
1 b. 2 b. 3 b.5.6 Other distances
5.6.2 The states under three distances
So far, the states were places, and their distances were kilometres. A distance matrix can just as well say how different the states are in other respects. Take the six indicators of Chapter 4: income, illiteracy, life expectancy, murder rate, high-school graduation and days of frost, standardised as there. Each state is then a point in a six-dimensional space, with one coordinate per indicator, and the Euclidean distance of Section 5.2 works the same way with six coordinates instead of two:
\[ d_{st}=\sqrt{\sum_{j=1}^{6}(z_{sj}-z_{tj})^2} , \]
where \(z_{sj}\) is the standardised value of indicator \(j\) for state \(s\). This distance compares the profiles of two states, how rich, how educated, how safe and how cold they are, and not their locations. Four states show the difference:
round(X6[st_ex, ], 1) # the six indicators, before standardising
## Income Illiteracy LifeExp Murder HSGrad Frost
## Montana 4347 0.6 70.6 5.0 59.2 155
## New Hampshire 4281 0.7 71.2 3.3 57.6 174
## California 5114 1.1 71.7 10.3 62.6 20
## Nevada 5149 0.5 69.0 11.5 65.2 188
round(st_D$Euclidean[st_ex, st_ex], 2) # distances between the standardised profiles
## Montana New Hampshire California Nevada
## Montana 0.00 0.82 3.46 2.66
## New Hampshire 0.82 0.00 3.89 3.27
## California 3.46 3.89 0.00 3.95
## Nevada 2.66 3.27 3.95 0.00Montana and New Hampshire lie 2,971 km apart, yet their profiles are only 0.82 apart: just 1% of all 1,225 pairs of states are more alike. California and Nevada are neighbours, 384 km apart, yet their profiles are 3.95 apart, more than the 3.00 of a typical pair: Nevada has less illiteracy, a lower life expectancy and far more days of frost.
Classical MDS turns such a table into a map of the profiles, on which states with similar profiles end up close, wherever they lie. Here are the maps from three distance tables, all computed from the same six indicators: the Euclidean distance above, the Manhattan distance and the Mahalanobis distance (the second and third maps turned to line up with the first):
fig_states_maps <- function() {
ref <- st_mds$Euclidean$points
if (ref["Alaska", 2] < 0) ref[, 2] <- -ref[, 2]
ttl <- c(Euclidean = "Euclidean", Manhattan = "Manhattan (city block)", Mahalanobis = "Mahalanobis")
sub <- c(Euclidean = "= the PCA scores of Chapter 4", Manhattan = "sum of absolute differences",
Mahalanobis = "relative to the shape of the cloud")
panels <- lapply(names(st_D), function(nm) {
Y <- if (nm == "Euclidean") ref else procrustes_align(st_mds[[nm]]$points, ref)
d <- tibble(x = Y[, 1], y = Y[, 2], lab = state.abb)
ggplot(d, aes(x, y, label = lab)) + axes0 + geom_text(size = 2.6, colour = "#2c3e50") +
coord_equal() + labs(title = ttl[[nm]], subtitle = sub[[nm]], x = "dimension 1", y = "dimension 2") +
theme(plot.title = element_text(size = 13, face = "bold"), plot.subtitle = element_text(size = 10))
})
wrap_plots(panels, nrow = 1)
}
# draw the figure
fig_states_maps()
The Euclidean map is the map of principal component scores of Chapter 4, the points of its biplot. The Manhattan map looks much the same, with the states spread a little differently. The Mahalanobis map is round: measuring distance relative to the shape of the cloud removes the correlations, so every direction carries the same variance.
The eigenvalues of \(\mathbf B\) show the difference. Each state now has six coordinates, one per indicator, so \(\mathbf B\) can have up to six positive eigenvalues (the flat map of the states had two coordinates, and so two). Here are the first seven for each table:
sapply(st_D, function(D) round(mds_eigen(D)[1:7], 1)) # the seven largest eigenvalues of B
## Euclidean Manhattan Mahalanobis
## [1,] 174.2 965.0 49
## [2,] 48.4 193.3 49
## [3,] 38.7 172.9 49
## [4,] 15.7 83.8 49
## [5,] 10.1 50.4 49
## [6,] 6.8 33.6 49
## [7,] 0.0 29.1 0- Euclidean: six positive eigenvalues, then zeros. They are \(n-1=49\) times the variances of the six principal components of Chapter 4, so two dimensions keep 76%, the share of variance of the first two components.
- Manhattan: more than six nonzero eigenvalues, 25 of them negative. Manhattan distances are not Euclidean (Section 5.6.3).
- Mahalanobis: six positive eigenvalues, all equal to 49. The Mahalanobis distance between two states is the Euclidean distance between their standardised scores \(\boldsymbol\varepsilon_t\) of Chapter 4, which have variance one in every direction, and \(n-1\) times a variance of one is 49. So two dimensions keep only two sixths, 33%, and not even PCA’s assumption can say which two directions to show: MDS returns the standardised scores in an arbitrary rotation. The round cloud of shocks in the Introduction had the same problem.
This goes one step beyond PCA of the correlation matrix, which gives the Euclidean map here: standardising gives every variable a variance of one, and the Mahalanobis distance also removes the correlations, which gives every component a variance of one.
5.6.3 Distances that no map reproduces
Euclidean distances always fit some set of points exactly. Many other distances do not: no set of points, in any number of dimensions, has them as straight-line distances. A loop shows why. Take four places evenly spaced around a loop, A, B, C and D. Along the road, neighbours are 1 minute apart and opposite places 2 minutes (top left). Can four points on a map have these as straight-line distances?
fig_loop4 <- function(nrow = 2) {
ttl <- theme(plot.title = element_text(size = 13, face = "bold", hjust = 0.5),
plot.subtitle = element_text(size = 10.5, hjust = 0.5, colour = "grey30", lineheight = 1.05))
ang <- c(A = 180, B = 90, C = 0, D = 270) * pi / 180
mid <- c(135, 45, 315, 225) * pi / 180 # directions of the side midpoints A-B, B-C, C-D, D-A
lim <- coord_equal(xlim = c(-1.45, 1.45), ylim = c(-1.45, 1.45), clip = "off")
corners <- function(P) list(
geom_point(data = P, aes(x, y), size = 3, colour = "#2c3e50"),
geom_text(data = P, aes(x * (1 + 0.28 / sqrt(x^2 + y^2)), y * (1 + 0.28 / sqrt(x^2 + y^2)), label = lab),
size = 5, fontface = "bold", colour = "#2c3e50"))
# 1: the table, distances along the loop
r <- 0.85
P1 <- tibble(lab = names(ang), x = r * cos(ang), y = r * sin(ang))
circ <- tibble(t = seq(0, 2 * pi, length.out = 300), x = r * cos(t), y = r * sin(t))
p1 <- ggplot() + geom_path(data = circ, aes(x, y), colour = "#cccccc", linewidth = 3) + corners(P1) +
annotate("text", x = 1.3 * r * cos(mid), y = 1.3 * r * sin(mid), label = "1 min", size = 3.8, colour = "grey35") +
lim + theme_void() + ttl +
labs(title = "The table", subtitle = "along the loop: neighbours 1 minute apart,\nopposite places 2 minutes")
# 2 and 3: squares, with the distances that are wrong in red
square <- function(a, side, diag, side_ok, title, subtitle) {
P <- tibble(lab = names(ang), x = a * cos(ang), y = a * sin(ang))
col <- function(ok) if (ok) "grey35" else col_a2
ggplot() +
annotate("segment", x = P$x, y = P$y, xend = P$x[c(2, 3, 4, 1)], yend = P$y[c(2, 3, 4, 1)],
colour = col(side_ok), linewidth = 0.9) +
annotate("segment", x = P$x[1:2], y = P$y[1:2], xend = P$x[3:4], yend = P$y[3:4],
colour = col(!side_ok), linewidth = 0.9, linetype = "22") +
annotate("text", x = (a / sqrt(2) + 0.16) * cos(mid), y = (a / sqrt(2) + 0.16) * sin(mid),
label = side, size = 4.2, colour = col(side_ok), fontface = if (side_ok) "plain" else "bold") +
annotate("text", x = c(0.5 * a, 0.09), y = c(0.09, -0.5 * a), label = diag, hjust = c(0.5, 0), vjust = c(0, 0.5),
size = 4.2, colour = col(!side_ok), fontface = if (side_ok) "bold" else "plain") +
corners(P) + lim + theme_void() + ttl + labs(title = title, subtitle = subtitle)
}
p2 <- square(sqrt(0.5), "1", "1.41", TRUE, "A square with sides 1", "sides 1, as in the table,\nbut diagonals of 1.41, not 2")
p3 <- square(1, "1.41", "2", FALSE, "Classical MDS", "diagonals 2, as in the table,\nbut sides of 1.41, not 1")
# 4: why no arrangement in any number of dimensions works
p4 <- ggplot() +
annotate("segment", x = -1, xend = 1, y = 0, yend = 0, colour = "#2c3e50", linewidth = 0.8) +
annotate("point", x = c(-1, 1), y = 0, size = 3, colour = "#2c3e50") +
annotate("point", x = 0, y = 0, size = 3.4, colour = col_a2) +
annotate("text", x = c(-1.12, 1.12), y = 0, label = c("A", "C"), size = 5, fontface = "bold",
colour = "#2c3e50", hjust = c(1, 0)) +
annotate("text", x = 0, y = c(0.2, -0.2), label = c("B", "D"), size = 5, fontface = "bold", colour = col_a2) +
annotate("text", x = c(-0.5, 0.5), y = 0.12, label = "1", size = 4.2, colour = "grey35") +
annotate("text", x = 0, y = -0.85, size = 3.9, colour = "grey20", lineheight = 1.05,
label = "B and D would be the same point,\nyet they are 2 minutes apart.") +
lim + theme_void() + ttl +
labs(title = "Why nothing works", subtitle = "A to B to C takes 1 + 1 = 2, as A to C does.\nSo B sits halfway along the line, and so does D.")
wrap_plots(p1, p2, p3, p4, nrow = nrow)
}
# draw the figure
fig_loop4()
A square is the natural try, but it cannot get all six distances right. With sides of 1, the diagonals are only \(\sqrt2\approx 1.41\), not 2 (top right). Classical MDS returns the square with diagonals of 2, and then the sides are 1.41, not 1 (bottom left). No other arrangement does better, not even in three or more dimensions (bottom right). The trip from A to C through B takes 1 + 1 = 2 minutes, exactly as long as the direct trip. For straight lines, a detour costs nothing only when B lies on the straight line from A to C, halfway along; anywhere else, the direct line is shorter (the triangle inequality). The same holds for D. So B and D would be the same point, the midpoint between A and C, yet the table puts them 2 minutes apart. (The four corners of a city block, one block apart, have the same table of Manhattan distances.)
Classical MDS detects this through the eigenvalues of the matrix \(\mathbf B\). For any coordinates, \(\mathbf B=\mathbf X\mathbf X'\). If \(\mathbf v\) is an eigenvector, \(\mathbf B\mathbf v=\kappa\mathbf v\), then \(\kappa\,\mathbf v'\mathbf v=\mathbf v'\mathbf X\mathbf X'\mathbf v=\lVert\mathbf X'\mathbf v\rVert^2\) is never negative, so a negative eigenvalue of \(\mathbf B\) means that no coordinates reproduce the table. For the four places, the eigenvalues are 2, 2, 0 and \(-1\): the two eigenvalues of 2 give the square of the bottom-left panel, and the \(-1\) is the part of the table that no map reproduces. The test works both ways: if \(\mathbf B\) has no negative eigenvalues, \(\mathbf VK^{1/2}\) reproduces the table exactly, in as many dimensions as there are positive eigenvalues (Schoenberg 1935). When there are negative eigenvalues, classical MDS drops them: a negative eigenvalue has no real square root, so it cannot become a column of \(\mathbf VK^{1/2}\).
The bars show the eigenvalues of \(\mathbf B\) for five tables (relative to the largest; red ones are negative):
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
}
eig_table <- function() {
sets <- list(
"US map, flat (Euclidean)" = us_D,
"US, great circle" = us_G,
"States, Manhattan" = st_D$Manhattan,
"Loop road, no waiting" = D_wait(0),
"Words, average distance" = word_D)
purrr::imap_dfr(sets, function(D, nm) { ev <- mds_eigen(D)
tibble(set = nm, j = seq_along(ev), ev = ev, rel = ev / ev[1]) }) |>
mutate(set = factor(set, levels = names(sets)))
}
fig_eigen_types <- function() {
d <- eig_table()
brk <- function(l) { b <- pretty(c(1, l[2]), n = 4); c(1, b[b > 1 & b <= l[2]]) }
ggplot(d, aes(j, rel, fill = rel < -1e-8)) + geom_col(width = 0.75) + geom_hline(yintercept = 0, colour = "grey40") +
facet_wrap(~ set, nrow = 1, scales = "free_x") +
scale_fill_manual(values = c(`FALSE` = col_a1, `TRUE` = col_a2), labels = c("positive", "negative"), name = NULL) +
scale_x_continuous(breaks = brk) +
labs(x = "eigenvalue number, largest first (all of them)", y = "eigenvalue / largest eigenvalue") +
theme(legend.position = "top", strip.text = element_text(size = 10, face = "bold"))
}
# draw the figure
fig_eigen_types()
- The flat map of the states (Euclidean): two positive eigenvalues, the rest zero.
- Great-circle distances between the same state centres, measured along the curved surface of the Earth: two large eigenvalues, a small third one and negative ones too small to see (more on these below).
- Manhattan distances between the states: 25 small negative eigenvalues.
- Travel times on the loop road without waiting, for the reason shown above: large negative eigenvalues.
- Average distances between the words: 6 small negative eigenvalues.
The great-circle distances deserve a closer look. The state centres now lie on the curved surface of the Earth, and their MDS map needs a third dimension: its eigenvalue is 0.1% of the first. In the figure, each state sits at its first two MDS coordinates, which give the familiar map, and its colour shows the third coordinate: red states lie above the plane of the first two dimensions, blue ones below it. The middle of the country bulges up by up to 63 km, and the edges bend down by up to 120 km, as on a globe:
fig_us_sphere <- function(title = TRUE) {
Y <- us_mds_G$points
Y2 <- procrustes_align(Y[, 1:2], us_X)
d <- tibble(x = Y2[, 1], y = Y2[, 2], z = us_bulge, lab = us48$abb)
ggplot() +
geom_path(data = us_borders, aes(east, north, group = group), colour = "grey85", linewidth = 0.3) +
geom_label(data = d, aes(x, y, label = lab, fill = z), size = 2.5, label.size = 0, colour = "white",
fontface = "bold", label.padding = unit(0.12, "lines")) +
scale_fill_gradient2(low = "#2166ac", mid = "#bbbbbb", high = "#b2182b",
name = "dimension 3 (km)\nred: above the plane\nblue: below it") +
coord_equal(xlim = c(-2900, 2900), ylim = c(-2100, 2100)) +
labs(x = "dimension 1 (km)", y = "dimension 2 (km)",
title = if (title) "Classical MDS of the great-circle distances between the state centres",
subtitle = if (title) "position: dimensions 1 and 2 (the familiar map); colour: dimension 3, the bulge of the Earth") +
theme(plot.title = element_text(size = 13, face = "bold"), plot.subtitle = element_text(size = 10.5))
}
# draw the figure
fig_us_sphere()
Straight through the Earth, the distances between the state centres (the chords) would be exactly Euclidean, the distances between points in three dimensions. Along the surface of the Earth, a sphere with a radius of 6,371 km, an arc of \(d\) km is longer than its chord by about \(d^3/(24\cdot 6371^2)\) km: 82 km for the longest trip, from Maine to California (4,300 km). No map reproduces that excess, and it makes the small negative eigenvalues.
So a map from classical MDS can miss the table for two different reasons. Dropping positive eigenvalues, to draw
fewer dimensions than the table needs, is dimension reduction, as in PCA. Dropping negative eigenvalues is
unavoidable: no number of extra dimensions brings them back. With a few small negative eigenvalues, MDS still gives a
useful map from the positive ones. With many large ones, the straight-line distances of a map are a poor model for
the table, and non-metric MDS (Section 5.8) is often the better choice. In R, cmdscale() keeps only
positive eigenvalues: asked for more dimensions than there are positive eigenvalues, it warns and returns fewer.
(Older versions of R, as in the output printed by Everitt and Hothorn, show NaN for those dimensions instead.)
Check your understanding
- Classical MDS of Mahalanobis distances returns
- the principal component scores
- the standardised scores, a round cloud
- the original variables
- a line
- A negative eigenvalue of \(\mathbf B\) means that
- the distances were computed wrongly
- no set of points has exactly these straight-line distances
- the map must be turned upside down
- one observation is missing
- Great-circle distances need a small third dimension because
- the Earth is curved
- the states are in three time zones
- MDS always returns three dimensions
- the distances are in miles
- Four places evenly spaced on a loop are 1 minute from their neighbours and 2 minutes from the place opposite.
These travel times are the straight-line distances of
- the corners of a square in the plane
- the corners of a regular tetrahedron
- no set of points, in any number of dimensions
- four points on a line
Answers
1 b. 2 b. 3 a. 4 c (in a square the diagonal is \(\sqrt2\), not 2).5.7 How many dimensions, and how good is the map?
5.7.2 The Shepard diagram
A direct check plots each distance on the map against the distance in the table: a Shepard diagram. For a perfect map, all points lie on the diagonal.
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
}
shepard_df <- function(D, Y, nm) {
dm <- as.matrix(dist(Y)); i <- which(upper.tri(D))
tibble(set = nm, obs = D[i], map = dm[i])
}
fig_shepard <- function() {
d <- bind_rows(
shepard_df(us_D, us_mds$points, "US map (2 of 2 dimensions)"),
shepard_df(st_D$Euclidean, st_mds$Euclidean$points, "States, 6 variables (2 dimensions)"),
shepard_df(D_wait(0), cmdscale(as.dist(D_wait(0)), k = 2), "Loop road (2 dimensions)"),
shepard_df(word_D, word_mds$points, "Words (2 dimensions)")) |>
mutate(set = factor(set, levels = unique(set)))
ggplot(d, aes(obs, map)) + geom_abline(slope = 1, intercept = 0, colour = col_a2, linetype = "22") +
geom_point(alpha = 0.35, size = 1.1, colour = "#2c3e50") +
facet_wrap(~ set, nrow = 1, scales = "free") +
labs(x = "distance in the table", y = "distance on the map") +
theme(strip.text = element_text(size = 10, face = "bold"))
}
# draw the figure
fig_shepard()
The flat map of the states is perfect. For the six state indicators, two dimensions shrink the distances, never stretch them: what is dropped is the spread along the other four components (Section 4.7). For the loop road it is the other way round: every distance on the map is longer than in the table. Each squared distance adds up contributions from all dimensions, \(d_{st}^2=\sum_l\kappa_l(v_{sl}-v_{tl})^2\), and the dropped dimensions include the negative eigenvalues, which subtract. The words, whose few negative eigenvalues are small, lie close to the diagonal.
Check your understanding
- For Euclidean distances, the share of the first \(k\) eigenvalues is
- the share of variance kept by \(k\) principal components
- always one
- the stress
- the largest distance
- In a Shepard diagram of a perfect map, the points
- lie on a horizontal line
- lie on the diagonal
- form a ring
- are spread at random
Answers
1 a. 2 b.5.8 When only the order counts: non-metric MDS
Sometimes only the order of the distances can be trusted. A person rating how different two leaders are on a scale from 1 to 9 can say that one pair is more different than another, but a 6 is not necessarily twice a 3. And sometimes no map reproduces the distances themselves, but one reproduces their order.
Non-metric MDS (Shepard 1962, Kruskal 1964) uses only the order. It looks for points whose distances come in the same order as the table, as far as possible. The fit is measured by the stress,
\[ \text{stress}=\sqrt{\frac{\sum_{s<t}\big(d^{\,\text{map}}_{st}-\hat d_{st}\big)^2}{\sum_{s<t}\big(d^{\,\text{map}}_{st}\big)^2}} , \]
where \(d^{\,\text{map}}_{st}\) are the distances on the map and \(\hat d_{st}\) the numbers closest to them that come in the order of the table, fitted to the map distances. Kruskal’s rule of thumb: 20% or more is poor, 10% fair, 5% or less good, 0 perfect.
The loop road shows what this buys. Classical MDS cannot reproduce its travel times without waiting: they have negative eigenvalues (Section 5.6), and the two-dimensional map stretches every distance (Section 5.7). But the order of the travel times is exactly the order of straight-line distances between points on a circle: the longer the trip around the loop, the further apart two points are across the circle, up to half a turn. So non-metric MDS fits the order perfectly, with a stress of zero:
fig_nonmetric <- function() {
Y <- loop_iso$points
d <- tibble(place = places$place, x = Y[, 1], y = Y[, 2])
p1 <- ggplot(d, aes(x, y)) + axes0 + geom_path(data = bind_rows(d, d[1, ]), colour = "#cccccc", linewidth = 2.5) +
geom_point(size = 2.6, colour = "#2c3e50") +
geom_text_repel(aes(label = place), size = 3.8, seed = 3, colour = "#2c3e50") + coord_equal() +
labs(title = "Non-metric MDS of the travel times",
subtitle = sprintf("no waiting; stress %.1f%%; grey line: the road", loop_iso$stress),
x = "dimension 1", y = "dimension 2")
sh <- tibble(x = loop_shep$x, y = loop_shep$y, yf = loop_shep$yf)
p2 <- ggplot(sh, aes(x, y)) + geom_step(aes(y = yf), colour = col_a2, linewidth = 1) +
geom_point(size = 2, colour = "#2c3e50") +
labs(title = "Shepard diagram", subtitle = "red: the best order-preserving fit",
x = "travel time in the table (minutes)", y = "distance on the map")
p1 + p2 + plot_layout(widths = c(1, 1))
}
# draw the figure
fig_nonmetric()
The map is a ring with the places in driving order. In the Shepard diagram every pair of places sits on the red steps: a longer trip always means a longer distance on the map. In R:
library(MASS)
loop_iso <- isoMDS(as.dist(D_wait(0)), k = 2) # non-metric MDS in two dimensions
loop_iso$stress # in percentCheck your understanding
- Non-metric MDS is useful when
- only the order of the distances can be trusted
- the distances are Euclidean
- there are more variables than observations
- the map has to be upside down
- A stress of 4% means that the map
- is a poor fit
- is a good fit
- has four dimensions
- has four negative eigenvalues
Answers
1 a. 2 b.5.9 Summary
- MDS starts from a distance matrix \(\mathbf D\) and finds coordinates whose straight-line distances reproduce it. The travel times of the loop road give a ring, and with a long wait at the construction site a line.
- \(\mathbf D\) determines the points only up to a shift, a rotation and a reflection: the states come back in the right shape, but possibly upside down.
- Classical MDS turns squared distances into inner products by double centring, \(\mathbf B=-\tfrac12\mathbf J\mathbf D^{(2)}\mathbf J\), and takes the coordinates from the eigendecomposition \(\mathbf B=\mathbf VK \mathbf V'\), as \(\mathbf VK^{1/2}\).
- For Euclidean distances it returns the principal component scores. So it goes from distances straight to latent coordinates, without choosing the orientation of a map first. A first step that turns the map into place is needed only when the latent coordinates must know which axis is which variable, as with Cholesky.
- In AI, embeddings are coordinates whose geometry reproduces how words are used: words that appear near each other in text end up close. Before any learning, one-hot encoding turns each token into a unit vector, with all words equally far apart.
- Many distances are not Euclidean (Manhattan, great circle, travel times, distances in a text). The sign is negative eigenvalues of \(\mathbf B\), which no number of extra dimensions removes. The share of the eigenvalues and the Shepard diagram show how good the map is.
- Non-metric MDS uses only the order of the distances and measures the fit by the stress.
5.9.1 Further reading
- Everitt and Hothorn (2011), An Introduction to Applied Multivariate Analysis with R, Chapter 4: classical MDS with the airline distances between ten US cities, the Egyptian skulls and the water voles; non-metric MDS with voting in the House of Representatives and judgements of World War II leaders; and correspondence analysis.
- Borg and Groenen (2005), Modern Multidimensional Scaling: the standard reference.
- Schoenberg (1935) and Young and Householder (1938) on when a table of distances fits a set of points; Gower (1966) on principal coordinates; Kruskal (1964) on non-metric MDS and the stress; Mardia, Kent and Bibby (1979), Multivariate Analysis, Chapter 14, on the fit criteria.
- Mikolov et al. (2013) on word2vec, and Levy and Goldberg (2014), “Neural word embedding as implicit matrix factorization”, on why learned embeddings and factorising a table of word pairs are close relatives.
- Jurafsky and Martin, Speech and Language Processing, the chapter on vector semantics and embeddings.
- 3Blue1Brown, But what is a GPT?, for tokens, embeddings and directions that carry meaning.
