4 Principal Components Analysis
R code for this chapter: pca_figures.R (data and figures) and _common.R (shared helpers). Save both in one folder and run source("pca_figures.R"); every figure is then one function call, as shown under the Code buttons.
Slides for this chapter: pca_slides.html (opens in a new tab; use the arrow keys to move between slides).
The Introduction wrote the data as unit-variance shocks moved by a matrix, \(\mathbf x_t=A\boldsymbol\varepsilon_t\), and showed that many \(A\) fit the same data. This chapter first adds one more step to that story: shocks with units. Splitting \(A\) into a part that scales the shocks and a part that combines them puts the Introduction’s choices of \(A\) (Cholesky, symmetric root, structural, PCA) into one frame (Section 4.1). The rest of the chapter works out one of them, principal components analysis (PCA): how to find the components, whether to start from the covariance or the correlation matrix, how many components to keep, how to read and use them, and what they do and do not tell us.
The examples of the Introduction carry the first sections, with two variables so that every step can be drawn: education and earnings, roommates’ grades, the flights, and above all Coca-Cola and Pepsi sales. The six state indicators of Chapter 2 then show PCA with more variables.
Notation as in the Introduction. Each variable is measured as a deviation from its mean, so the observations \(\mathbf x_t\) (rows of the data matrix \(\mathbf X\), bold because they are vectors) are centred, and the structural form is
\[ \mathbf x_t=A\,\boldsymbol\varepsilon_t , \]
with uncorrelated, unit-variance shocks \(\boldsymbol\varepsilon_t\) and \(AA'=\Sigma\). In the Introduction \(\Sigma\) was known. With data it is not: it is estimated by the sample covariance matrix \(S\) (Chapter 3), so the \(A\) we compute satisfies \(AA'=S\) and is an estimate too, as is everything derived from it below (to keep the formulas light, we drop the hats).
4.1 Factors with units: \(A=\Gamma D\)
4.1.1 Shocks have no units
Start from the familiar equation of the Introduction,
\[ \mathbf x_t=A\,\boldsymbol\varepsilon_t . \]
Each choice of \(A\) there came with a story: the flights (a structural restriction), a regression of earnings on education (Cholesky), roommates’ grades (symmetric root), and Coke and Pepsi (PCA). In every story the shocks \(\boldsymbol\varepsilon_t\) have variance one. A shock of one means “one standard deviation more than usual”, which is a convenient coordinate but not a measurement. A pilot reports headwind in km/h, a registrar reports a GPA, an economist reports years of schooling. To speak about the forces in such units, \(A\) needs one more step.
4.1.2 Scale, then combine
Split \(A\) in two:
\[ \mathbf x_t=A\,\boldsymbol\varepsilon_t=\Gamma\,\underbrace{D\,\boldsymbol\varepsilon_t}_{\mathbf f_t}=\Gamma\,\mathbf f_t, \qquad\text{so}\qquad A=\Gamma D . \]
- \(D\) is diagonal. It scales each unit-variance shock into a factor with its own units. The factors are still uncorrelated, and their variances, the diagonal of \(D^2\), say how important each factor is.
- \(\Gamma\) says how the measured variables respond to one unit of each factor.
The covariance matrix becomes \(S=AA'=\Gamma D^2\Gamma'\): the factor variances \(D^2\), combined by \(\Gamma\).
The split is not unique. Doubling the unit of factor \(j\) (halving \(d_j\)) and doubling column \(j\) of \(\Gamma\) leaves \(A\) unchanged. So, on top of the restriction that picked \(A\), splitting it needs one more assumption per factor, a normalisation that fixes the unit in which the factor is measured. Each story of the Introduction suggests a natural one. In each figure below, the unit-variance shocks (left) are scaled by \(D\) into factors (middle), which \(\Gamma\) combines into the data (right); the arrows show what one standard deviation of each factor does, and one observation (orange) is followed through the layers.
4.1.3 Cholesky: a regression
Take years of education \(x_1\) and annual earnings \(x_2\) (in $1000). The Cholesky restriction of the Introduction is \(a_{12}=0\): education does not respond to the earnings shock. The natural normalisation measures each factor in the units of “its” variable, so \(\Gamma\) has ones on the diagonal:
\[ x_{t1}=f_{t1},\qquad x_{t2}=\beta f_{t1}+f_{t2},\qquad \Gamma=L=\begin{pmatrix}1&0\\ \beta&1\end{pmatrix},\qquad D=\begin{pmatrix}\sigma_1&0\\0&\sigma_u\end{pmatrix}. \]
The shocks are scaled into the explanatory variable and the residual, and \(L\) combines them into the two variables. Factor 1 is education, with standard deviation \(\sigma_1=2.5\) years. \(\beta=4\) is the regression slope, $4000 a year per year of education, and factor 2 is the earnings residual, in $1000, with standard deviation \(\sigma_u=15\). The Cholesky factor of the Introduction is \(LD\), and \(S=LD^2L'\) is known as the LDL\('\) decomposition.
fig_md <- function(X, M, D, f_lab, x_lab, f_sub = NULL, equal = FALSE, obs = NULL) {
A <- M %*% D; X <- scale(X, scale = FALSE); E <- X %*% t(solve(A)); Fm <- E %*% D
if (is.null(obs)) obs <- which.min((E[, 1] - 1.3)^2 + (E[, 2] - 1.4)^2)
col_wk <- "#e6820e"
arrows_of2 <- function(B) geom_segment(data = tibble(xend = B[1, ], yend = B[2, ], col = c(col_a1, col_a2)),
aes(0, 0, xend = xend, yend = yend, colour = I(col)), linewidth = 1.3,
arrow = arrow(length = unit(0.2, "cm"), type = "closed"))
pts <- function(P) list(geom_point(data = tibble(x = P[, 1], y = P[, 2]), aes(x, y), colour = "#6f7a8c",
alpha = 0.35, size = 1.2),
geom_point(aes(x = P[obs, 1], y = P[obs, 2]), colour = col_wk, size = 3))
rng <- function(P) { r <- 1.08 * max(abs(P)); c(-r, r) }
p1 <- ggplot() + axes0 + pts(E) + arrows_of2(diag(2)) + coord_equal(xlim = c(-3.4, 3.4), ylim = c(-3.4, 3.4)) +
labs(title = expression("Shocks "*bold(epsilon)[t]), subtitle = "variance 1, no units",
x = expression(epsilon[1]), y = expression(epsilon[2]))
p2 <- ggplot() + axes0 + pts(Fm) + arrows_of2(D) +
(if (equal) coord_equal(xlim = rng(Fm), ylim = rng(Fm)) else
coord_cartesian(xlim = rng(Fm[, 1]), ylim = rng(Fm[, 2]))) +
labs(title = expression("Factors "*bold(f)[t] == D*bold(epsilon)[t]), subtitle = f_sub, x = f_lab[1], y = f_lab[2])
p3 <- ggplot() + axes0 + pts(X) + arrows_of2(A) +
(if (equal) coord_equal(xlim = rng(X), ylim = rng(X)) else
coord_cartesian(xlim = rng(X[, 1]), ylim = rng(X[, 2]))) +
labs(title = expression("Data "*bold(x)[t] == Gamma*bold(f)[t]*" = "*Gamma*italic(D)*bold(epsilon)[t]*" = "*italic(A)*bold(epsilon)[t]), subtitle = "deviations from the means",
x = x_lab[1], y = x_lab[2])
step <- function(lab) ggplot() +
annotate("segment", x = 0.05, xend = 0.95, y = 0.5, yend = 0.5, linewidth = 1.1,
arrow = arrow(length = unit(0.25, "cm"), type = "closed")) +
annotate("text", x = 0.5, y = 0.62, label = lab, size = 5.5, parse = TRUE) +
coord_cartesian(xlim = c(0, 1), ylim = c(0, 1)) + theme_void()
p1 + step("italic(D)") + p2 + step("Gamma") + p3 + plot_layout(widths = c(1, 0.2, 1, 0.2, 1))
}
fig_md_chol <- function() fig_md(chol_X, chol_M, chol_D,
f_lab = c("education (years)", "earnings residual ($1000)"), x_lab = c("education (years)", "earnings ($1000)"),
f_sub = "the regressor and the residual")
# draw the figure
fig_md_chol()
4.1.4 Symmetric root: roommates
Two first-year students are paired at random, and each one’s GPA is affected by the other. The symmetric root of the Introduction is \(a_{12}=a_{21}\): neither roommate comes first. Normalise again with ones on the diagonal: factor \(j\) is student \(j\)’s own contribution to her GPA, her GPA before the peer effect, in GPA points, and the off-diagonal entries of \(\Gamma\) are the peer effects,
\[ x_{t1}=f_{t1}+\gamma_{12}f_{t2},\qquad x_{t2}=\gamma_{21}f_{t1}+f_{t2}. \]
Here \(d_j=a_{jj}\) and \(\gamma_{ij}=a_{ij}/a_{jj}\). In the example each student’s own contribution has standard deviation 0.5 GPA points, and every point of the roommate’s own contribution adds \(\gamma_{12}=\gamma_{21}=0.2\) points to one’s GPA. With equally variable students, the symmetric \(A\) means equal peer effects in both directions, which is what random pairing suggests.
fig_md <- function(X, M, D, f_lab, x_lab, f_sub = NULL, equal = FALSE, obs = NULL) {
A <- M %*% D; X <- scale(X, scale = FALSE); E <- X %*% t(solve(A)); Fm <- E %*% D
if (is.null(obs)) obs <- which.min((E[, 1] - 1.3)^2 + (E[, 2] - 1.4)^2)
col_wk <- "#e6820e"
arrows_of2 <- function(B) geom_segment(data = tibble(xend = B[1, ], yend = B[2, ], col = c(col_a1, col_a2)),
aes(0, 0, xend = xend, yend = yend, colour = I(col)), linewidth = 1.3,
arrow = arrow(length = unit(0.2, "cm"), type = "closed"))
pts <- function(P) list(geom_point(data = tibble(x = P[, 1], y = P[, 2]), aes(x, y), colour = "#6f7a8c",
alpha = 0.35, size = 1.2),
geom_point(aes(x = P[obs, 1], y = P[obs, 2]), colour = col_wk, size = 3))
rng <- function(P) { r <- 1.08 * max(abs(P)); c(-r, r) }
p1 <- ggplot() + axes0 + pts(E) + arrows_of2(diag(2)) + coord_equal(xlim = c(-3.4, 3.4), ylim = c(-3.4, 3.4)) +
labs(title = expression("Shocks "*bold(epsilon)[t]), subtitle = "variance 1, no units",
x = expression(epsilon[1]), y = expression(epsilon[2]))
p2 <- ggplot() + axes0 + pts(Fm) + arrows_of2(D) +
(if (equal) coord_equal(xlim = rng(Fm), ylim = rng(Fm)) else
coord_cartesian(xlim = rng(Fm[, 1]), ylim = rng(Fm[, 2]))) +
labs(title = expression("Factors "*bold(f)[t] == D*bold(epsilon)[t]), subtitle = f_sub, x = f_lab[1], y = f_lab[2])
p3 <- ggplot() + axes0 + pts(X) + arrows_of2(A) +
(if (equal) coord_equal(xlim = rng(X), ylim = rng(X)) else
coord_cartesian(xlim = rng(X[, 1]), ylim = rng(X[, 2]))) +
labs(title = expression("Data "*bold(x)[t] == Gamma*bold(f)[t]*" = "*Gamma*italic(D)*bold(epsilon)[t]*" = "*italic(A)*bold(epsilon)[t]), subtitle = "deviations from the means",
x = x_lab[1], y = x_lab[2])
step <- function(lab) ggplot() +
annotate("segment", x = 0.05, xend = 0.95, y = 0.5, yend = 0.5, linewidth = 1.1,
arrow = arrow(length = unit(0.25, "cm"), type = "closed")) +
annotate("text", x = 0.5, y = 0.62, label = lab, size = 5.5, parse = TRUE) +
coord_cartesian(xlim = c(0, 1), ylim = c(0, 1)) + theme_void()
p1 + step("italic(D)") + p2 + step("Gamma") + p3 + plot_layout(widths = c(1, 0.2, 1, 0.2, 1))
}
fig_md_room <- function() fig_md(room_X, room_M, room_D,
f_lab = c("student 1's own GPA", "student 2's own GPA"), x_lab = c("GPA of student 1", "GPA of student 2"),
f_sub = "GPA before the peer effect", equal = TRUE)
# draw the figure
fig_md_room()
4.1.5 Structural: the flights
The flights need outside information twice. First, to identify \(A\): the aircraft manual says that an extra minute at cruise burns 100 kg of fuel, which fixes the direction of the headwind column (Section 1.4). Second, to normalise the factors, one more fact for each:
- Headwind in km/h. On this 640 km route at a cruise speed of 800 km/h, the flight takes \(640/(800-w)\) hours against a headwind of \(w\) km/h, so each extra km/h adds about \(640/800^2\) hours, or \(\gamma_{11}=0.06\) minutes.
- Load in tonnes. The climb tables say that each extra tonne adds \(\gamma_{12}=0.1\) minutes.
With these two numbers the rest follows from \(A\): the factor standard deviations are \(d_1=a_{11}/\gamma_{11}=20\) km/h and \(d_2=a_{12}/\gamma_{12}=2\) tonnes, and the fuel row of \(\Gamma\) is \(\gamma_{21}=a_{21}/d_1\), 6 kg per km/h of headwind, and \(\gamma_{22}=a_{22}/d_2\), 65 kg per tonne:
\[ \underset{A}{\begin{pmatrix}1.20&0.20\\ 1.20&1.30\end{pmatrix}} =\underset{\Gamma}{\begin{pmatrix}0.06&0.1\\ 0.06&0.65\end{pmatrix}} \underset{D}{\begin{pmatrix}20&0\\ 0&2\end{pmatrix}}. \]
fig_md <- function(X, M, D, f_lab, x_lab, f_sub = NULL, equal = FALSE, obs = NULL) {
A <- M %*% D; X <- scale(X, scale = FALSE); E <- X %*% t(solve(A)); Fm <- E %*% D
if (is.null(obs)) obs <- which.min((E[, 1] - 1.3)^2 + (E[, 2] - 1.4)^2)
col_wk <- "#e6820e"
arrows_of2 <- function(B) geom_segment(data = tibble(xend = B[1, ], yend = B[2, ], col = c(col_a1, col_a2)),
aes(0, 0, xend = xend, yend = yend, colour = I(col)), linewidth = 1.3,
arrow = arrow(length = unit(0.2, "cm"), type = "closed"))
pts <- function(P) list(geom_point(data = tibble(x = P[, 1], y = P[, 2]), aes(x, y), colour = "#6f7a8c",
alpha = 0.35, size = 1.2),
geom_point(aes(x = P[obs, 1], y = P[obs, 2]), colour = col_wk, size = 3))
rng <- function(P) { r <- 1.08 * max(abs(P)); c(-r, r) }
p1 <- ggplot() + axes0 + pts(E) + arrows_of2(diag(2)) + coord_equal(xlim = c(-3.4, 3.4), ylim = c(-3.4, 3.4)) +
labs(title = expression("Shocks "*bold(epsilon)[t]), subtitle = "variance 1, no units",
x = expression(epsilon[1]), y = expression(epsilon[2]))
p2 <- ggplot() + axes0 + pts(Fm) + arrows_of2(D) +
(if (equal) coord_equal(xlim = rng(Fm), ylim = rng(Fm)) else
coord_cartesian(xlim = rng(Fm[, 1]), ylim = rng(Fm[, 2]))) +
labs(title = expression("Factors "*bold(f)[t] == D*bold(epsilon)[t]), subtitle = f_sub, x = f_lab[1], y = f_lab[2])
p3 <- ggplot() + axes0 + pts(X) + arrows_of2(A) +
(if (equal) coord_equal(xlim = rng(X), ylim = rng(X)) else
coord_cartesian(xlim = rng(X[, 1]), ylim = rng(X[, 2]))) +
labs(title = expression("Data "*bold(x)[t] == Gamma*bold(f)[t]*" = "*Gamma*italic(D)*bold(epsilon)[t]*" = "*italic(A)*bold(epsilon)[t]), subtitle = "deviations from the means",
x = x_lab[1], y = x_lab[2])
step <- function(lab) ggplot() +
annotate("segment", x = 0.05, xend = 0.95, y = 0.5, yend = 0.5, linewidth = 1.1,
arrow = arrow(length = unit(0.25, "cm"), type = "closed")) +
annotate("text", x = 0.5, y = 0.62, label = lab, size = 5.5, parse = TRUE) +
coord_cartesian(xlim = c(0, 1), ylim = c(0, 1)) + theme_void()
p1 + step("italic(D)") + p2 + step("Gamma") + p3 + plot_layout(widths = c(1, 0.2, 1, 0.2, 1))
}
fig_md_air <- function() fig_md(air_X, air_M, air_D,
f_lab = c("headwind (km/h)", "load (tonnes)"), x_lab = c("flight time (min)", "fuel (100 kg)"),
f_sub = "physical units")
# draw the figure
fig_md_air()
4.1.6 PCA: Coke and Pepsi
PCA’s restriction is that the first column of \(A\) is as long as possible (Section 4.2 works it out). Its normalisation gives every column of \(\Gamma\) length one, \(\lVert\gamma_j\rVert=1\). Two things make this a clever choice:
- One unit of a factor moves the observation by a distance of one, in the units of the data. A factor is a length along its direction, measured like the data themselves.
- The variances add up. The total variance of the data (the sum of the variances, the trace of \(S\)) splits into the factor variances, \[ \operatorname{tr}(S)=\operatorname{tr}(\Gamma D^2\Gamma')=\sum_j d_j^2\,\lVert\gamma_j\rVert^2=\sum_j d_j^2 , \] so \(d_j^2\) is exactly the part of the total variance that factor \(j\) carries: nothing is gained or lost in the translation from factors to data.
Both only make sense when the variables share their units, a point Section 4.5 returns to. The PCA factors are called the principal component scores. Because they share the units of the data, the middle panel can be drawn to scale: the round cloud of shocks is stretched into an ellipse lined up with the axes, and \(\Gamma\) only turns it into place (Section 4.2). Read backwards, from the data to the shocks, the middle panel becomes the biplot of Section 4.2.
fig_md <- function(X, M, D, f_lab, x_lab, f_sub = NULL, equal = FALSE, obs = NULL) {
A <- M %*% D; X <- scale(X, scale = FALSE); E <- X %*% t(solve(A)); Fm <- E %*% D
if (is.null(obs)) obs <- which.min((E[, 1] - 1.3)^2 + (E[, 2] - 1.4)^2)
col_wk <- "#e6820e"
arrows_of2 <- function(B) geom_segment(data = tibble(xend = B[1, ], yend = B[2, ], col = c(col_a1, col_a2)),
aes(0, 0, xend = xend, yend = yend, colour = I(col)), linewidth = 1.3,
arrow = arrow(length = unit(0.2, "cm"), type = "closed"))
pts <- function(P) list(geom_point(data = tibble(x = P[, 1], y = P[, 2]), aes(x, y), colour = "#6f7a8c",
alpha = 0.35, size = 1.2),
geom_point(aes(x = P[obs, 1], y = P[obs, 2]), colour = col_wk, size = 3))
rng <- function(P) { r <- 1.08 * max(abs(P)); c(-r, r) }
p1 <- ggplot() + axes0 + pts(E) + arrows_of2(diag(2)) + coord_equal(xlim = c(-3.4, 3.4), ylim = c(-3.4, 3.4)) +
labs(title = expression("Shocks "*bold(epsilon)[t]), subtitle = "variance 1, no units",
x = expression(epsilon[1]), y = expression(epsilon[2]))
p2 <- ggplot() + axes0 + pts(Fm) + arrows_of2(D) +
(if (equal) coord_equal(xlim = rng(Fm), ylim = rng(Fm)) else
coord_cartesian(xlim = rng(Fm[, 1]), ylim = rng(Fm[, 2]))) +
labs(title = expression("Factors "*bold(f)[t] == D*bold(epsilon)[t]), subtitle = f_sub, x = f_lab[1], y = f_lab[2])
p3 <- ggplot() + axes0 + pts(X) + arrows_of2(A) +
(if (equal) coord_equal(xlim = rng(X), ylim = rng(X)) else
coord_cartesian(xlim = rng(X[, 1]), ylim = rng(X[, 2]))) +
labs(title = expression("Data "*bold(x)[t] == Gamma*bold(f)[t]*" = "*Gamma*italic(D)*bold(epsilon)[t]*" = "*italic(A)*bold(epsilon)[t]), subtitle = "deviations from the means",
x = x_lab[1], y = x_lab[2])
step <- function(lab) ggplot() +
annotate("segment", x = 0.05, xend = 0.95, y = 0.5, yend = 0.5, linewidth = 1.1,
arrow = arrow(length = unit(0.25, "cm"), type = "closed")) +
annotate("text", x = 0.5, y = 0.62, label = lab, size = 5.5, parse = TRUE) +
coord_cartesian(xlim = c(0, 1), ylim = c(0, 1)) + theme_void()
p1 + step("italic(D)") + p2 + step("Gamma") + p3 + plot_layout(widths = c(1, 0.2, 1, 0.2, 1))
}
fig_md_cola <- function() {
G <- cola_eig$vectors; if (G[1, 1] < 0) G[, 1] <- -G[, 1]; if (det(G) < 0) G[, 2] <- -G[, 2]
fig_md(cola, G, diag(sqrt(cola_eig$values)), f_lab = c("score 1 (market)", "score 2 (brand switching)"),
x_lab = c("Coca-Cola sales", "Pepsi sales"), f_sub = "lengths in the units of the data", equal = TRUE)
}
# draw the figure
fig_md_cola()
4.1.7 Four normalisations
| restriction on \(A\) | normalisation of \(\Gamma\) | factors \(\mathbf f_t\) | |
|---|---|---|---|
| Cholesky | \(a_{12}=0\) | ones on the diagonal | the regressor and the residual |
| Symmetric root | \(a_{12}=a_{21}\) | ones on the diagonal | each roommate’s own GPA |
| Structural | the manual’s fuel flow | one outside fact per factor | headwind (km/h), load (t) |
| PCA | first column longest | columns of length one | scores, in the units of the data |
\(A=\Gamma D\): the diagonal \(D\) says how important each factor is, and \(\Gamma\) how the measured variables combine the factors. Choosing \(A\) needs a restriction; splitting it into \(\Gamma\) and \(D\) needs a normalisation.
PCA needs no outside information, neither an ordering of the variables nor a manual, which is one reason it is the most widely used. The rest of the chapter studies it.
Check your understanding
- In \(\mathbf x_t=\Gamma D\boldsymbol\varepsilon_t\), the diagonal matrix \(D\)
- rotates the shocks
- scales each unit-variance shock into a factor in its own units
- holds the correlations of the variables
- is always the identity
- Measuring headwind in m/s instead of km/h changes
- the data
- \(A\)
- the split of \(A\) into \(\Gamma\) and \(D\), but not \(A\)
- nothing at all
- In the Cholesky split with ones on the diagonal of \(\Gamma\), the second factor is
- the second variable itself
- the part of the second variable not explained by the first, the regression residual
- the first principal component
- the peer effect
- With columns of \(\Gamma\) of length one, the factor variances \(d_j^2\)
- are all one
- add up to the total variance of the data
- are the correlations
- depend on the order of the variables
Answers
1 b. 2 c. 3 b. 4 b.4.2 Two arrows, the first as long as possible
Which \(A\) does PCA pick? With Coke and Pepsi, the slider of the Introduction finds it.
4.2.1 Every rotation fits the data
Each week’s Coke and Pepsi sales (as deviations from the mean) are a combination of two uncorrelated shocks with variance one,
\[ \mathbf x_t=A\,\boldsymbol\varepsilon_t=\varepsilon_{t1}\,a_1+\varepsilon_{t2}\,a_2 , \]
where \(a_1\) and \(a_2\), the columns of \(A\), are the two arrows: what one standard deviation of each shock does to the two sales figures. Any \(A\) with \(AA'=S\) fits the data equally well (Section 1.3): turning both arrows together by an angle \(\varphi\) keeps their tips on the one-standard-deviation ellipse and leaves \(S\) unchanged. Algebraically, \(A(\varphi)=S^{1/2}Q(\varphi)\), with \(S^{1/2}\) the symmetric root and \(Q(\varphi)\) the rotation matrix of Section 3.7.
4.2.2 How much variance each arrow carries
One number summarises how much the data vary in all directions together: the total variance, the sum of the variances of the variables. It is the sum of the diagonal entries of \(S\), called the trace:
\[ \operatorname{tr}(S)=\operatorname{tr}\begin{pmatrix}s_1^2&s_{12}\\ s_{12}&s_2^2\end{pmatrix}=s_1^2+s_2^2 . \]
The covariance \(s_{12}\) is off the diagonal and does not enter. Now write each variance in terms of the arrows. Variable 1 is \(x_{t1}=a_{11}\varepsilon_{t1}+a_{12}\varepsilon_{t2}\), and the shocks are uncorrelated with variance one, so by the rule for linear combinations (Section 3.5.4)
\[ s_1^2=a_{11}^2\operatorname{var}(\varepsilon_{t1})+a_{12}^2\operatorname{var}(\varepsilon_{t2})+2a_{11}a_{12}\operatorname{cov}(\varepsilon_{t1},\varepsilon_{t2}) =a_{11}^2+a_{12}^2 , \]
and in the same way \(s_2^2=a_{21}^2+a_{22}^2\). Adding the two and regrouping the four squares by shock instead of by variable,
\[ \operatorname{tr}(S)=\underbrace{(a_{11}^2+a_{12}^2)}_{s_1^2}+\underbrace{(a_{21}^2+a_{22}^2)}_{s_2^2} =\underbrace{(a_{11}^2+a_{21}^2)}_{\lVert a_1\rVert^2}+\underbrace{(a_{12}^2+a_{22}^2)}_{\lVert a_2\rVert^2} . \]
The first grouping splits the total variance by variable, the second by shock: \(a_{11}^2+a_{21}^2\) collects what the first shock adds to the variance of each variable, and it is the squared length of the first column of \(A\), the first arrow.
The squared length of an arrow is the part of the total variance that its shock carries. The total is fixed by the data; the rotation only decides how it is divided. Turn the arrows with the slider:
fig_pca_arrows <- function() {
S <- cov(cola); X <- scale(cola, scale = FALSE); root <- sym_root(S)
phi_lab <- function(phi) sprintf("%.1f", phi)
phi_grid <- sort(unique(c(seq(-90, 90, by = 2.5), pca_phi)))
fk <- function(phi) factor(phi_lab(phi), levels = phi_lab(phi_grid))
A_of <- function(phi) root %*% rotation_matrix(phi * pi / 180)
len2 <- function(phi) colSums(A_of(phi)^2)
cols <- c(col_a1, col_a2)
arrows <- lapply(1:2, function(j) purrr::map_dfr(phi_grid, function(ph)
arrow_geometry(A_of(ph)[, j], head_length = 0.2, head_width = 0.1, shaft_width = 0.022)$arrow |> mutate(k = fk(ph))))
labs_df <- purrr::map_dfr(phi_grid, function(ph) { M <- A_of(ph); r <- sqrt(colSums(M^2))
tibble(x = M[1, ] * (1 + 0.35 / r), y = M[2, ] * (1 + 0.35 / r), label = c("a<sub>1</sub>", "a<sub>2</sub>"),
col = cols, k = fk(ph)) })
ell <- ellipse_xy(root, 1)
curve <- tibble(phi = seq(-90, 90, by = 0.5)) |>
mutate(l1 = purrr::map_dbl(phi, ~ len2(.x)[1]), l2 = purrr::map_dbl(phi, ~ len2(.x)[2]))
marks <- purrr::map_dfr(phi_grid, function(ph) { l <- len2(ph)
tibble(phi = ph, l = l, col = cols, k = fk(ph)) })
tot <- sum(diag(S))
readout <- purrr::map_dfr(phi_grid, function(ph) { l <- len2(ph)
tibble(x = 0, y = tot * 1.2, k = fk(ph),
t = sprintf("‖a<sub>1</sub>‖² = %.2f (%.0f%%) ‖a<sub>2</sub>‖² = %.2f (%.0f%%) total = %.2f",
l[1], 100 * l[1] / tot, l[2], 100 * l[2] / tot, tot)) })
p1 <- plot_ly() |>
add_trace(x = X[, 1], y = X[, 2], type = "scatter", mode = "markers",
marker = list(size = 5, color = "#6f7a8c", opacity = 0.4), hoverinfo = "skip", showlegend = FALSE) |>
add_trace(x = ell[1, ], y = ell[2, ], type = "scatter", mode = "lines", line = list(color = "black", width = 2),
hoverinfo = "skip", showlegend = FALSE)
for (j in 1:2) p1 <- add_arrow_trace(p1, arrows[[j]], color = cols[j])
p1 <- p1 |> add_trace(data = labs_df, x = ~x, y = ~y, frame = ~k, text = ~label, type = "scatter", mode = "text",
textfont = list(size = 16, color = ~col), hoverinfo = "skip", showlegend = FALSE, inherit = FALSE)
p2 <- plot_ly() |>
add_trace(x = c(-90, 90), y = c(tot, tot), type = "scatter", mode = "lines",
line = list(color = "grey", dash = "dot"), hoverinfo = "skip", showlegend = FALSE) |>
add_trace(x = -88, y = tot * 1.07, text = "total variance tr(S)", type = "scatter", mode = "text",
textposition = "middle right", textfont = list(size = 11, color = "grey"), hoverinfo = "skip",
showlegend = FALSE) |>
add_trace(data = curve, x = ~phi, y = ~l1, type = "scatter", mode = "lines", line = list(color = col_a1, width = 2.5),
hoverinfo = "skip", showlegend = FALSE) |>
add_trace(data = curve, x = ~phi, y = ~l2, type = "scatter", mode = "lines", line = list(color = col_a2, width = 2.5),
hoverinfo = "skip", showlegend = FALSE) |>
add_trace(data = marks, x = ~phi, y = ~l, frame = ~k, type = "scatter", mode = "markers",
marker = list(size = 12, color = ~col), hoverinfo = "skip", showlegend = FALSE, inherit = FALSE) |>
add_trace(data = readout, x = ~x, y = ~y, frame = ~k, text = ~t, type = "scatter", mode = "text",
textfont = list(size = 12, color = "#2c3e50"), hoverinfo = "skip", showlegend = FALSE, inherit = FALSE)
jump <- list(
list(label = "PCA: first arrow longest", method = "animate",
args = list(list(phi_lab(pca_phi)), list(mode = "immediate", frame = list(duration = 0, redraw = TRUE),
transition = list(duration = 0)))),
list(label = "Symmetric root", method = "animate",
args = list(list(phi_lab(0)), list(mode = "immediate", frame = list(duration = 0, redraw = TRUE),
transition = list(duration = 0)))))
subplot(p1, p2, widths = c(0.5, 0.5), margin = 0.07, titleX = TRUE, titleY = TRUE) |>
layout(xaxis = list(title = "Coca-Cola sales (deviation)", range = c(-3.2, 3.2), zeroline = FALSE),
yaxis = list(title = "Pepsi sales (deviation)", range = c(-3.2, 3.2), scaleanchor = "x", zeroline = FALSE),
xaxis2 = list(title = "rotation φ (degrees)", range = c(-90, 90), dtick = 45, zeroline = FALSE),
yaxis2 = list(title = "variance carried by each arrow", range = c(0, tot * 1.3)),
margin = list(t = 70, b = 150)) |>
animation_opts(frame = 80, transition = 0, redraw = TRUE) |>
animation_slider(currentvalue = list(prefix = "rotation φ = ", suffix = "°")) |>
animation_button(x = 0, xanchor = "left", y = -0.3, yanchor = "top", label = "Play") |>
finalize_animation(jump, start_frame = "0.0", prefix = "rotation φ = ", suffix = "°")
}
# draw the figure
fig_pca_arrows()At \(\varphi=0\), the symmetric root, the two arrows carry nearly equal shares: a symmetric \(A\) has \(A'A=AA'=S\), so the squared arrow lengths equal the two variances, 1 and 1.1, or 48% and 52% of the total. As they turn, the blue arrow grows and the red one shrinks, until at \(\varphi\approx46\) degrees the blue arrow is as long as it can be:
Principal components analysis chooses the rotation at which the first arrow is longest, so that the first shock carries as much of the total variance as possible.
At that angle, \(\lVert a_1\rVert^2=2.00\), or 95% of the total, and \(\lVert a_2\rVert^2=0.10\). The two arrows are perpendicular and point along the axes of the ellipse: the long axis is the market (both brands up together), the short axis brand switching. These two directions are the principal components. With \(p\) variables there are \(p\) arrows, and the same idea continues: the first arrow as long as possible, then the second as long as possible given the first, and so on.
4.2.3 Scores: taking \(A\) apart one layer at a time
Split the PCA choice of \(A\) as in Section 4.1,
\[ A=\Gamma D=\begin{pmatrix}\gamma_1&\gamma_2\end{pmatrix}\begin{pmatrix}d_1&0\\0&d_2\end{pmatrix} =\begin{pmatrix}d_1\gamma_1&d_2\gamma_2\end{pmatrix}, \]
with the columns of \(\Gamma\) of length one. Column by column, each arrow is a length times a unit-length direction:
\[ a_j=d_j\,\gamma_j,\qquad d_j=\lVert a_j\rVert,\qquad \gamma_j=a_j/\lVert a_j\rVert , \]
and the factor variance \(d_j^2\) is the variance arrow \(j\) carries. Because the arrows are perpendicular, the columns of \(\Gamma\) are perpendicular unit vectors, \(\Gamma'\Gamma=I\): \(\Gamma\) is a rotation (possibly with a reflection), which turns space without stretching or squishing anything. Reading \(\mathbf x_t=\Gamma D\boldsymbol\varepsilon_t\) from right to left, one transformation after the other (3Blue1Brown, chapter 4): \(D\) stretches the round cloud of shocks along the axes (a diagonal matrix just scales each basis vector), and \(\Gamma\) turns the stretched cloud into place. The covariance matrix is \(S=AA'=\Gamma D^2\Gamma'\). The figure follows one week (orange) through the two steps; the arrows follow the two shocks, and the dashed lines show the week’s coordinates.
pca_step <- function(lab, col = "black") ggplot() +
annotate("segment", x = 0.05, xend = 0.95, y = 0.5, yend = 0.5, linewidth = 1.1, colour = col,
arrow = arrow(length = unit(0.25, "cm"), type = "closed")) +
annotate("text", x = 0.5, y = 0.63, label = lab, parse = TRUE, size = 5.5, colour = col) +
coord_cartesian(xlim = c(0, 1), ylim = c(0, 1)) + theme_void()
shock_arrows <- function(B) tibble(x = B[1, ], y = B[2, ], col = c(col_a1, col_a2), lab = NA_character_, lx = 0, ly = 0)
cloud_pts <- function(X, alpha = 0.45) geom_point(data = tibble(x = X[, 1], y = X[, 2]), aes(x, y),
colour = "#6f7a8c", alpha = alpha, size = 1.5)
pca_panel <- function(P, Mell, Dcoord, week, title, sub, xl, yl, pc_lines = NULL, arrows_df = NULL, lim = c(-3.4, 3.4)) {
col_wk <- "#e6820e"; pt <- P[week, ]
el <- ellipse_xy(Mell, 1)
c1 <- sum(pt * Dcoord[, 1]) * Dcoord[, 1]; c2 <- sum(pt * Dcoord[, 2]) * Dcoord[, 2]
g <- ggplot() + axes0
if (!is.null(pc_lines)) g <- g + geom_abline(slope = pc_lines[2, ] / pc_lines[1, ], intercept = 0,
colour = c(col_a1, col_a2), alpha = 0.3)
g <- g + cloud_pts(P, 0.35) + geom_path(data = tibble(x = el[1, ], y = el[2, ]), aes(x, y), linewidth = 0.8)
if (!is.null(arrows_df)) g <- g +
geom_segment(data = arrows_df, aes(0, 0, xend = x, yend = y, colour = I(col)), linewidth = 1.3,
arrow = arrow(length = unit(0.2, "cm"), type = "closed")) +
geom_label(data = filter(arrows_df, !is.na(lab)), aes(x * 1.18 + lx, y * 1.18 + ly, label = lab, colour = I(col)),
size = 3.4, fontface = "bold", label.size = 0, fill = alpha("white", 0.8))
g + geom_segment(aes(x = pt[1], y = pt[2], xend = c1[1], yend = c1[2]), linetype = "22", colour = col_wk) +
geom_segment(aes(x = pt[1], y = pt[2], xend = c2[1], yend = c2[2]), linetype = "22", colour = col_wk) +
geom_point(aes(x = pt[1], y = pt[2]), colour = col_wk, size = 3.2) +
coord_equal(xlim = lim, ylim = lim) + labs(title = title, subtitle = sub, x = xl, y = yl)
}
pca_layers <- function() {
X <- scale(cola, scale = FALSE); e <- eigen(cov(X), symmetric = TRUE)
G <- e$vectors; if (G[1, 1] < 0) G[, 1] <- -G[, 1]; if (det(G) < 0) G[, 2] <- -G[, 2]
D <- diag(sqrt(e$values)); Fs <- X %*% G; E <- sweep(Fs, 2, sqrt(e$values), "/")
list(X = X, G = G, D = D, Fs = Fs, E = E, week = which.min((E[, 1] - 1.3)^2 + (E[, 2] - 1.6)^2))
}
fig_pca_forward <- function() {
L <- pca_layers()
p1 <- pca_panel(L$E, diag(2), diag(2), L$week, expression("Shocks "*bold(epsilon)[t]), "variance 1: round",
expression(epsilon[1]*" (market)"), expression(epsilon[2]*" (brand switching)"),
arrows_df = shock_arrows(diag(2)))
p2 <- pca_panel(L$Fs, L$D, diag(2), L$week, expression("Scores "*bold(f)[t] == italic(D)*bold(epsilon)[t]),
"stretched along the axes", expression(italic(f)[1]), expression(italic(f)[2]),
arrows_df = shock_arrows(L$D))
p3 <- pca_panel(L$X, L$G %*% L$D, diag(2), L$week, expression("Data "*bold(x)[t] == Gamma*bold(f)[t]*" = "*Gamma*italic(D)*bold(epsilon)[t]*" = "*italic(A)*bold(epsilon)[t]),
"rotated into place", "Coca-Cola (deviation)", "Pepsi (deviation)",
arrows_df = shock_arrows(L$G %*% L$D))
p1 + pca_step("italic(D)") + p2 + pca_step("Gamma") + p3 + plot_layout(widths = c(1, 0.2, 1, 0.2, 1))
}
# draw the figure
fig_pca_forward()
The scores go back from the data to the shocks. Undoing a product of transformations means undoing the last one first, so
\[ A^{-1}=\big(\Gamma D\big)^{-1}=D^{-1}\,\Gamma' , \]
where a rotation is undone by its transpose. Indeed, \(\Gamma'\Gamma=I\) says that applying \(\Gamma\) and then \(\Gamma'\) changes nothing, so \(\Gamma'\) is the inverse of \(\Gamma\), \(\Gamma^{-1}=\Gamma'\) (for a square matrix, a matrix that undoes it from one side also undoes it from the other, so \(\Gamma\Gamma'=I\) as well). The two layers come off one at a time:
- Undo the rotation. Turning the data back gives the factors, the principal component scores, \[ \mathbf f_t=\Gamma'\mathbf x_t,\qquad f_{tj}=\gamma_j'\mathbf x_t . \] Each score is an inner product with a unit vector, so it is the signed length of the projection of the week onto the direction of arrow \(j\) (3Blue1Brown, chapter 9). Put differently, \(\Gamma'\) is a change of basis (3Blue1Brown, chapter 13): \(\mathbf f_t\) describes the same week in coordinates whose axes are the arrows. The stretch is still in: the scores on component \(j\) have variance \(d_j^2\).
- Undo the stretch. Dividing each score by its standard deviation gives the shocks back, \[ \boldsymbol\varepsilon_t=D^{-1}\mathbf f_t,\qquad \varepsilon_{tj}=f_{tj}/d_j, \] the standardised scores, with variance one.
The second figure runs the same week backwards, from the data to the shocks. This time the purple arrows follow the two variables: in the data panel they are the axes, one unit of Coca-Cola and one unit of Pepsi. The dashed lines in the data panel run perpendicular to the two components: the scores are projections.
pca_step <- function(lab, col = "black") ggplot() +
annotate("segment", x = 0.05, xend = 0.95, y = 0.5, yend = 0.5, linewidth = 1.1, colour = col,
arrow = arrow(length = unit(0.25, "cm"), type = "closed")) +
annotate("text", x = 0.5, y = 0.63, label = lab, parse = TRUE, size = 5.5, colour = col) +
coord_cartesian(xlim = c(0, 1), ylim = c(0, 1)) + theme_void()
cloud_pts <- function(X, alpha = 0.45) geom_point(data = tibble(x = X[, 1], y = X[, 2]), aes(x, y),
colour = "#6f7a8c", alpha = alpha, size = 1.5)
pca_panel <- function(P, Mell, Dcoord, week, title, sub, xl, yl, pc_lines = NULL, arrows_df = NULL, lim = c(-3.4, 3.4)) {
col_wk <- "#e6820e"; pt <- P[week, ]
el <- ellipse_xy(Mell, 1)
c1 <- sum(pt * Dcoord[, 1]) * Dcoord[, 1]; c2 <- sum(pt * Dcoord[, 2]) * Dcoord[, 2]
g <- ggplot() + axes0
if (!is.null(pc_lines)) g <- g + geom_abline(slope = pc_lines[2, ] / pc_lines[1, ], intercept = 0,
colour = c(col_a1, col_a2), alpha = 0.3)
g <- g + cloud_pts(P, 0.35) + geom_path(data = tibble(x = el[1, ], y = el[2, ]), aes(x, y), linewidth = 0.8)
if (!is.null(arrows_df)) g <- g +
geom_segment(data = arrows_df, aes(0, 0, xend = x, yend = y, colour = I(col)), linewidth = 1.3,
arrow = arrow(length = unit(0.2, "cm"), type = "closed")) +
geom_label(data = filter(arrows_df, !is.na(lab)), aes(x * 1.18 + lx, y * 1.18 + ly, label = lab, colour = I(col)),
size = 3.4, fontface = "bold", label.size = 0, fill = alpha("white", 0.8))
g + geom_segment(aes(x = pt[1], y = pt[2], xend = c1[1], yend = c1[2]), linetype = "22", colour = col_wk) +
geom_segment(aes(x = pt[1], y = pt[2], xend = c2[1], yend = c2[2]), linetype = "22", colour = col_wk) +
geom_point(aes(x = pt[1], y = pt[2]), colour = col_wk, size = 3.2) +
coord_equal(xlim = lim, ylim = lim) + labs(title = title, subtitle = sub, x = xl, y = yl)
}
pca_layers <- function() {
X <- scale(cola, scale = FALSE); e <- eigen(cov(X), symmetric = TRUE)
G <- e$vectors; if (G[1, 1] < 0) G[, 1] <- -G[, 1]; if (det(G) < 0) G[, 2] <- -G[, 2]
D <- diag(sqrt(e$values)); Fs <- X %*% G; E <- sweep(Fs, 2, sqrt(e$values), "/")
list(X = X, G = G, D = D, Fs = Fs, E = E, week = which.min((E[, 1] - 1.3)^2 + (E[, 2] - 1.6)^2))
}
fig_pca_inverse <- function() {
L <- pca_layers(); col_v <- "#7b4fb5"
var_arrows <- function(B) tibble(x = B[1, ], y = B[2, ], col = col_v, lab = c("Coca-Cola", "Pepsi"),
lx = c(0.35, -0.2), ly = c(-0.25, 0.3))
p1 <- pca_panel(L$X, L$G %*% L$D, L$G, L$week, expression("Data "*bold(x)[t]), "axes = the two variables",
"Coca-Cola (deviation)", "Pepsi (deviation)", pc_lines = L$G, arrows_df = var_arrows(diag(2)))
p2 <- pca_panel(L$Fs, L$D, diag(2), L$week, expression("Scores "*bold(f)[t] == Gamma*minute*bold(x)[t]),
"rotated back: the biplot", expression(italic(f)[1]), expression(italic(f)[2]),
arrows_df = var_arrows(t(L$G)))
p3 <- pca_panel(L$E, diag(2), diag(2), L$week, expression("Shocks "*bold(epsilon)[t] == italic(D)^{-1}*bold(f)[t]),
"stretch undone: standardised scores", expression(epsilon[1]), expression(epsilon[2]),
arrows_df = var_arrows(t(L$G %*% L$D))) # rows of A: the standardised biplot
col_wk <- "#e6820e"
p1 + pca_step("Gamma*minute", col_wk) + p2 + pca_step("italic(D)^{-1}", col_wk) + p3 +
plot_layout(widths = c(1, 0.2, 1, 0.2, 1))
}
# draw the figure
fig_pca_inverse()
The middle panel is the biplot: the observations at their scores, and the variables as arrows. Each arrow is where \(\Gamma'\) sends one unit of a variable, \(\Gamma'e_i\), which is row \(i\) of \(\Gamma\), so the arrows are the rows of \(\Gamma\). Because \(\Gamma\) is a rotation, the picture is the data panel turned, with nothing stretched: the inner product of a point with an arrow is that week’s value of the variable, \(x_{ti}=\gamma_{i1}f_{t1}+\gamma_{i2}f_{t2}\), and distances between points are distances between weeks. The right panel is the other common version, the standardised biplot. Undoing the stretch squishes the points into the round cloud of shocks, so for the inner product to still give the data, the stretch has to move onto the arrows: they are the rows of \(A=\Gamma D\), and \(x_{ti}=a_{i1}\varepsilon_{t1}+a_{i2}\varepsilon_{t2}\). Section 4.2.5 shows how to read biplots.
4.2.4 Dropping the short arrows
Because the first arrow carries 95% of the variance, dropping the second loses little:
\[ \mathbf x_t\approx \varepsilon_{t1}\,a_1=f_{t1}\,\gamma_1 . \]
Each week is described by one number, its score \(f_{t1}\), its position along the market direction: the dimension reduction of the Introduction. The figure below turns the second arrow off. On the left, each week’s prediction \(\hat{\mathbf x}_t=f_{t1}\gamma_1\) is its projection onto the line of the first arrow, and the segment joining it to the actual week is the part that was dropped, \(\varepsilon_{t2}a_2\), perpendicular to the line. On the right, the predictions are plotted against the actual sales. They are close: they reproduce 95% of the variance of Coca-Cola sales and 96% of Pepsi’s.
f2 <- function(x, d = 2) formatC(x, format = "f", digits = d)
fig_pca_drop <- function() {
X <- scale(cola, scale = FALSE); e <- eigen(cov(X), symmetric = TRUE)
G <- e$vectors; if (G[1, 1] < 0) G[, 1] <- -G[, 1]
a1 <- G[, 1] * sqrt(e$values[1]); a2 <- G[, 2] * sqrt(e$values[2])
eps1 <- (X %*% G[, 1]) / sqrt(e$values[1])
P <- eps1 %*% t(a1)
d <- tibble(x = X[, 1], y = X[, 2], px = P[, 1], py = P[, 2])
r2 <- 1 - colSums((X - P)^2) / colSums(X^2)
p1 <- ggplot(d) + axes0 +
geom_abline(slope = a1[2] / a1[1], intercept = 0, colour = col_a1, alpha = 0.5) +
geom_segment(aes(x, y, xend = px, yend = py), colour = "grey55", linewidth = 0.3) +
geom_point(aes(x, y), colour = "#6f7a8c", alpha = 0.5, size = 1.4) +
geom_point(aes(px, py), colour = col_a1, size = 1.4) +
coord_equal(xlim = c(-3.2, 3.2), ylim = c(-3.2, 3.2)) +
labs(x = expression("Coca-Cola"~italic(x)[1]), y = expression("Pepsi"~italic(x)[2]),
title = expression("Second arrow off: " * hat(bold(x))[t] == epsilon[t1] * italic(a)[1]),
subtitle = "grey: actual, blue: predicted")
lab <- c(coke = sprintf("Coca-Cola (R\u00b2 = %s)", f2(r2[1])), pepsi = sprintf("Pepsi (R\u00b2 = %s)", f2(r2[2])))
d2 <- bind_rows(tibble(brand = lab[["coke"]], actual = X[, 1], pred = P[, 1]),
tibble(brand = lab[["pepsi"]], actual = X[, 2], pred = P[, 2]))
p2 <- ggplot(d2, aes(actual, pred, colour = brand)) +
geom_abline(slope = 1, intercept = 0, colour = "grey60", linetype = "22") +
geom_point(alpha = 0.6, size = 1.4) +
scale_colour_manual(values = c("#b2182b", "#2166ac"), name = NULL) +
coord_equal(xlim = c(-3.2, 3.2), ylim = c(-3.2, 3.2)) +
labs(x = "actual sales (deviation)", y = "predicted from the first arrow",
title = "Predicted against actual", subtitle = "dashed line: perfect") +
theme(legend.position = c(0.3, 0.88), legend.background = element_rect(fill = "white", colour = NA))
p1 + p2
}
# draw the figure
fig_pca_drop()
4.2.5 Reading the biplot
With two variables, the biplot shows nothing that the scatterplot did not. Its value comes with more variables, where it shows the first two of many components: a map of the observations and the variables at once (the states in Section 4.5). Because \(x_{ti}=\gamma_{i1}f_{t1}+\gamma_{i2}f_{t2}\), it is read with three rules, exact when all components are shown and approximate when some are dropped:
- Point and arrow. A week far out in the direction of the Pepsi arrow sold a lot of Pepsi: its value on a variable is its projection onto that variable’s arrow, times the arrow’s length.
- Distances between points are the Euclidean distances between the observations (Chapter 2), because a rotation does not change distances. With more than two variables, the biplot shows only the first two components, and the distances on the map leave out the differences along the dropped ones: they are never longer than the true distances.
- Arrow lengths. With all components, every arrow has length one (the rows of a rotation). When the biplot keeps only the first two of \(p\) components, arrow \(i\) has length \(\sqrt{\gamma_{i1}^2+\gamma_{i2}^2}\le1\): the shorter it is, the more of variable \(i\) lies in the dropped components, and the less the map says about it.
The two versions of the biplot in the backward figure come with two names for their arrows. In the scores version, the arrows are the rows of \(\Gamma\), and the entries of \(\Gamma\) are called the weights: they say how each score is computed, \(f_{tj}=\gamma_{1j}x_{t1}+\gamma_{2j}x_{t2}\). In the standardised version, the arrows are the rows of \(A=\Gamma D\), called the loadings: one standard deviation of component \(j\) moves variable \(i\) by \(a_{ij}=\gamma_{ij}d_j\), and divided by the standard deviation \(s_i\) of the variable this is the correlation between variable and component. Software uses the word “loadings” for both, so it pays to check which one is meant. In R:
pc_cola <- prcomp(cola)
head(pc_cola$x, 3) # scores f_t (first three weeks)
## PC1 PC2
## [1,] 0.003983154 -0.01521639
## [2,] 0.932400319 -0.10206863
## [3,] -3.433352009 0.01052975
pc_cola$rotation # weights: Gamma (arrows of the scores biplot)
## PC1 PC2
## coke -0.6882736 -0.7254512
## pepsi -0.7254512 0.6882736
pc_cola$sdev # standard deviations d_j of the scores
## [1] 1.4146784 0.3141419
# biplot(pc_cola, scale = 0) draws the scores version; the default, scale = 1, the standardised oneThe rest of the chapter makes this practical. Section 4.3 reaches the same arrows from the data side, by projecting, and Section 4.4 shows how linear algebra finds them without a slider. The later sections ask which matrix to start from and how many components to keep.
Check your understanding
- In \(\mathbf x_t=A \boldsymbol\varepsilon_t\) with uncorrelated unit-variance shocks, the squared length \(\lVert a_j\rVert^2\) of
column \(j\) is
- the correlation between the two variables
- the part of the total variance carried by shock \(j\)
- the mean of shock \(j\)
- always one
- Turning both arrows together changes
- the covariance matrix \(S\)
- the total variance \(\operatorname{tr}(S)\)
- how the total variance is divided between the two shocks
- the data
- PCA chooses the rotation at which
- the two arrows have equal length
- the first arrow is as long as possible
- the arrows point along the coordinate axes
- \(A\) is lower triangular
- The scores \(\mathbf f_t=\Gamma'\mathbf x_t\) undo
- the stretch \(D\) only
- the rotation \(\Gamma\) only, so their variances are still \(d_j^2\)
- both layers of \(A\), so their variances are one
- nothing; they are the data
- In a biplot of the first two of six components, a variable’s arrow is very short. This means
- the variable has a small variance
- the variable lies mostly in the dropped components, so the map says little about it
- the variable is uncorrelated with all others
- the variable was measured in small units
Answers
1 b. 2 c. 3 b. 4 b. 5 b.4.3 Projections: the same answer from the data side
The scores of Section 4.2 are projections onto the arrows. Turn this around: project the data onto any direction, and ask which direction makes the projections spread out most. The answer is the first arrow again, now reached from the data alone.
4.3.1 A score along a direction
Section 4.2 had two scores per week, one for each arrow: \(f_{t1}=\gamma_1'\mathbf x_t\) and \(f_{t2}=\gamma_2'\mathbf x_t\). Here we look at the first one only, a single linear combination of the two variables, and leave its direction open: \(\gamma_1=(\gamma_{11},\gamma_{21})'\) is any vector of length one, \(\gamma_1'\gamma_1=\gamma_{11}^2+\gamma_{21}^2=1\), not yet the PCA direction. Drop every week onto the line through the origin (the mean) in that direction. Its position on the line is its score,
\[ f_{t1}=\gamma_1'\mathbf x_t=\gamma_{11}\,x_{t1}+\gamma_{21}\,x_{t2}, \]
a weighted sum of the week’s deviations from the mean, exactly as in the scores of Section 4.2.
The scores have mean zero, because the \(\mathbf x_t\) do. Their sample variance is therefore the sum of squared scores divided by \(n-1\), and writing the square as \(f_{t1}^2=(\gamma_1'\mathbf x_t)(\mathbf x_t'\gamma_1)\) lets \(\gamma_1\) move outside the sum:
\[ s_{f_1}^2=\frac{1}{n-1}\sum_{t=1}^n f_{t1}^2 =\gamma_1'\Big(\frac{1}{n-1}\sum_{t=1}^n\mathbf x_t\mathbf x_t'\Big)\gamma_1 =\gamma_1'S\,\gamma_1 , \]
since the matrix in the middle is the sample covariance matrix of the centred data (Chapter 3). Written out, \(\gamma_1'S\gamma_1=\gamma_{11}^2s_1^2+2\gamma_{11}\gamma_{21}s_{12}+\gamma_{21}^2s_2^2\), the rule for the variance of a linear combination (Section 3.5.4).
This is the same quantity as the squared length of the first arrow. With \(q=(\cos\varphi,\sin\varphi)'\), the first column of \(Q(\varphi)\), the first arrow is \(a_1=S^{1/2}q\), so \(\lVert a_1\rVert^2=q'S^{1/2}S^{1/2}q=q'Sq\): the variance of the scores along \(q\). Turn the line with the slider; the right panel is the blue curve of the arrow figure again:
fig_pca_direction <- function() {
S <- cov(cola); X <- scale(cola, scale = FALSE)
phis <- seq(0, 175, by = 5)
v_of <- function(phi) c(cos(phi * pi / 180), sin(phi * pi / 180))
curve <- tibble(phi = seq(0, 180, by = 1)) |>
mutate(v = purrr::map_dbl(phi, function(p) { g <- v_of(p); drop(t(g) %*% S %*% g) }))
lab <- function(p) p # numeric frames: slider in numeric order
fr <- purrr::map_dfr(phis, function(p) {
g <- v_of(p); s <- drop(X %*% g)
tibble(frame = lab(p), x = X[, 1], y = X[, 2], px = s * g[1], py = s * g[2])
})
lines <- purrr::map_dfr(phis, function(p) { g <- v_of(p)
tibble(frame = lab(p), x = c(-4 * g[1], 4 * g[1]), y = c(-4 * g[2], 4 * g[2])) })
segs <- fr |> mutate(id = rep(seq_len(nrow(X)), length(phis)))
seg_df <- segs |> group_by(frame) |> group_modify(~ {
tibble(x = as.vector(rbind(.x$x, .x$px, NA)), y = as.vector(rbind(.x$y, .x$py, NA))) }) |> ungroup()
mark <- tibble(frame = lab(phis), phi = phis,
v = purrr::map_dbl(phis, function(p) { g <- v_of(p); drop(t(g) %*% S %*% g) }))
txt <- mark |> mutate(t = sprintf("angle %d°: variance of the scores = %.2f", phi, v))
p1 <- plot_ly() |>
add_trace(data = seg_df, x = ~x, y = ~y, frame = ~frame, type = "scatter", mode = "lines",
line = list(color = "rgba(150,150,150,0.45)", width = 1), hoverinfo = "skip", showlegend = FALSE) |>
add_trace(data = fr, x = ~x, y = ~y, frame = ~frame, type = "scatter", mode = "markers",
marker = list(color = "rgba(111,122,140,0.55)", size = 5), hoverinfo = "skip", showlegend = FALSE) |>
add_trace(data = lines, x = ~x, y = ~y, frame = ~frame, type = "scatter", mode = "lines",
line = list(color = col_a1, width = 3), hoverinfo = "skip", showlegend = FALSE) |>
add_trace(data = fr, x = ~px, y = ~py, frame = ~frame, type = "scatter", mode = "markers",
marker = list(color = col_a1, size = 4), hoverinfo = "skip", showlegend = FALSE)
p2 <- plot_ly() |>
add_trace(data = curve, x = ~phi, y = ~v, type = "scatter", mode = "lines",
line = list(color = "black", width = 2), hoverinfo = "skip", showlegend = FALSE) |>
add_trace(data = mark, x = ~phi, y = ~v, frame = ~frame, type = "scatter", mode = "markers",
marker = list(color = col_a1, size = 12), hoverinfo = "skip", showlegend = FALSE) |>
add_trace(data = txt, x = I(90), y = I(max(curve$v) * 1.13), text = ~t, frame = ~frame, type = "scatter",
mode = "text", textfont = list(size = 13, color = col_a1), hoverinfo = "skip", showlegend = FALSE)
subplot(p1, p2, widths = c(0.5, 0.5), margin = 0.07, titleX = TRUE, titleY = TRUE) |>
layout(xaxis = list(title = "Coca-Cola sales (deviation)", range = c(-3.6, 3.6), zeroline = FALSE),
yaxis = list(title = "Pepsi sales (deviation)", range = c(-3.6, 3.6), scaleanchor = "x", zeroline = FALSE),
xaxis2 = list(title = "angle of the line (degrees)", range = c(0, 180), dtick = 45),
yaxis2 = list(title = "variance of the scores", range = c(0, max(curve$v) * 1.2)),
margin = list(t = 20)) |>
animation_opts(frame = 120, transition = 0, redraw = FALSE) |>
animation_slider(currentvalue = list(prefix = "angle: ", suffix = "°")) |>
animation_button(x = 0, xanchor = "left", y = -0.2, yanchor = "top", label = "Play")
}
# draw the figure
fig_pca_direction()Along the cloud, the scores spread out widely; across it they are bunched together. The variance is largest at an angle of about 47 degrees, where it reaches 2.00, and smallest at the perpendicular direction, where it is only 0.10.
4.3.2 The principal components
So the longest first arrow points in the direction with the largest score variance. In this language, the first principal component is the direction \(\gamma_1\) with the largest score variance,
\[ \max_{\gamma_1}\;\gamma_1'S\gamma_1\qquad\text{subject to}\qquad \gamma_1'\gamma_1=1 . \]
The constraint matters: without it, doubling \(\gamma_1\) would quadruple the variance, and there would be no maximum. It is the normalisation of Section 4.1, columns of \(\Gamma\) of length one, seen from the data side. The second principal component \(\gamma_2\) maximises \(\gamma_2'S\gamma_2\) in the same way, among all unit vectors perpendicular to the first, \(\gamma_2'\gamma_1=0\); the third is perpendicular to both, and so on, up to \(p\) components. The scores on the \(j\)-th component, \(f_{tj}=\gamma_j'\mathbf x_t\), are the new variables.
4.3.3 The best-fitting line
The first component has a second description. By Pythagoras, the squared distance of a point from the centre splits into the squared score along the line plus the squared distance to the line:
\[ \lVert \mathbf x_t\rVert^2=f_t^2+\big(\text{perpendicular distance of } \mathbf x_t \text{ to the line}\big)^2 . \]
The left side does not depend on the line. So the line that maximises the sum of squared scores is the line that minimises the sum of squared perpendicular distances: the first principal component is the line of best fit in the perpendicular sense. Regression fits a different line, because it minimises the vertical distances: it treats one variable as given and the other as the outcome, the assumption the Introduction questioned. PCA treats the variables symmetrically.
fig_pca_vs_ols <- function() {
X <- scale(air_X, scale = FALSE); S <- cov(X)
g <- eigen(S, symmetric = TRUE)$vectors[, 1]; if (g[1] < 0) g <- -g
b <- S[1, 2] / S[1, 1]
set.seed(3); idx <- sample(nrow(X), 45)
d <- tibble(x = X[idx, 1], y = X[idx, 2]) |>
mutate(s = x * g[1] + y * g[2], px = s * g[1], py = s * g[2], fy = b * x)
base <- ggplot(d) + axes0 + coord_equal(xlim = c(-4, 4), ylim = c(-4.5, 4.5)) +
labs(x = expression("flight time"~italic(x)[1]), y = expression("fuel"~italic(x)[2]))
p1 <- base +
geom_abline(slope = g[2] / g[1], intercept = 0, colour = col_a1, linewidth = 1.1) +
geom_segment(aes(x, y, xend = px, yend = py), colour = col_a1, alpha = 0.6) +
geom_point(aes(x, y), colour = "grey30", size = 1.6) +
labs(title = "First principal component", subtitle = "minimises the perpendicular distances")
p2 <- base +
geom_abline(slope = b, intercept = 0, colour = col_a2, linewidth = 1.1) +
geom_segment(aes(x, y, xend = x, yend = fy), colour = col_a2, alpha = 0.6) +
geom_point(aes(x, y), colour = "grey30", size = 1.6) +
labs(title = "Regression of fuel on time", subtitle = "minimises the vertical distances")
p1 + p2
}
# draw the figure
fig_pca_vs_ols()
Likewise, the first \(m\) components span the \(m\)-dimensional plane that is closest to the cloud.
Check your understanding
- The score of an observation along a unit vector \(\gamma\) is
- its distance from the line
- the signed length of the projection of \(\mathbf x_t\) onto \(\gamma\)
- the angle between \(\mathbf x_t\) and \(\gamma\)
- its Mahalanobis distance
- Why does PCA require \(\gamma'\gamma=1\)?
- Otherwise the scores would not have mean zero
- Otherwise the variance could be made as large as we like by scaling \(\gamma\)
- Otherwise \(S\) would not be symmetric
- Otherwise the components would be correlated
- Compared with the regression line of \(x_2\) on \(x_1\), the first principal component line
- minimises vertical distances
- minimises perpendicular distances and treats both variables alike
- is always steeper
- passes through the origin rather than the mean
Answers
1 b. 2 b. 3 b.4.4 Eigenvectors and eigenvalues
Sections 4.2 and 4.3 found the components by turning a slider. With many variables there are too many angles to try. Linear algebra finds them directly, with an idea worth learning on its own: eigenvectors (3Blue1Brown, chapter 14). This section shows what they are and why the PCA directions are eigenvectors of \(S\).
4.4.1 Vectors that stay on their line
A matrix moves the whole plane (the Introduction, and 3Blue1Brown, chapter 3). Take the covariance matrix \(S\) itself as such a movement: it sends each point \(v\) to \(Sv\). Most points are knocked off their own line, the line through the origin and \(v\) (its span). The points on a few special lines stay on them and are only stretched or squished:
\[ Sv=\lambda v . \]
Such a \(v\) is an eigenvector of \(S\), and the stretch factor \(\lambda\) is its eigenvalue (3Blue1Brown, chapter 14). The slider applies the movement gradually, from nothing at all (the identity) to \(S\), for the Coke and Pepsi \(S\). The points start on eight lines through the origin (dashed):
fig_eigen_turn <- function() {
S <- cov(cola); e <- eigen(S, symmetric = TRUE)
ang_e <- c(pca_phi, pca_phi + 90)
angs <- c(0, 22.5, 67.5, 90, 112.5, 157.5, ang_e)
kind <- c("x-axis", rep("other", 5), "eig1", "eig2")
cols <- c("x-axis" = "#222222", other = "#a6a6a6", eig1 = col_a1, eig2 = col_a2)
r <- seq(-1.5, 1.5, by = 0.25); r <- r[r != 0]
base <- purrr::map_dfr(seq_along(angs), function(i) {
u <- c(cos(angs[i] * pi / 180), sin(angs[i] * pi / 180))
tibble(line = i, kind = kind[i], x0 = r * u[1], y0 = r * u[2]) })
ks <- seq(0, 1, by = 0.05)
fr <- purrr::map_dfr(ks, function(k) { Tk <- (1 - k) * diag(2) + k * S
P <- cbind(base$x0, base$y0) %*% t(Tk); mutate(base, frame = k, x = P[, 1], y = P[, 2]) })
lines <- purrr::map_dfr(ks, function(k) purrr::map_dfr(seq_along(angs), function(i) {
u <- c(cos(angs[i] * pi / 180), sin(angs[i] * pi / 180))
tibble(frame = k, kind = kind[i], x = c(-3.4 * u[1], 3.4 * u[1], NA), y = c(-3.4 * u[2], 3.4 * u[2], NA)) }))
lab <- tibble(frame = ks, t = ifelse(ks == 0, "identity: nothing moves",
sprintf("blue line stretched by %.2f, red line by %.2f", 1 - ks + ks * e$values[1],
1 - ks + ks * e$values[2])))
p <- plot_ly()
for (kd in names(cols)) {
p <- p |>
add_trace(data = filter(lines, kind == kd), x = ~x, y = ~y, frame = ~frame, type = "scatter", mode = "lines",
line = list(color = cols[[kd]], width = if (kd == "other") 1 else 1.5, dash = "dash"),
opacity = if (kd == "other") 0.5 else 0.8, hoverinfo = "skip", showlegend = FALSE) |>
add_trace(data = filter(fr, kind == kd), x = ~x, y = ~y, frame = ~frame, type = "scatter", mode = "markers",
marker = list(color = cols[[kd]], size = if (kd == "other") 6 else 8), hoverinfo = "skip",
showlegend = FALSE)
}
p |>
add_trace(data = lab, x = I(0), y = I(3.05), text = ~t, frame = ~frame, type = "scatter", mode = "text",
textfont = list(size = 14), hoverinfo = "skip", showlegend = FALSE) |>
layout(xaxis = list(title = "first coordinate", range = c(-3.4, 3.4), zeroline = FALSE),
yaxis = list(title = "second coordinate", range = c(-3.4, 3.4), scaleanchor = "x", zeroline = FALSE),
margin = list(t = 10)) |>
animation_opts(frame = 150, transition = 0, redraw = FALSE) |>
animation_slider(currentvalue = list(prefix = "how much of S is applied: ")) |>
animation_button(x = 0, xanchor = "left", y = -0.12, yanchor = "top", label = "Play")
}
# draw the figure
fig_eigen_turn()The points on the grey lines, and on the horizontal line in black, leave their lines. The points on the blue line, at 46.5 degrees, stay on it and are stretched by \(\lambda_1=2.00\); those on the red line, at 136.5 degrees, stay on it and are squished by \(\lambda_2=0.10\). These are the two directions of the PCA arrows, and the stretch factors are the factor variances \(d_1^2\) and \(d_2^2\). The next subsection shows that this is no coincidence.
4.4.2 Why the PCA directions are eigenvectors
Start from the covariance matrix and the PCA split of Section 4.2, \(A=\Gamma D\) with \(\Gamma\) a rotation and \(D\) diagonal:
\[ S=AA'=(\Gamma D)(\Gamma D)'=\Gamma D D'\Gamma'=\Gamma D^2\Gamma' , \]
using \((\Gamma D)'=D'\Gamma'\) and \(D'=D\) for a diagonal matrix. Now multiply both sides by \(\Gamma\) on the right. Because \(\Gamma'\Gamma=I\), the last two matrices cancel:
\[ S\Gamma=\Gamma D^2\Gamma'\Gamma=\Gamma D^2 . \]
Read this column by column. Column \(j\) of \(S\Gamma\) is \(S\gamma_j\). Column \(j\) of \(\Gamma D^2\) is \(d_j^2\gamma_j\), because multiplying by a diagonal matrix on the right just scales each column. So
\[ S\gamma_j=d_j^2\,\gamma_j , \]
which is exactly the eigenvector equation: each PCA direction \(\gamma_j\) is an eigenvector of \(S\), and its eigenvalue is \(d_j^2\), the variance of factor \(j\). In the figure, the points on the blue line are stretched by \(d_1^2\) and those on the red line by \(d_2^2\). And because PCA makes the first arrow as long as possible, the first component is the eigenvector with the largest eigenvalue, the second the one with the next largest, and so on.
The connection also runs the other way, and that is how PCA is computed in practice. A matrix whose eigenvectors span the space can be written as
\[ S=Q\Lambda Q^{-1}, \]
with the eigenvectors as the columns of \(Q\) and the eigenvalues in the diagonal matrix \(\Lambda=\operatorname{diag}(\lambda_1,\dots,\lambda_p)\), read from right to left: \(Q^{-1}\) changes to the coordinates of the eigenvectors, \(\Lambda\) stretches each axis, and \(Q\) changes back (3Blue1Brown, chapters 13 and 14). This is the eigendecomposition. For a general matrix, \(Q\) is not a rotation and \(Q^{-1}\) has to be computed. Covariance matrices are special: they are symmetric, \(S'=S\), and for a symmetric matrix the eigenvectors can always be chosen perpendicular and of length one (the spectral theorem). Then \(Q\) is a rotation, \(Q^{-1}=Q'\), and
\[ S=Q\Lambda Q' \]
has exactly the form of the PCA split \(S=\Gamma D^2\Gamma'\): \(\Gamma=Q\) and \(D^2=\Lambda\), up to the order and signs of the
columns. The eigenvalues of a covariance matrix are variances, so they are never negative. One call to eigen()
therefore replaces the slider:
S <- cov(cola)
e <- eigen(S)
e$values # eigenvalues: the factor variances d_j^2
## [1] 2.00131488 0.09868512
e$vectors # eigenvectors: the directions gamma_j (columns), up to sign
## [,1] [,2]
## [1,] 0.6882736 -0.7254512
## [2,] 0.7254512 0.6882736
A <- e$vectors %*% diag(sqrt(e$values)) # the PCA choice of A = Gamma D
A %*% t(A) # reproduces S
## [,1] [,2]
## [1,] 1.00 0.95
## [2,] 0.95 1.10The \(j\)-th principal component is the eigenvector \(\gamma_j\) of \(S\) with the \(j\)-th largest eigenvalue, and the variance of its scores is that eigenvalue, \(\lambda_j=d_j^2\).
From here on the chapter writes \(\lambda_j\) for the variance of the \(j\)-th component. What Sections 4.1 and 4.2 showed about the factor variances now reads as a statement about eigenvalues: they add up to the total variance, \(\lambda_1+\dots+\lambda_p=\operatorname{tr}(S)\), so component \(j\) carries the share \(\lambda_j/\operatorname{tr}(S)\) of it. For Coke and Pepsi the market component carries 95%.
Check your understanding
- A vector \(v\) is an eigenvector of \(S\) when
- \(Sv\) is perpendicular to \(v\)
- \(Sv\) stays on the line through \(v\), \(Sv=\lambda v\)
- \(v\) has length one
- \(Sv=0\)
- The eigenvalue that belongs to the PCA direction \(\gamma_j\) is
- one
- the variance \(d_j^2\) of factor \(j\)
- the correlation of the variables
- the length of \(\gamma_j\)
- For a covariance matrix, the eigendecomposition can be written \(S=Q\Lambda Q'\) rather than \(S=Q\Lambda Q^{-1}\) because
- \(S\) is symmetric, so its eigenvectors can be chosen perpendicular and of length one
- every matrix has \(Q^{-1}=Q'\)
- the eigenvalues are positive
- \(\Lambda\) is diagonal
- With three variables of variances 4, 3 and 1, the three eigenvalues of \(S\) add up to
- 3
- 4
- 8
- it depends on the correlations
Answers
1 b. 2 b. 3 a. 4 c (the trace).4.5 Covariance or correlation matrix?
4.5.1 PCA depends on the units
PCA maximises variance, and variances depend on units. Back to the two arrows. Suppose Pepsi’s sales were recorded in different units, say in packs instead of single cans, or the other way round: multiply the Pepsi column by a factor \(k\). Nothing about the weeks has changed, but the covariance matrix has: Pepsi’s variance is multiplied by \(k^2\). Move the slider:
fig_scale_slider <- function() {
X <- scale(cola, scale = FALSE); Z <- scale(cola)
ks <- round(exp(seq(log(1 / 3), log(3), length.out = 41)), 3)
lab <- function(k) sprintf("%.3f", k)
pca_A <- function(M) { e <- eigen(cov(M), symmetric = TRUE); G <- e$vectors
if (G[1, 1] + G[2, 1] < 0) G[, 1] <- -G[, 1]; if (G[2, 2] < 0) G[, 2] <- -G[, 2]
list(A = G %*% diag(sqrt(e$values)), share = e$values[1] / sum(e$values), ang = atan2(G[2, 1], G[1, 1]) * 180 / pi) }
cols <- c(col_a1, col_a2)
pts <- purrr::map_dfr(ks, function(k) tibble(x = X[, 1], y = k * X[, 2], f = lab(k)))
arrows <- lapply(1:2, function(j) purrr::map_dfr(ks, function(k) {
A <- pca_A(cbind(X[, 1], k * X[, 2]))$A
arrow_geometry(A[, j], head_length = 0.35, head_width = 0.18, shaft_width = 0.04)$arrow |> mutate(k = lab(k)) }))
txt <- purrr::map_dfr(ks, function(k) { r <- pca_A(cbind(X[, 1], k * X[, 2]))
tt <- sprintf("Pepsi × %.2f: PC1 at %.0f°, %.0f%% of the variance", k, r$ang, 100 * r$share)
tibble(x = -7.6, y = 9.2, t = tt, k = lab(k)) })
Ar <- pca_A(Z)$A; ar <- lapply(1:2, function(j) arrow_geometry(Ar[, j], head_length = 0.2, head_width = 0.1,
shaft_width = 0.022)$arrow)
p1 <- plot_ly() |>
add_trace(data = pts, x = ~x, y = ~y, frame = ~f, type = "scatter", mode = "markers",
marker = list(size = 4, color = "#6f7a8c", opacity = 0.45), hoverinfo = "skip", showlegend = FALSE)
for (j in 1:2) p1 <- add_arrow_trace(p1, arrows[[j]], color = cols[j])
p1 <- p1 |> add_trace(data = txt, x = ~x, y = ~y, frame = ~k, text = ~t, type = "scatter", mode = "text",
textposition = "middle right", textfont = list(size = 12, color = "#2c3e50"),
hoverinfo = "skip", showlegend = FALSE, inherit = FALSE)
p2 <- plot_ly() |>
add_trace(x = Z[, 1], y = Z[, 2], type = "scatter", mode = "markers",
marker = list(size = 4, color = "#6f7a8c", opacity = 0.45), hoverinfo = "skip", showlegend = FALSE)
for (j in 1:2) p2 <- p2 |> add_trace(data = ar[[j]], x = ~x, y = ~y, type = "scatter", mode = "lines", fill = "toself",
fillcolor = cols[j], line = list(width = 1, color = cols[j]),
hoverinfo = "skip", showlegend = FALSE)
subplot(p1, p2, widths = c(0.6, 0.4), margin = 0.07, titleX = TRUE, titleY = TRUE) |>
layout(xaxis = list(title = "Coca-Cola sales (deviation)", range = c(-8, 8), zeroline = FALSE),
yaxis = list(title = "Pepsi sales × k (deviation)", range = c(-10, 10), scaleanchor = "x", zeroline = FALSE),
xaxis2 = list(title = "Coca-Cola (standardised)", range = c(-3.5, 3.5), zeroline = FALSE),
yaxis2 = list(title = "Pepsi (standardised)", range = c(-3.5, 3.5), scaleanchor = "x2", zeroline = FALSE),
annotations = list(
list(text = "<b>Covariance matrix</b>: depends on the units", x = 0, y = 1.06, xref = "paper", yref = "paper",
xanchor = "left", showarrow = FALSE, font = list(size = 13)),
list(text = "<b>Correlation matrix</b>: the same for every k", x = 0.62, y = 1.06, xref = "paper", yref = "paper",
xanchor = "left", showarrow = FALSE, font = list(size = 13))),
margin = list(t = 50, b = 120)) |>
animation_opts(frame = 100, transition = 0, redraw = TRUE) |>
animation_slider(currentvalue = list(prefix = "Pepsi units: × ")) |>
animation_button(x = 0, xanchor = "left", y = -0.25, yanchor = "top", label = "Play") |>
finalize_animation(list(list(label = "original units (× 1)", method = "animate",
args = list(list("1.000"), list(mode = "immediate", frame = list(duration = 0, redraw = TRUE),
transition = list(duration = 0))))),
start_frame = "1.000", prefix = "Pepsi units: × ")
}
# draw the figure
fig_scale_slider()As \(k\) grows, the first arrow swings towards the Pepsi axis and takes almost all of the variance; as \(k\) shrinks, it swings towards Coke. PCA of the covariance matrix finds the variable with the most units, not the most interesting direction. The right panel shows the remedy: standardise each variable first, \(z_{tj}=(x_{tj}-\bar x_j)/s_j\). Standardised values do not depend on the units, so neither do their components. The covariance matrix of standardised variables is the correlation matrix \(R\); for two variables its components are always the sum and the difference, \(\tfrac{1}{\sqrt2}(1,1)'\) and \(\tfrac{1}{\sqrt2}(1,-1)'\) (Section 4.4).
PCA is not scale-invariant: changing the units of a variable changes the components, not just their units (Everitt and Hothorn, Section 3.4). When the variables are measured in different units, use PCA of the correlation matrix. Every variable then has variance one, \(\operatorname{tr}(R)=p\), and each starts with an equal claim on the components. Working with \(S\) is appropriate when all variables share a unit and their variances are comparable (sales of two brands in the same units, test scores on the same scale).
4.5.2 More variables: the states
With more variables and very different units, the effect is extreme. Run PCA on the covariance matrix of the six state indicators of Chapter 2:
pct <- function(x, d = 0) paste0(formatC(100 * x, format = "f", digits = d), "%")
fig_scale <- function() {
w_cov <- st_cov$rotation[, 1]; if (w_cov["Income"] < 0) w_cov <- -w_cov
d <- bind_rows(
tibble(var = names(w_cov), w = w_cov, which = sprintf("Covariance matrix: PC1 = %s of the variance",
pct(st_cov$sdev[1]^2 / sum(st_cov$sdev^2), 1))),
tibble(var = names(w_cov), w = st_cor$rotation[, 1], which = sprintf("Correlation matrix: PC1 = %s of the variance",
pct(st_lam[1] / sum(st_lam))))) |>
mutate(var = factor(var, levels = rev(colnames(X6))), which = factor(which, levels = unique(which)))
sds <- tibble(var = factor(colnames(X6), levels = rev(colnames(X6))), sd = apply(X6, 2, sd))
p0 <- ggplot(sds, aes(sd, var)) + geom_col(fill = "grey60", width = 0.6) +
geom_text(aes(label = formatC(sd, format = "f", digits = 1)), hjust = -0.15, size = 3.6) +
scale_x_continuous(expand = expansion(mult = c(0, 0.25))) +
labs(title = "Standard deviations", x = "sd (in the variable's units)", y = NULL)
p1 <- ggplot(d, aes(w, var, fill = w > 0)) + geom_col(width = 0.6, show.legend = FALSE) +
geom_vline(xintercept = 0, colour = "grey40") +
scale_fill_manual(values = c(`TRUE` = col_a1, `FALSE` = col_a2)) +
facet_wrap(~ which, ncol = 1) + xlim(-1, 1) +
labs(title = "Weights of the first component", x = expression("weight in"~gamma[1]), y = NULL)
p0 + p1 + plot_layout(widths = c(0.8, 1.2))
}
# draw the figure
fig_scale()
Income, in dollars, has a standard deviation of 614; illiteracy, in percent, one of 0.61. The first component of the covariance matrix is income alone, with 99.3% of the total variance. Everitt and Hothorn find the same with blood chemistry data, where the platelet count, with a variance about 400 times that of any other variable, takes the first component on its own. From the correlation matrix, all six variables count.
X <- state.x77[, c("Income", "Illiteracy", "Life Exp", "Murder", "HS Grad", "Frost")]
round(summary(prcomp(X))$importance, 3) # covariance matrix: income dominates
## PC1 PC2 PC3 PC4 PC5 PC6
## Standard deviation 614.605 50.694 6.22 2.913 0.687 0.322
## Proportion of Variance 0.993 0.007 0.00 0.000 0.000 0.000
## Cumulative Proportion 0.993 1.000 1.00 1.000 1.000 1.000
pc <- prcomp(X, scale. = TRUE) # correlation matrix (standardised variables)
round(summary(pc)$importance, 3)
## PC1 PC2 PC3 PC4 PC5 PC6
## Standard deviation 1.885 0.994 0.889 0.567 0.454 0.374
## Proportion of Variance 0.592 0.165 0.132 0.054 0.034 0.023
## Cumulative Proportion 0.592 0.757 0.889 0.942 0.977 1.000
round(pc$rotation[, 1:2], 2)
## PC1 PC2
## Income 0.31 0.72
## Illiteracy -0.47 0.13
## Life Exp 0.42 -0.06
## Murder -0.44 0.38
## HS Grad 0.43 0.40
## Frost 0.35 -0.414.5.3 The states in a biplot
pct <- function(x, d = 0) paste0(formatC(100 * x, format = "f", digits = d), "%")
biplot_gg <- function(Y, G, lam, point_labels = NULL, label_all = FALSE, arrow_scale = 1,
var_col = col_a2, pt_col = col_a1) {
L <- G[, 1:2] * arrow_scale
d <- tibble(id = rownames(Y), y1 = Y[, 1], y2 = Y[, 2])
d$lab <- if (label_all) d$id else if (is.null(point_labels)) NA_character_ else unname(point_labels[d$id])
a <- tibble(var = rownames(G), x = L[, 1], y = L[, 2])
sec <- function(nm) sec_axis(~ . / arrow_scale, name = nm)
ggplot() + axes0 +
geom_point(data = d, aes(y1, y2), colour = pt_col, size = 1.8, alpha = 0.7) +
geom_text_repel(data = filter(d, !is.na(lab)), aes(y1, y2, label = lab), size = 3.2, colour = pt_col,
seed = 4, max.overlaps = 40) +
geom_segment(data = a, aes(0, 0, xend = x, yend = y), colour = var_col, linewidth = 1,
arrow = arrow(length = unit(0.2, "cm"))) +
geom_label_repel(data = a, aes(x, y, label = var), colour = var_col, size = 3.8, fontface = "bold",
label.size = 0, fill = alpha("white", 0.8), seed = 7, min.segment.length = 10,
box.padding = 0.15, point.padding = 0) +
scale_x_continuous(sec.axis = sec(NULL)) + scale_y_continuous(sec.axis = sec(NULL)) +
coord_equal() +
theme(axis.title.x.top = element_text(colour = var_col), axis.title.y.right = element_text(colour = var_col),
axis.text.x.top = element_text(colour = var_col), axis.text.y.right = element_text(colour = var_col)) +
labs(x = sprintf("PC1 score (%s of the variance)", pct(lam[1] / sum(lam))),
y = sprintf("PC2 score (%s)", pct(lam[2] / sum(lam))))
}
fig_states_biplot <- function() {
Y <- st_cor$x; rownames(Y) <- state.abb
biplot_gg(Y, st_cor$rotation, st_lam, label_all = TRUE, arrow_scale = 4)
}
# draw the figure
fig_states_biplot()
The biplot also helps to interpret the components. Each arrow’s coordinates, read on the red axes at the top and right, are the variable’s weights on the two components. So:
- an arrow that points almost horizontally belongs mainly to the first component, one that points almost vertically to the second;
- two arrows pointing in opposite directions along one line form a contrast: a component that runs along that line separates states high on one variable from states high on the other.
The illiteracy and life-expectancy arrows lie almost on the horizontal axis, pointing in opposite directions (weights -0.47 and 0.42 on the first component, 0.13 and -0.06 on the second). The first component (59% of the variance) is therefore mainly the contrast between illiteracy and life expectancy, with murder joining illiteracy on the left and graduation, frost and income joining life expectancy on the right: an index of general well-being. The southern states (Louisiana, Mississippi, Alabama, South Carolina) sit at the left, the northern plains (Minnesota, North Dakota, Iowa, Utah) at the right.
The income arrow points mostly upwards (weight 0.72 on the second component, the largest of all), so the second component (16%) is mainly income. Murder and frost point in opposite directions along a diagonal: they contrast on both components, and on the second one murder goes up with income and frost goes down. States high on the second component are richer and warmer, with more murders (Alaska, California, Hawaii, Florida, Nevada at the top).
The arrow lengths show how well the map represents each variable. With all six components every arrow would have length one. Here the income arrow is the longest (0.78): income lies mostly in the plane of the first two components, and the map shows it well. The life-expectancy arrow is the shortest (0.42), followed by illiteracy (0.49): much of their variation lies in the four dropped components, so the map says less about them, and states that look alike on the map can still differ in life expectancy.
These labels are interpretations, not facts: they come from reading weights, and two components keep 76% of the variance, not all of it. Section 4.8 returns to this. The distances between the states on the map approximate their Euclidean distances in the six standardised variables. (The arrows are drawn four times longer than they are; the red axes give their scale.)
Check your understanding
- Recording Pepsi’s sales in units ten times smaller (multiplying the column by 10) makes the first component of
the covariance matrix
- stay the same
- swing towards Pepsi and take almost all of the variance
- swing towards Coke
- disappear
- PCA of the correlation matrix is the same as
- PCA of the covariance matrix of the standardised variables
- PCA of the raw data in thousands of dollars
- regression of each variable on the others
- the covariance matrix with the diagonal removed
- For a correlation matrix of \(p\) variables, the eigenvalues add up to
- 1
- \(p\)
- \(n\)
- the largest variance
Answers
1 b. 2 a. 3 b.4.6 How many components?
All \(p\) components together reproduce the data exactly. The point of PCA is to keep fewer. There is no single correct number; Everitt and Hothorn (Section 3.8) list the common rules of thumb:
- Percentage of variance. Keep enough components to explain a chosen share of the total variance, usually between 70% and 90%.
- Above-average eigenvalues. Keep the components with \(\lambda_j\) above the average eigenvalue, \(\operatorname{tr}(S)/p\), the components that explain more than an average variable. For a correlation matrix the average is one: the Kaiser rule \(\lambda_j>1\). Jolliffe (1972) found in simulations that this drops too many components and suggested \(\lambda_j>0.7\) instead.
- Scree plot. Plot \(\lambda_j\) against \(j\) and look for an elbow, where the curve changes from steep to flat (Cattell 1966; scree is the rubble at the foot of a cliff). Keep the components before the flat part. A variant plots \(\log\lambda_j\).
fig_scree <- function() {
mk <- function(lam, name) tibble(data = name, j = seq_along(lam), lambda = lam, cum = cumsum(lam) / sum(lam))
d <- mk(st_lam, "US states (6 variables)")
ggplot(d, aes(j, lambda)) +
geom_hline(yintercept = 1, colour = col_a2, linetype = 2) +
geom_hline(yintercept = 0.7, colour = col_a2, linetype = 3) +
geom_line(linewidth = 1) + geom_point(size = 2.6) +
geom_text(aes(label = paste0(round(100 * cum), "%")), nudge_y = 0.3, size = 3.3, colour = "grey30") +
geom_text(data = tibble(y = c(1, 0.7), lab = c("1 (Kaiser)", "0.7 (Jolliffe)")),
aes(x = 6, y = y, label = lab), hjust = 1, vjust = c(-0.4, 1.4), colour = col_a2, size = 3.3) +
scale_x_continuous(breaks = 1:6) +
labs(x = "component", y = expression("eigenvalue"~lambda[j]~"(variance of the component)"),
subtitle = "Labels: cumulative share of the total variance")
}
# draw the figure
fig_scree()
The rules disagree. For the states, 70% asks for 2 components and 90% for 4; the Kaiser rule keeps 1 (the second eigenvalue, 0.99, misses the cut-off by a hair), Jolliffe’s 0.7 keeps 3, and the elbow at component 2 says one. These are guides, not tests: choose with the purpose in mind. Two components are needed for a scatterplot; an index needs one; an input to a later analysis may need more.
Check your understanding
- In a scree plot, the elbow marks
- the component with the largest eigenvalue
- where the eigenvalues stop falling steeply and level off
- the component that explains exactly 50%
- where the eigenvalues become negative
- For a correlation matrix, the Kaiser rule keeps components with eigenvalue above 1 because
- 1 is the variance of each standardised variable, so such components explain more than one variable
- eigenvalues above 1 are statistically significant
- the total variance is 1
- components with \(\lambda<1\) are negatively correlated
Answers
1 b. 2 a.4.7 Reconstruction and unusual observations
With \(p\) variables, keeping only a few components loses information. How much, and for which observations? Because \(\Gamma\) is a rotation, the scores can be turned back into the data: \(\mathbf x_t=\Gamma \mathbf f_t =\sum_{j=1}^p f_{tj}\gamma_j\). Keeping only the first \(m\) terms gives the best approximation from \(m\) numbers,
\[ \hat{\mathbf x}_t=\sum_{j=1}^m f_{tj}\gamma_j , \]
and the sum of the squared errors over all observations and variables is \((n-1)(\lambda_{m+1}+\dots+\lambda_p)\): the variance of the dropped components. The covariance matrix is approximated in the same way, \(S\approx A_mA_m'\) with the first \(m\) columns of \(A\) (Everitt and Hothorn, Section 3.7).
fig_reconstruct <- function(states = c("Alaska", "Hawaii", "Texas")) {
Z <- scale(X6); G <- st_cor$rotation; Y <- st_cor$x
rec <- function(s, m) drop(G[, 1:m, drop = FALSE] %*% Y[s, 1:m]) # x-hat = sum of the first m score * weight
d <- purrr::map_dfr(states, function(s) bind_rows(
tibble(state = s, var = colnames(X6), m = "actual", z = Z[s, ]),
purrr::map_dfr(1:3, function(k) tibble(state = s, var = colnames(X6), z = rec(s, k), m = paste0("m = ", k))))) |>
mutate(var = factor(var, levels = colnames(X6)), state = factor(state, levels = states))
ggplot(d, aes(var, z)) +
geom_hline(yintercept = 0, colour = "grey60") +
geom_col(data = filter(d, m == "actual"), fill = "grey80", width = 0.7) +
geom_point(data = filter(d, m != "actual"), aes(colour = m, shape = m), size = 2.6,
position = position_dodge(width = 0.55)) +
scale_colour_manual(values = c("m = 1" = col_a1, "m = 2" = "#7b4fb5", "m = 3" = col_a2), name = "reconstruction") +
scale_shape_manual(values = c("m = 1" = 16, "m = 2" = 17, "m = 3" = 15), name = "reconstruction") +
facet_wrap(~ state, ncol = 3) +
labs(x = NULL, y = "standardised value (bars: actual)") +
theme(axis.text.x = element_text(angle = 40, hjust = 1), legend.position = "top")
}
# draw the figure
fig_reconstruct()
Texas follows the common pattern: one component (blue) already gets the signs and rough sizes of all six standardised values. Alaska and Hawaii do not: one component misses them badly, and only two or three components come close. Recall from Section 2.6 that these are the states with unusual combinations. This is no coincidence: the squared Mahalanobis distance is the sum of the standardised squared scores,
\[ d_t^2=\mathbf x_t'S^{-1}\mathbf x_t=\sum_{j=1}^p\frac{f_{tj}^2}{\lambda_j}=\sum_{j=1}^p\varepsilon_{tj}^2, \]
because \(S^{-1}=\Gamma D^{-2}\Gamma'\). A large score on a small component, a direction in which the cloud is thin, counts heavily. Unusual states are exactly those that the first components describe badly.
Z <- scale(X)
for (m in 1:4) {
Zhat <- pc$x[, 1:m, drop = FALSE] %*% t(pc$rotation[, 1:m, drop = FALSE]) # reconstruction from m scores
cat(m, "components: squared error", round(sum((Z - Zhat)^2), 1),
"= (n - 1) x dropped eigenvalues", round(49 * sum(pc$sdev[-(1:m)]^2), 1), "\n")
}
## 1 components: squared error 119.8 = (n - 1) x dropped eigenvalues 119.8
## 2 components: squared error 71.4 = (n - 1) x dropped eigenvalues 71.4
## 3 components: squared error 32.7 = (n - 1) x dropped eigenvalues 32.7
## 4 components: squared error 17 = (n - 1) x dropped eigenvalues 17Check your understanding
- Reconstructing standardised data from the first \(m\) components leaves a squared error equal to
- zero
- \((n-1)\) times the sum of the dropped eigenvalues
- \((n-1)\) times the sum of the kept eigenvalues
- the largest eigenvalue
- A state with a large score on the last component
- is typical
- is unusual in a direction where the cloud is thin, so it has a large Mahalanobis distance
- has a large value on every variable
- has been reconstructed exactly by the first component
Answers
1 b. 2 b.4.8 What PCA is, and what it is not
4.8.1 One choice of structural form
PCA is one answer to the identification problem of the Introduction: of all the matrices \(A\) with \(AA'=S\), it picks the one whose first column is longest. That is a choice made for convenience (order the directions by variance), not one forced by the data. For the flights, where we know the true shocks from the manual, the first principal component explains 91% of the variance, but it is neither the headwind nor the load: it is a mixture of both.
cloud_pts <- function(X, alpha = 0.45) geom_point(data = tibble(x = X[, 1], y = X[, 2]), aes(x, y),
colour = "#6f7a8c", alpha = alpha, size = 1.5)
fig_pca_vs_truth <- function() {
S <- cov(air_X); e <- eigen(S, symmetric = TRUE)
G <- e$vectors; if (G[1, 1] < 0) G[, 1] <- -G[, 1]; if (det(G) < 0) G[, 2] <- -G[, 2]
A_pca <- G %*% diag(sqrt(e$values))
el <- ellipse_xy(sym_root(S), 1); el <- tibble(x = el[1, ], y = el[2, ])
panel <- function(M, labs, title) {
lab <- tibble(x = M[1, ] * (1 + 0.9 / sqrt(colSums(M^2))), y = M[2, ] * (1 + 0.9 / sqrt(colSums(M^2))),
txt = labs, col = c(col_a1, col_a2))
ggplot() + axes0 + cloud_pts(air_X, 0.25) + geom_path(data = el, aes(x, y), linewidth = 0.9) +
geom_segment(data = tibble(xend = M[1, ], yend = M[2, ], col = c(col_a1, col_a2)),
aes(0, 0, xend = xend, yend = yend, colour = I(col)), linewidth = 1.5,
arrow = arrow(length = unit(0.22, "cm"), type = "closed")) +
geom_label(data = lab, aes(x, y, label = txt, colour = I(col)), size = 4, fontface = "bold",
label.size = 0, fill = alpha("white", 0.8), lineheight = 0.9) +
coord_equal(xlim = c(-4.2, 4.2), ylim = c(-4.2, 4.2)) +
labs(title = title, x = "flight time (min)", y = "fuel (100 kg)")
}
panel(A_pca, c("PC1", "PC2"), "PCA: longest first column") +
panel(air_A, c("headwind", "load"), "The true shocks (from the manual)")
}
# draw the figure
fig_pca_vs_truth()
So it is tempting, but risky, to give components names such as “all-round ability” or “quality of life”. Everitt and Hothorn quote Marriott (1974): “no mathematical method is, or could be, designed to give physically meaningful results.” A component that has an obvious meaning reflects a strongly structured data set, or luck. PCA is safest as a tool for description and compression: a low-dimensional map of the data, an index, or fewer inputs for a later analysis.
4.8.2 Practical points
- Correlation is needed. PCA can only compress correlated variables. If the variables are uncorrelated and standardised, every eigenvalue is one and no component is better than any other.
- Scale. Results depend on the units unless the variables are standardised (Section 4.5).
- Outliers. One observation can change the correlations, and hence the components (the PNG athlete). Look at the data first, as in Chapter 2.
- Signs and order. Signs are arbitrary. Components with nearly equal eigenvalues are unstable: a slightly different sample can swap them or mix them.
- Sample size. Larger samples give more stable components, especially when eigenvalues are close together. Rules such as \(n>100\) or \(n>5p\) have little evidence behind them (Everitt and Hothorn, Section 3.12).
- Regression on components. Highly correlated explanatory variables can be replaced by their first few components (principal components regression). The components with the largest variance need not be the ones that best predict the outcome, however: Everitt and Hothorn’s air-pollution example finds low-variance components that matter (Section 3.10.3).
Check your understanding
- For the flights, the first principal component
- is exactly the headwind shock
- is exactly the load shock
- is a mixture of both: PCA picks a convenient rotation, not the true one
- does not exist because the shocks are independent
- Six uncorrelated standardised variables give a correlation-matrix PCA in which
- the first component explains everything
- every eigenvalue is 1, so there is nothing to compress
- the components are the variables in order of their means
- the scree plot has a sharp elbow
Answers
1 c. 2 b.4.9 Two sets of variables: canonical correlation
PCA looks at the relations within one set of variables. Sometimes the question is about the relation between two sets: aptitude tests and achievement tests, plant growth and weather, or, for the states, education (illiteracy, high-school graduation) and health and safety (life expectancy, murder). Many pairwise correlations between the sets are hard to summarise, and the correlations within each set get in the way. Canonical correlation analysis (CCA, Everitt and Hothorn, Section 3.13) replaces each set by a few linear combinations.
With the first set \(x\) (\(q_1\) variables) and the second set \(y\) (\(q_2\) variables), find weights \(a_1\) and \(b_1\) such that the two canonical variates \(u_1=a_1'x\) and \(v_1=b_1'y\) have the largest possible correlation \(R_1\), the first canonical correlation. Then find a second pair \((u_2,v_2)\) with the largest correlation \(R_2\) among combinations uncorrelated with the first pair, and so on, up to \(s=\min(q_1,q_2)\) pairs. Like the principal components, the weights are eigenvectors: with \(R_{11}\) and \(R_{22}\) the correlation matrices within the two sets and \(R_{12}=R_{21}'\) the correlations between them, the \(a_i\) are the eigenvectors of \(E_1=R_{11}^{-1}R_{12}R_{22}^{-1}R_{21}\), the \(b_i\) those of \(E_2=R_{22}^{-1}R_{21}R_{11}^{-1}R_{12}\), and the eigenvalues are the squared canonical correlations \(R_i^2\).
For the states, the first canonical correlation is 0.71. In standardised variables, the first pair is approximately
\[ u_1\propto-0.98\,\text{Illiteracy}+0.19\,\text{HSGrad},\qquad v_1\propto0.30\,\text{LifeExp}-0.95\,\text{Murder}: \]
low illiteracy goes with low murder rates. The second canonical correlation, 0.37, is much weaker. Its pair puts positive weight on both variables of each set,
\[ u_2\propto0.60\,\text{Illiteracy}+0.80\,\text{HSGrad},\qquad v_2\propto0.75\,\text{LifeExp}+0.66\,\text{Murder}: \]
what is left once the first pair is accounted for: a weak tendency for states with both more illiteracy and more high-school graduates to have both longer lives and more murders. With two variables per set, \(u_2\) is the only education index left that is uncorrelated with \(u_1\), so it plays the role of a residual: a second education index, not a regression residual, but the direction in the education variables that \(u_1\) leaves out. The same holds for \(v_2\) and health and safety.
fig_cca <- function() {
U <- Zst[, c("Illiteracy", "HSGrad")] %*% cc_states$xcoef
V <- Zst[, c("LifeExp", "Murder")] %*% cc_states$ycoef
U <- U * sqrt(nrow(U) - 1); V <- V * sqrt(nrow(V) - 1) # canonical variates with variance 1
s1 <- sign(cc_states$xcoef["HSGrad", 1]) # first pair: high = more educated
s2 <- sign(cc_states$xcoef["HSGrad", 2]) # second pair: positive weights
d <- tibble(abb = state.abb, u1 = s1 * U[, 1], v1 = s1 * V[, 1], u2 = s2 * U[, 2], v2 = s2 * V[, 2])
p1 <- ggplot(d, aes(u1, v1)) + geom_point(colour = col_a1, size = 2) +
geom_text_repel(aes(label = abb), size = 2.8, colour = "grey35", seed = 5, max.overlaps = 15) +
labs(title = sprintf("First pair: correlation %.2f", cc_states$cor[1]),
x = expression(italic(u)[1]*": education"), y = expression(italic(v)[1]*": health and safety"))
p2 <- ggplot(d, aes(u2, v2)) + geom_point(colour = col_a2, size = 2) +
geom_text_repel(aes(label = abb), size = 2.8, colour = "grey35", seed = 5, max.overlaps = 15) +
labs(title = sprintf("Second pair: correlation %.2f", cc_states$cor[2]),
x = expression(italic(u)[2]*": education, second index"),
y = expression(italic(v)[2]*": health and safety, second index"))
p1 + p2
}
# draw the figure
fig_cca()
Most states lie close to the line in the left panel. Nevada stands out at the bottom right: well educated, but with a high murder rate.
Zs <- scale(X)
cc <- cancor(Zs[, c("Illiteracy", "HS Grad")], Zs[, c("Life Exp", "Murder")])
cc$cor # canonical correlations
## [1] 0.7102436 0.3651655
R <- cor(X[, c("Illiteracy", "HS Grad", "Life Exp", "Murder")])
E1 <- solve(R[1:2, 1:2]) %*% R[1:2, 3:4] %*% solve(R[3:4, 3:4]) %*% R[3:4, 1:2]
sqrt(eigen(E1)$values) # the same, from the eigenvalues of E1
## [1] 0.7102436 0.3651655CCA is used less than the other methods in this course because its variates are often hard to interpret (Everitt and Hothorn’s examples, head sizes of brothers and depression in Los Angeles, show both a clear and a less clear case). It is the natural generalisation of the multiple correlation of regression to several outcomes.
Check your understanding
- Canonical correlation analysis finds
- the directions of largest variance in one set of variables
- linear combinations of two sets of variables that are as highly correlated as possible
- clusters of observations
- the regression of each variable on all others
- With 2 variables in one set and 4 in the other, the number of canonical correlations is
- 2
- 4
- 6
- 8
Answers
1 b. 2 a.4.10 Summary
- Splitting \(A=\Gamma D\) gives the shocks units: \(D\) says how important each factor is, \(\Gamma\) how the variables combine them. The split needs a normalisation: ones on the diagonal (Cholesky, the regressor and the residual; symmetric root, each roommate’s own GPA), outside facts (structural), or columns of length one (PCA, so that the factor variances add up to the total variance).
- Every \(A\) with \(AA'=S\) fits the data; the squared length of each arrow (column) is the variance its shock carries. PCA turns the arrows until the first one is longest, then the second, and so on; the arrows come out perpendicular, so \(A=\Gamma D\) is a stretch followed by a rotation. The scores \(\mathbf f_t=\Gamma'\mathbf x_t\) undo the rotation, the standardised scores undo the stretch too.
- Equivalently, the first principal component is the unit vector \(\gamma_1\) whose scores \(\gamma_1'\mathbf x_t\) have the largest variance; it is also the line closest to the cloud in the perpendicular sense.
- The components are the eigenvectors of \(S\), the directions that \(S\) only stretches, and their variances the eigenvalues. In the eigenbasis the covariance matrix is diagonal, \(Q'SQ=\Lambda\), and \(S=Q\Lambda Q'\) is the PCA split with \(\Gamma=Q\), \(D^2=\Lambda\): the scores are uncorrelated, and the eigenvalues add up to the total variance.
- PCA depends on the units: rescaling one variable swings the components towards it. With different units, use the correlation matrix (standardised variables).
- How many components is a judgement: share of variance, eigenvalues above average (Kaiser, Jolliffe), the scree plot.
- The biplot draws \(\mathbf x_t=\Gamma\mathbf f_t\): scores as points, rows of \(\Gamma\) (the weights) as arrows; with standardised scores, the arrows are the rows of \(A=\Gamma D\) (the loadings). Short arrows mark variables that the first two components represent poorly.
- The first \(m\) components give the best \(m\)-dimensional reconstruction; observations that it misses are the unusual combinations of Chapter 2.
- PCA is a convenient rotation, not a discovery of the true forces: use it to describe and compress, and label components with care. Canonical correlation extends the idea to two sets of variables.
PCA keeps the directions in which the data vary most, and drops the rest.
4.10.1 Further reading
- Everitt and Hothorn (2011), An Introduction to Applied Multivariate Analysis with R, Chapter 3 (principal components analysis, Sections 3.1 to 3.12; canonical correlation analysis, Section 3.13).
- 3Blue1Brown, Essence of Linear Algebra, chapters 9 (dot products and projections), 13 (change of basis) and 14 (eigenvectors and eigenvalues).