library(tidyverse) # should've already install.packages("tidyverse")
library(ggplot2movies) # the films; might need to install.packages("ggplot2movies")
library(randomForest) # might need to install.packages("randomForest")
library(xgboost) # version 3 or later; if xgboost(x = ...) fails, install.packages("xgboost") again
library(mgcv) # used only in the optional items; ships with R
theme_set(theme_minimal())
options(pillar.sigfig = 4) # tables print four significant digits
mse <- function(y, pred) mean((y - pred)^2)
se_loss <- function(loss) sd(loss) / sqrt(length(loss)) # standard error of a mean of lossesWeek 8 seminar (complete)
Before the seminar
The lecture proved the variance of an average of correlated variables; exercise 1 is that proof again, with the slides closed. It derived boosting as approximate gradient descent; exercise 2 takes one boosting step by hand. Do both on paper before the seminar. You may use, without proof: \(\mathrm{Var}\big(\sum_b V_b\big) = \sum_b\sum_{b'}\mathrm{Cov}(V_b, V_{b'})\), and \(\mathrm{Cov}(V, V) = \mathrm{Var}(V)\).
Each exercise has hints, collapsed below it. Do not open a hint unless you have been stuck for at least a few minutes, and open them in order. Solutions are shown in the seminar if you ask.
Exercise 1 (correlated-average variance, with the slides closed). \(V_1, \ldots, V_B\) are random variables, each with variance \(\tau^2 > 0\), and every pair has correlation \(\rho\).
Show that \(\mathrm{Var}\big(\frac1B\sum_{b=1}^B V_b\big) = \rho\tau^2 + (1 - \rho)\tau^2/B\).
What is left as \(B \to \infty\)? What does the formula give when \(\rho = 1\), and when \(\rho = 0\)?
In a bagged ensemble or a random forest, \(V_b\) is the \(b\)th tree’s prediction at one input \(x\), and the randomness is the draw of the training data and of the resampling. Which term can more trees shrink, and which term does a random forest try to shrink instead?
- Write the variance of the sum as a double sum of covariances. How many terms have \(b = b'\), and how many have \(b \ne b'\)? What is each one?
- The covariance of two variables with correlation \(\rho\) and variances \(\tau^2\) is \(\rho\tau^2\). Divide the variance of the sum by \(B^2\), then write \(\frac{B(B-1)}{B^2} = 1 - \frac1B\) and regroup.
\(\mathrm{Var}\big(\sum_b V_b\big) = \sum_b\sum_{b'}\mathrm{Cov}(V_b, V_{b'})\). The \(B\) terms with \(b = b'\) are variances, \(\tau^2\) each; the \(B(B - 1)\) terms with \(b \ne b'\) are covariances, \(\rho\tau^2\) each (correlation times the two standard deviations). So \[ \mathrm{Var}\Big(\frac1B\sum_b V_b\Big) = \frac{1}{B^2}\Big(B\tau^2 + B(B - 1)\rho\tau^2\Big) = \frac{\tau^2}{B} + \Big(1 - \frac1B\Big)\rho\tau^2 = \rho\tau^2 + \frac{(1 - \rho)\tau^2}{B}. \qquad \blacksquare \]
As \(B \to \infty\) the second term vanishes and \(\rho\tau^2\) is left. With \(\rho = 1\) the average has variance \(\tau^2\), as if there were one variable: copies do not help. With \(\rho = 0\) it is \(\tau^2/B\), the familiar variance of a mean of uncorrelated variables.
More trees shrink only \((1 - \rho)\tau^2/B\); with hundreds of trees it is already small. A random forest tries each split on a random subset of the inputs, so that the trees differ more and \(\rho\) is smaller, which shrinks \(\rho\tau^2\) (it can raise \(\tau^2\) a little: each tree is a little worse).
Common errors: counting \(B^2\) covariances of \(\rho\tau^2\) (the \(B\) diagonal terms are variances); dividing by \(B\) instead of \(B^2\); answering (c) with “more trees” for both terms.
Exercise 2 (one boosting step by hand). The five Star Wars films in the lecture’s data, with their year and average IMDb rating (in the data, which end in 2005):
| Film | Year | Rating |
|---|---|---|
| Star Wars | 1977 | 8.8 |
| The Empire Strikes Back | 1980 | 8.8 |
| Return of the Jedi | 1983 | 8.1 |
| The Phantom Menace | 1999 | 6.4 |
| Attack of the Clones | 2002 | 7.0 |
The training loss of fitted values \(\mathbf f = (f_1, \ldots, f_5)\) is \(L(\mathbf f) = \sum_i \frac12(y_i - f_i)^2\).
Start from \(f_i = \bar y\) for every film. Compute \(\bar y\) and the negative gradient of \(L\) at this \(\mathbf f\).
Fit a tree with one split on year to the negative gradient: for each of the four cutoffs halfway between consecutive years, compute the residual sum of squares of the two leaves, each predicting its mean. Which cutoff wins, and what does each leaf predict?
Take a step of size \(\gamma = 0.5\) along that tree. Give the new fitted values, and the training loss before and after the step.
- The derivative of \(\frac12(y_i - f_i)^2\) with respect to \(f_i\).
(b), (c) A leaf predicts the mean of the residuals in it. The step is \(f_i \leftarrow f_i + \gamma\,t(x_i)\), with \(t\) the tree.
\(\bar y = 39.1/5 = 7.82\). The negative gradient is the residual vector \(\mathbf y - \mathbf f = (0.98, 0.98, 0.28, -1.42, -0.82)\).
The cutoffs and the residual sum of squares of the two leaves:
| Cutoff | Left leaf (mean) | Right leaf (mean) | RSS |
|---|---|---|---|
| 1978.5 | 0.98 | 0.98, 0.28, −1.42, −0.82 (\(-0.245\)) | 3.49 |
| 1981.5 | 0.98, 0.98 (\(0.98\)) | 0.28, −1.42, −0.82 (\(-0.653\)) | 1.49 |
| 1991 | 0.98, 0.98, 0.28 (\(0.747\)) | −1.42, −0.82 (\(-1.12\)) | 0.51 |
| 2000.5 | 0.98, 0.98, 0.28, −1.42 (\(0.205\)) | −0.82 | 3.85 |
The cutoff at 1991 wins: the tree predicts \(0.747\) for the films before 1991 and \(-1.12\) for the two after.
- \(f_i \leftarrow 7.82 + 0.5 \times 0.747 = 8.19\) for the first three films and \(7.82 - 0.5 \times 1.12 = 7.26\) for the last two. The loss before the step is \(\frac12(0.98^2 + 0.98^2 + 0.28^2 + 1.42^2 + 0.82^2) = 2.344\); after it, the residuals are \(0.61, 0.61, -0.09, -0.86, -0.26\) and the loss is \(0.776\).
Common errors: fitting the tree to the ratings instead of the residuals (it then predicts the leaf means of the ratings, and the step adds them to \(\bar y\)); forgetting \(\gamma\); writing the gradient without its sign, which steps uphill.
Problems
Both problems use two inequalities. Markov’s inequality: if \(W \ge 0\) and \(a > 0\), then \(P(W \ge a) \le \mathbb E[W]/a\). Hoeffding’s inequality (Hoeffding 1963): if \(Z_1, \ldots, Z_m\) are independent with \(0 \le Z_i \le 1\) and \(\bar Z\) is their mean, then for every \(t > 0\), \[ P\big(|\bar Z - \mathbb E\bar Z| \ge t\big) \le 2e^{-2mt^2}. \]
Problem 1 (how far a score can be from the risk). A classifier predicts a track’s playlist genre, one of six, from its audio features (data note). It was fitted on training tracks and is now fixed; its risk \(R\) is its error rate on new tracks. On \(m = 2000\) tuning tracks, drawn independently of each other and of the training tracks, it errs on 1,062, so its score is \(\hat R = 0.531\), the mean of \(m\) losses \(\ell_i \in \{0, 1\}\) with mean \(R\). Write \(D = \hat R - R\). We want an interval \(\hat R \pm t\) that contains \(R\) with probability at least \(1 - \delta\), for \(\delta = 0.001\): a \(t\) with \(P(|D| \ge t) \le \delta\).
Show that \(\mathrm{Var}(\ell_i) \le \frac14\), so that \(\mathrm{Var}(D) \le \frac{1}{4m}\).
Apply Markov’s inequality to \(W = |D|\), using \(\mathbb E|D| \le \sqrt{\mathbb E[D^2]}\), and find \(t\).
Apply it to \(W = D^2\) instead (this is Chebyshev’s inequality), and find \(t\).
Find \(t\) from Hoeffding’s inequality.
Compute the three intervals. Guessing a genre at random errs with probability \(\frac56\): which interval rules that out for this classifier? How does each \(t\) grow as \(\delta\) shrinks?
Optional. Hoeffding’s lemma says that if \(0 \le Z \le 1\) with mean \(\mu\), then \(\mathbb E\big[e^{\lambda(Z - \mu)}\big] \le e^{\lambda^2/8}\) for every \(\lambda\). Apply Markov’s inequality to \(W = e^{\lambda D}\) with \(\lambda > 0\), and use independence and the lemma to show that \(P(D \ge t) \le e^{-\lambda t + \lambda^2/(8m)}\). Then choose \(\lambda\) to get \(P(D \ge t) \le e^{-2mt^2}\).
- A loss of 0 or 1 equals its square. The \(\ell_i\) are independent, and \(D\) is their mean minus a constant.
- to (d) Each inequality bounds \(P(|D| \ge t)\) by an expression in \(t\): set it equal to \(\delta\) and solve for \(t\). In (c), \(|D| \ge t\) exactly when \(D^2 \ge t^2\).
- \(D \ge t\) exactly when \(e^{\lambda D} \ge e^{\lambda t}\). Write \(e^{\lambda D}\) as a product of \(m\) independent factors, one for each tuning track.
A loss of 0 or 1 equals its square, so \(\mathbb E[\ell_i^2] = R\) and \(\mathrm{Var}(\ell_i) = R - R^2 = R(1 - R)\), which is at most \(\frac14\), its value at \(R = \frac12\). (For any loss between 0 and 1, \(\ell_i^2 \le \ell_i\) gives the same bound.) \(D = \frac1m\sum_i (\ell_i - R)\) is a mean of \(m\) independent terms, so \(\mathrm{Var}(D) = \mathrm{Var}(\ell_i)/m \le \frac{1}{4m}\).
\(\mathbb E[D] = 0\), so \(\mathbb E[D^2] = \mathrm{Var}(D) \le \frac{1}{4m}\) and \(\mathbb E|D| \le \frac{1}{2\sqrt m}\). Markov’s inequality gives \(P(|D| \ge t) \le \mathbb E|D|/t \le \frac{1}{2t\sqrt m}\), which equals \(\delta\) at \[ t = \frac{1}{2\delta\sqrt m} = \frac{1}{2 \times 0.001 \times \sqrt{2000}} = 11.2. \]
\(P(|D| \ge t) = P(D^2 \ge t^2) \le \mathbb E[D^2]/t^2 \le \frac{1}{4mt^2}\), which equals \(\delta\) at \(t = \frac{1}{2\sqrt{\delta m}} = \frac{1}{2\sqrt 2} = 0.354\).
The \(\ell_i\) are independent and between 0 and 1, so \(P(|D| \ge t) \le 2e^{-2mt^2}\), which equals \(\delta\) at \(t = \sqrt{\log(2/\delta)/(2m)} = \sqrt{\log(2000)/4000} = 0.044\).
Markov’s interval, \(0.531 \pm 11.2\), says less than we knew before: \(R\) is between 0 and 1 anyway. Chebyshev’s is \([0.177, 0.885]\), which contains \(\frac56 = 0.833\), so it cannot tell this classifier from guessing. Hoeffding’s is \([0.487, 0.575]\), which rules guessing out. As \(\delta\) shrinks, \(t\) grows like \(1/\delta\) for Markov, \(1/\sqrt\delta\) for Chebyshev and \(\sqrt{\log(2/\delta)}\) for Hoeffding. All three shrink like \(1/\sqrt m\); what differs is the price of a small \(\delta\). Each is Markov’s inequality applied to a different function of \(D\): \(|D|\), \(D^2\) and, for Hoeffding, \(e^{\lambda D}\) (part (f)). Each uses more about \(D\): one moment, then two, then, through the bounds on the losses, all of them. At \(\delta = 0.05\) the three are 0.22, 0.050 and 0.030, and Chebyshev’s would be usable; problem 2 shows why a search needs a small \(\delta\). Hoeffding’s interval is the best of the three, not the best possible: it uses only independence and the bounds on the losses, and a normal approximation gives about \(\pm 0.037\) here.
By Markov’s inequality, \(P(D \ge t) = P(e^{\lambda D} \ge e^{\lambda t}) \le e^{-\lambda t}\,\mathbb E[e^{\lambda D}]\). Since \(e^{\lambda D} = \prod_i e^{(\lambda/m)(\ell_i - R)}\) and the \(\ell_i\) are independent, the lemma with \(\lambda/m\) in place of \(\lambda\) gives \[ \mathbb E[e^{\lambda D}] = \prod_{i=1}^m \mathbb E\big[e^{(\lambda/m)(\ell_i - R)}\big] \le e^{m\lambda^2/(8m^2)} = e^{\lambda^2/(8m)}. \] So \(P(D \ge t) \le e^{-\lambda t + \lambda^2/(8m)}\). The exponent is smallest at \(\lambda = 4mt\), where it equals \(-4mt^2 + 2mt^2 = -2mt^2\). The same argument for the losses \(1 - \ell_i\) bounds \(P(D \le -t)\) by \(e^{-2mt^2}\), and the two together give Hoeffding’s inequality. \(\blacksquare\)
Common errors: in (b), forgetting that \(\mathbb E[D^2]\) is the variance only because \(\mathbb E[D] = 0\); in (c), \(t = \frac{1}{4m\delta}\) (the square root forgotten), or the plug-in variance \(\hat R(1 - \hat R)\) in place of \(\frac14\), which is close here but no longer a guarantee; in (d), \(\log(1/\delta)\) in place of \(\log(2/\delta)\) (the bound covers both tails).
Problem 2 (the size of a search). A model’s risk is its expected loss on a new unit, \(R = \mathbb E[\ell]\), for a loss with \(0 \le \ell \le 1\) (for example, the 0–1 loss of a classifier). Before the tuning data are seen, \(K\) candidate models are fixed, fitted on the training data, with risks \(R_1, \ldots, R_K\); treat the fitted models as fixed, so that everything below is conditional on the training data. On \(m\) tuning units, drawn independently of each other and of the training data, candidate \(k\) scores \(\hat R_k\), the mean of its \(m\) losses.
Find \(t_K\) such that, with probability at least \(1 - \delta\), \(|\hat R_k - R_k| < t_K\) for every \(k\) at once. Did you need the \(K\) scores to be independent of each other?
Let \(\hat k\) be the candidate with the lowest tuning score and \(k^\star\) the candidate with the lowest risk. On the event of (a), show that \(R_{\hat k} < \hat R_{\hat k} + t_K\) and \(R_{\hat k} < R_{k^\star} + 2t_K\).
Take \(m = 2000\) and \(\delta = 0.05\). Compute \(t_K\) for \(K = 1\), \(10\), \(100\) and \(1{,}000{,}000\). How many candidates double \(t_1\)? How many tuning units halve \(t_K\)? What would Chebyshev’s inequality give in place of Hoeffding’s, for \(K = 100\)? What does this say about searching a larger grid?
The argument needs the \(K\) candidates to be fixed before any tuning score is seen. Give an example of a search that breaks this, and one that chooses adaptively but does not.
- Use the union bound: for any events \(A_1, \ldots, A_K\), \(P(A_1 \cup \cdots \cup A_K) \le \sum_k P(A_k)\). Take \(A_k\) to be the event \(|\hat R_k - R_k| \ge t\), bound each \(P(A_k)\) with Hoeffding’s inequality, and set the sum equal to \(\delta\).
- \(\hat k\) has the lowest score, so \(\hat R_{\hat k} \le \hat R_{k^\star}\). Use the event of (a) once for \(\hat k\) and once for \(k^\star\).
- Chebyshev’s inequality bounds each \(P(A_k)\) by \(\mathrm{Var}(\hat R_k)/t^2 \le \frac{1}{4mt^2}\).
Given the fitted models, each candidate’s \(m\) tuning losses are independent, between 0 and 1, with mean \(R_k\), so Hoeffding’s inequality gives \(P(|\hat R_k - R_k| \ge t) \le 2e^{-2mt^2}\) for each \(k\). By the union bound, \[ P\big(\text{some } k \text{ has } |\hat R_k - R_k| \ge t\big) \le \sum_{k=1}^K P\big(|\hat R_k - R_k| \ge t\big) \le 2Ke^{-2mt^2}, \] which equals \(\delta\) at \[ t_K = \sqrt{\frac{\log(2K/\delta)}{2m}}. \] For \(K = 1\) this is problem 1’s \(t\). The union bound needs no independence between the events: the \(K\) scores use the same tuning units and are usually strongly dependent, and the bound still holds.
On the event of (a), \(R_{\hat k} < \hat R_{\hat k} + t_K\): the winner’s risk is less than its reported score plus \(t_K\), so the reported score may understate its risk by up to \(t_K\). Then \(\hat R_{\hat k} \le \hat R_{k^\star}\), because \(\hat k\) has the lowest score, and \(\hat R_{k^\star} < R_{k^\star} + t_K\). Together, \(R_{\hat k} < R_{k^\star} + 2t_K\). \(\blacksquare\)
\(t_K = \sqrt{\log(40K)/4000}\): 0.030 for \(K = 1\), 0.039 for \(K = 10\), 0.046 for \(K = 100\) and 0.066 for \(K = 1{,}000{,}000\). Doubling \(t_1\) needs \(\log(40K) = 4\log 40\), that is, \(K = 40^3 = 64{,}000\) candidates. Halving \(t_K\) needs four times the tuning units, whatever \(K\) is. Chebyshev’s inequality bounds each \(P(|\hat R_k - R_k| \ge t)\) by \(\frac{1}{4mt^2}\), so the union bound needs \(\frac{K}{4mt^2} = \delta\), that is, \(t = \sqrt{K/(4m\delta)}\): 0.50 for \(K = 100\), against Hoeffding’s 0.046. Asking each candidate’s guarantee to hold with probability \(1 - \delta/K\) multiplies Chebyshev’s \(t\) by \(\sqrt K\), but adds only \(\log K\) under Hoeffding’s square root: the price of a small \(\delta\), from problem 1, is what decides the cost of a search. With Hoeffding’s inequality the grid’s size enters the bound only through \(\sqrt{\log K}\): a much larger grid adds little to the bound, while it can only lower \(R_{k^\star}\), the best risk among the candidates. So with a large tuning set a wide search is a good trade, and the tuning set’s size counts for far more than the grid’s. The bound limits the optimism of the reported minimum; it does not say how large the optimism is. Searching more candidates can increase it. When the candidates are equally good, adding one never lowers it, since the chosen one’s risk is the same whichever is chosen and the minimum of more scores can only be lower. In general its size depends on the candidates’ risks and on how their scores are correlated, and adding one much better candidate can even remove it. Either way the reported minimum is biased low, so the error of the chosen model should be estimated on data that the search never used. These numbers are for a loss between 0 and 1: squared errors on film ratings, from 1 to 10, can reach 81, so the same bound for them is at least 81 times larger.
A search that creates candidates after seeing tuning scores: new values of a knob around the current best, or new models tried until one scores well. Such candidates were not on a list fixed in advance, and the union bound over a fixed list of \(K\) does not cover them; reusing the tuning set after changing a model in response to its tuning errors is the same thing. A rule that only chooses which of a fixed list of \(K\) candidates to look at, adaptively or not (one knob at a time, say, within a grid fixed in advance), still picks one of the \(K\), so the bound for \(K\) still covers its choice.
Common errors: requiring independent scores in (a); in (b), using \(R_{\hat k} \le R_{k^\star}\) (false: \(k^\star\) has the lowest risk); reading (c) as “the optimism of a search grows like \(\sqrt{\log K}\)” (the bound limits the optimism; it does not measure it).
Coding
The lecture’s task: predict a film’s average IMDb rating from its year, length and seven genre indicators, squared loss (data note). The same split as the lecture: 5,000 training, 2,000 tuning and 3,000 test films, one seed. The tuning films choose the knobs; the test films are opened once, at the end.
mv <- movies |>
filter(length <= 200, length > 10, year > 1918, votes >= 20) |>
select(title, rating, year, length, Action, Animation, Comedy, Drama, Documentary, Romance, Short)
set.seed(310) # change this number: a different split, and different numbers below
mv_id <- sample(nrow(mv), 10000)
mv_train <- mv[mv_id[1:5000], ]
mv_tune <- mv[mv_id[5001:7000], ]
mv_test <- mv[mv_id[7001:10000], ]
mse(mv_tune$rating, mean(mv_train$rating)) # the training mean, scored on the tuning films[1] 2.003116
1. A random forest, two knobs
rf_fit(mtry, nodesize) fits a forest of 300 trees on the training films. Its two knobs: mtry, the number of inputs tried at each split (randomForest’s default for 9 inputs is 3), and nodesize, the size below which a node is not split (default 5). rf_score() returns a forest’s MSE on the tuning films.
rf_fit <- function(mtry, nodesize) {
randomForest(rating ~ year + length + Action + Animation + Comedy + Drama + Documentary + Romance + Short,
data = mv_train, ntree = 300, mtry = mtry, nodesize = nodesize)
}
rf_score <- function(mtry, nodesize) mse(mv_tune$rating, predict(rf_fit(mtry, nodesize), mv_tune))Question 1. Fit the forest with the default knobs. Compute its MSE on the training films, out of bag (predict(fit) with no new data predicts each training film from the trees that did not have it in their bootstrap sample), and on the tuning films. Which two agree, and why is the third lower? Why do we not tune the number of trees?
fit_default <- rf_fit(mtry = 3, nodesize = 5)
# c(training = mse(mv_train$rating, ____),
# out_of_bag = mse(mv_train$rating, ____),
# tuning = mse(mv_tune$rating, ____))fit_default <- rf_fit(mtry = 3, nodesize = 5)
q1 <- c(training = mse(mv_train$rating, predict(fit_default, mv_train)),
out_of_bag = mse(mv_train$rating, predict(fit_default)),
tuning = mse(mv_tune$rating, predict(fit_default, mv_tune)))
round(q1, 3) training out_of_bag tuning
1.192 1.504 1.489
The out-of-bag MSE (1.50) and the tuning MSE (1.49) agree; the training MSE (1.19) is lower, because each training film is predicted partly by the trees that were fitted on it. Out of bag, each film is predicted only by the trees that never saw it, so the out-of-bag error is an estimate on held-out data that costs no extra films. The number of trees is not tuned because more trees only shrink the \((1 - \rho)\tau^2/B\) term of the variance of an average: past a few hundred, more trees cost time and change little.
Common errors: predict(fit_default, mv_train) for the out-of-bag line, which is the training error again.
Question 2. Tune one knob at a time, leaving the other at its default: mtry in 1, 2, 3, 5 and 9 with nodesize = 5; then nodesize in 5, 50 and 200 with mtry = 3. Which value of each wins? (Eight forests, the default twice, about 20 seconds.)
mtrys <- c(1, 2, 3, 5, 9)
nodesizes <- c(5, 50, 200)
# mse_mtry <- sapply(mtrys, function(m) ____)
# mse_node <- sapply(nodesizes, function(s) ____)
# rbind(mtry = mtrys, tune_mse = round(mse_mtry, 3))
# rbind(nodesize = nodesizes, tune_mse = round(mse_node, 3))mtrys <- c(1, 2, 3, 5, 9)
nodesizes <- c(5, 50, 200)
mse_mtry <- sapply(mtrys, function(m) rf_score(m, 5))
mse_node <- sapply(nodesizes, function(s) rf_score(3, s))
rbind(mtry = mtrys, tune_mse = round(mse_mtry, 3)) [,1] [,2] [,3] [,4] [,5]
mtry 1.000 2.000 3.000 5.000 9.00
tune_mse 1.698 1.511 1.491 1.559 1.71
rbind(nodesize = nodesizes, tune_mse = round(mse_node, 3)) [,1] [,2] [,3]
nodesize 5.000 50.00 200.000
tune_mse 1.487 1.48 1.489
mtry = 3 wins, and both ends are worse: with 1 input tried the trees are weak, and with all 9 (mtry = 9 is bagging) they are alike. nodesize = 50 wins, and the three values are within 0.009 of each other: small beside the standard error of a tuning MSE (about 0.05), though larger than the change between two forests with the same knobs (about 0.003; each forest draws its own bootstrap samples). With mtry = 3 this knob matters little.
Common errors: rf_score(5, m), which swaps the knobs; tuning nodesize at the winning mtry instead of the default (question 6 does that, for boosting).
Checkpoint (run it; if it stops, fix question 2 before going on): the default’s two scores should be close.
stopifnot(abs(mse_mtry[mtrys == 3] - mse_node[nodesizes == 5]) < 0.03)Question 3. The chunk below fits all 15 forests of the grid (about 40 seconds). Does the best nodesize depend on mtry? Did searching both knobs together find a better forest than question 2?
rf_grid <- expand_grid(mtry = c(1, 2, 3, 5, 9), nodesize = c(5, 50, 200)) |>
mutate(tune_mse = map2_dbl(mtry, nodesize, rf_score))
rf_grid |> mutate(tune_mse = round(tune_mse, 3)) |>
pivot_wider(names_from = nodesize, values_from = tune_mse, names_prefix = "nodesize ")# A tibble: 5 x 4
mtry `nodesize 5` `nodesize 50` `nodesize 200`
<dbl> <dbl> <dbl> <dbl>
1 1 1.695 1.68 1.694
2 2 1.513 1.511 1.527
3 3 1.489 1.481 1.491
4 5 1.565 1.491 1.488
5 9 1.717 1.505 1.494
rf_wide <- rf_grid |> pivot_wider(names_from = nodesize, values_from = tune_mse)
rf_best <- rf_grid |> slice_min(tune_mse)Yes. With mtry = 9 (bagging) the larger nodes are much better (1.72, 1.50, 1.49 for nodes of 5, 50 and 200); with mtry = 3 the row is nearly flat. One reading, from the variance of an average of trees, \(\rho\tau^2 + (1 - \rho)\tau^2/B\): a small mtry lowers the correlation \(\rho\) between trees, and a large nodesize lowers each tree’s variance \(\tau^2\) (and raises its bias). When every tree tries all the inputs the trees are alike, so lowering each one’s variance helps; when each tries 3, averaging already removes much of it. The grid did not find a better forest than question 2: its best is mtry = 3, nodesize = 50 (1.481), the values question 2 chose one at a time, within 0.009 of the default. On these films a forest with its default knobs is already about as good as the grid can make it.
Common errors: reading a difference of 0.005 between two cells as a winner, when two forests with the same knobs differ by a few thousandths.
2. Boosted trees, three knobs
xgboost has three knobs that matter most here: the depth of each tree, the learning rate \(\gamma\), and the number of iterations. Its defaults are depth 6, rate 0.3 and 100 iterations. One fit of 800 iterations gives the predictions after any smaller number, so the chunk below makes 12 fits (4 depths, 3 rates) and scores each after 5, 10, 25, …, 800 iterations: 96 models in a table, models, with each one’s MSE on the tuning films. loss holds every model’s squared errors on the 2,000 tuning films, one column per model, in the order of the rows of models; col is that column. (About 5 seconds.)
X_train <- as.matrix(select(mv_train, -title, -rating))
X_tune <- as.matrix(select(mv_tune, -title, -rating))
X_test <- as.matrix(select(mv_test, -title, -rating))
boost_fit <- function(depth, rate) {
xgboost(x = X_train, y = mv_train$rating, nrounds = 800, max_depth = depth, learning_rate = rate, nthread = 1)
}
iters <- c(5, 10, 25, 50, 100, 200, 400, 800)
models <- expand_grid(depth = c(1, 2, 4, 6), rate = c(0.03, 0.1, 0.3), iters = iters) |>
mutate(col = row_number())
loss <- matrix(NA, nrow(mv_tune), nrow(models))
for (d in c(1, 2, 4, 6)) for (r in c(0.03, 0.1, 0.3)) {
fit <- boost_fit(d, r)
for (b in iters) {
j <- models |> filter(depth == d, rate == r, iters == b) |> pull(col)
loss[, j] <- (mv_tune$rating - predict(fit, X_tune, iteration_range = c(1, b)))^2
}
}
models$tune_mse <- colMeans(loss)Question 4. The chunk below scores the defaults on the tuning films and on the training films. Compare with the forest and with the training mean. What has happened?
models |> filter(depth == 6, rate == 0.3, iters == 100)# A tibble: 1 x 5
depth rate iters col tune_mse
<dbl> <dbl> <dbl> <int> <dbl>
1 6 0.3 100 93 1.683
fit_default_boost <- boost_fit(depth = 6, rate = 0.3)
mse(mv_train$rating, predict(fit_default_boost, X_train, iteration_range = c(1, 100))) # training MSE[1] 0.8182678
boost_default <- models |> filter(depth == 6, rate == 0.3, iters == 100)
boost_default_train <- mse(mv_train$rating, predict(fit_default_boost, X_train, iteration_range = c(1, 100)))The defaults score 1.68 on the tuning films, 0.19 worse than the default forest (1.49) and over a third of the way back to the training mean (2.00), while their training MSE is 0.82. A hundred steps of size 0.3 with trees of depth 6 fit the training films’ noise: the defaults overfit these data.
Common errors: comparing the default’s training MSE with the forest’s tuning MSE.
Question 5. Tune one knob at a time, from the defaults: the number of iterations with depth 6 and rate 0.3; the depth with rate 0.3 and 100 iterations; the rate with depth 6 and 100 iterations. Before scoring the model that takes all three winners together, predict: should it be at least as good as each winner alone? Then score it.
# models |> filter(____) |> slice_min(tune_mse) # iterations alone
# models |> filter(____) |> slice_min(tune_mse) # depth alone
# models |> filter(____) |> slice_min(tune_mse) # rate alone
# models |> filter(depth == ____, rate == ____, iters == ____) # the three winners togetheralone_iters <- models |> filter(depth == 6, rate == 0.3) |> slice_min(tune_mse)
alone_depth <- models |> filter(rate == 0.3, iters == 100) |> slice_min(tune_mse)
alone_rate <- models |> filter(depth == 6, iters == 100) |> slice_min(tune_mse)
together <- models |> filter(depth == alone_depth$depth, rate == alone_rate$rate, iters == alone_iters$iters)
bind_rows(alone_iters, alone_depth, alone_rate, together)# A tibble: 4 x 5
depth rate iters col tune_mse
<dbl> <dbl> <dbl> <int> <dbl>
1 6 0.3 10 90 1.497
2 2 0.3 100 45 1.505
3 6 0.03 100 77 1.492
4 2 0.03 10 26 1.898
# Tuning MSE against the number of iterations, one line per learning rate.
models |> filter(depth %in% c(2, 6)) |>
ggplot(aes(iters, tune_mse, color = factor(rate))) +
geom_line() + geom_point() +
geom_hline(yintercept = mse(mv_tune$rating, mean(mv_train$rating)), linetype = "dashed") +
scale_x_log10() + scale_color_viridis_d(end = 0.85) +
facet_wrap(~ depth, labeller = label_both) +
labs(x = "iterations (log scale)", y = "tuning MSE", color = "learning rate")No. Each knob alone fixes the defaults’ overfitting: 10 iterations (1.497), depth 2 (1.505) or rate 0.03 (1.492). Together they score 1.898, worse than the defaults: 10 small steps with trees of depth 2 have hardly moved from the training mean. Each winner was the best answer to “how do we stop overfitting?” with the other two knobs at the defaults; once one knob has stopped it, the others should move the other way. The rate and the number of iterations trade off against each other, and the depth with both: in the figure, each learning rate reaches a similar minimum, later the smaller the rate, and the dashed line is the training mean.
Common errors: filtering on the knob being tuned (filter(iters == 100) when tuning the iterations); combining the three winning tuning MSEs instead of finding the model that has all three winning knobs.
Question 6. Tune the knobs in sequence instead: the number of iterations first (depth 6, rate 0.3), then the depth at the winning number of iterations, then the rate at the winning depth and number of iterations. Then search the whole grid. Compare the two models, and the number of fits each search needed.
# step1 <- models |> filter(____) |> slice_min(tune_mse) # iterations, at depth 6 and rate 0.3
# step2 <- models |> filter(rate == 0.3, iters == ____) |> slice_min(tune_mse)
# step3 <- models |> filter(depth == ____, iters == ____) |> slice_min(tune_mse)
# models |> slice_min(tune_mse) # the whole gridstep1 <- models |> filter(depth == 6, rate == 0.3) |> slice_min(tune_mse)
step2 <- models |> filter(rate == 0.3, iters == step1$iters) |> slice_min(tune_mse)
step3 <- models |> filter(depth == step2$depth, iters == step1$iters) |> slice_min(tune_mse)
boost_best <- models |> slice_min(tune_mse)
bind_rows(sequence = step3, grid = boost_best, .id = "search")# A tibble: 2 x 6
search depth rate iters col tune_mse
<chr> <dbl> <dbl> <dbl> <int> <dbl>
1 sequence 6 0.3 10 90 1.497
2 grid 4 0.1 100 61 1.490
d_seq <- loss[, step3$col] - loss[, boost_best$col]
c(difference = mean(d_seq), se = se_loss(d_seq)) difference se
0.007565859 0.010334038
In sequence: 10 iterations, depth 6, rate 0.3, scoring 1.497. The whole grid: depth 4, rate 0.1, 100 iterations, scoring 1.490. The difference is 0.008 with a standard error of 0.010 (paired: the two models are scored on the same films), so here the sequence came close to the full grid, with 6 fits (one for the iterations, since one fit gives every number of iterations, then 3 more depths and 2 more rates) against the grid’s 12. Each step builds on the choices already made, which question 5’s searches from the defaults did not; but a single pass can miss better combinations, and its result can depend on the order of the knobs. The sequence only looked among the 96 models fixed in advance, so an argument like problem 2’s, with \(K = 96\), covers its choice even though it chose adaptively.
Common errors: tuning the depth at 100 iterations in step 2 (the defaults again, as in question 5).
Question 7. The chunk below gives the best model at each depth. Boosted trees of depth 1 are an additive model: each tree splits on one input, so the sum is a sum of one-input functions. Compute the paired difference in tuning loss between the best depth-1 model and the grid’s best, with its standard error. What does it suggest about interactions between the inputs?
models |> group_by(depth) |> slice_min(tune_mse) |> ungroup()# A tibble: 4 x 5
depth rate iters col tune_mse
<dbl> <dbl> <dbl> <int> <dbl>
1 1 0.1 400 15 1.515
2 2 0.1 400 39 1.502
3 4 0.1 100 61 1.490
4 6 0.03 100 77 1.492
j_additive <- models |> filter(depth == 1) |> slice_min(tune_mse) |> pull(col)
j_best <- models |> slice_min(tune_mse) |> pull(col)
# d_add <- ____
# c(difference = ____, se = ____)j_additive <- models |> filter(depth == 1) |> slice_min(tune_mse) |> pull(col)
j_best <- models |> slice_min(tune_mse) |> pull(col)
d_add <- loss[, j_additive] - loss[, j_best]
c(difference = mean(d_add), se = se_loss(d_add))difference se
0.02522631 0.01406809
The best additive model is worse by 0.025, with a standard error of 0.014: about 1.8 standard errors. Allowing deeper trees helps a little. That is compatible with useful interactions (length and year, say), but does not establish them: the difference is under two standard errors, and it favors the grid’s best, which was chosen as the minimum of all 96 of these tuning scores, against 24 at depth 1. The gain is small beside the 0.51 that the grid’s best gains over the training mean.
Common errors: sd(d_add) without dividing by \(\sqrt{2000}\); comparing the two tuning MSEs without pairing (the two models are scored on the same films, so their losses are correlated, and the unpaired standard error is much larger).
3. The size of the search
Three searches over the same 96 boosting models: one model fixed in advance, the defaults (fixed); the 13 models that question 5’s one-knob-at-a-time searches looked at (one_knob); and all 96. On one split of the tuning films the effect is too small to see, so we repeat the searches on many random halves, all three on the same halves.
Question 8. Complete half_gap(cols, A): among the models in cols, find the one with the lowest MSE on the half A of the tuning films; return that MSE and the same model’s MSE on the other half. The chunk then draws 2,000 random halves, runs the three searches on each and averages. Which search’s best model looks best on the films that chose it? Which is best on the other films?
fixed <- models |> filter(depth == 6, rate == 0.3, iters == 100) |> pull(col)
one_knob <- models |> filter((depth == 6 & rate == 0.3) | (rate == 0.3 & iters == 100) | (depth == 6 & iters == 100)) |> pull(col)
all_models <- models$colhalf_gap <- function(cols, A) {
mse_A <- colMeans(loss[A, cols, drop = FALSE]) # each model's MSE on the half A
# w <- ____ # the model with the lowest MSE on A
# c(chosen_on = ____, other_half = ____)
}
halves <- replicate(2000, {
A <- sample(nrow(loss), nrow(loss) / 2) # one random half of the tuning films
rbind(fixed = half_gap(fixed, A), one_knob = half_gap(one_knob, A), all_models = half_gap(all_models, A))
})
q8 <- apply(halves, 1:2, mean) # average over the 2,000 halves
cbind(q8, gap = q8[, "other_half"] - q8[, "chosen_on"])half_gap <- function(cols, A) {
mse_A <- colMeans(loss[A, cols, drop = FALSE])
w <- which.min(mse_A)
c(chosen_on = mse_A[[w]], other_half = mean(loss[-A, cols[w]]))
}
halves <- replicate(2000, {
A <- sample(nrow(loss), nrow(loss) / 2)
rbind(fixed = half_gap(fixed, A), one_knob = half_gap(one_knob, A), all_models = half_gap(all_models, A))
})
q8 <- apply(halves, 1:2, mean)
q8 <- cbind(q8, gap = q8[, "other_half"] - q8[, "chosen_on"])
round(q8, 4) chosen_on other_half gap
fixed 1.6826 1.6827 0.0000
one_knob 1.4900 1.5001 0.0101
all_models 1.4832 1.5014 0.0182
# The 96-model gap minus the 13-model gap, with its Monte Carlo standard error (same halves for both):
gap_diff <- (halves["all_models", "other_half", ] - halves["all_models", "chosen_on", ]) -
(halves["one_knob", "other_half", ] - halves["one_knob", "chosen_on", ])
c(difference = mean(gap_diff), se = se_loss(gap_diff)) difference se
0.0080710136 0.0003200926
The largest search reports the lowest MSE on the films that chose its model (1.483, against 1.490 for 13 models), but on the other half its winner scores 1.501 against 1.500. The gap between the two, the optimism of the reported minimum, is about 0.000 for the fixed model, 0.010 for 13 models and 0.018 for 96, each with a Monte Carlo standard error of about 0.0025: here it grows with the size of the search (the difference between 96 and 13 models is 0.0081, with a Monte Carlo standard error of 0.0003, much smaller because both searches use the same halves). That need not happen for every set of candidates: adding one much better candidate can lower the optimism, since the chosen model’s risk changes too. The gap is small beside the standard error of one tuning MSE on 1,000 films (about 0.078), which is why one split cannot show it. The error to report is the one on films the search never used.
Common errors: returning the minimum over the other half (min(colMeans(loss[-A, cols]))), which chooses on the other half too; comparing the three chosen_on values alone and concluding that the largest search found the best model.
Checkpoint: one fixed model is not chosen by anything, so on average its two halves should agree.
stopifnot(abs(q8["fixed", "other_half"] - q8["fixed", "chosen_on"]) < 0.01)4. The test films, once
Question 9. Before running the chunk below, write down which two models you will score on the test films: the forest and the boosting model that won their grids on the tuning films. Then compute each one’s test MSE with its standard error, the training mean’s, and the paired difference between the forest and the boosting model, with its standard error. Compare each test MSE with the same model’s tuning MSE, the training mean’s too. What can you conclude from the differences?
rf_best <- rf_grid |> slice_min(tune_mse) # the forest that won its grid
boost_best <- models |> slice_min(tune_mse) # the boosting model that won its grid
fit_rf <- rf_fit(rf_best$mtry, rf_best$nodesize)
fit_boost <- boost_fit(boost_best$depth, boost_best$rate)
loss_test <- tibble(
forest = (mv_test$rating - predict(fit_rf, mv_test))^2,
boosting = (mv_test$rating - predict(fit_boost, X_test, iteration_range = c(1, boost_best$iters)))^2,
training_mean = (mv_test$rating - mean(mv_train$rating))^2)
# round(sapply(loss_test, function(l) c(mse = ____, se = ____)), 3)
# d_test <- ____
# c(difference = ____, se = ____)rf_best <- rf_grid |> slice_min(tune_mse)
boost_best <- models |> slice_min(tune_mse)
fit_rf <- rf_fit(rf_best$mtry, rf_best$nodesize)
fit_boost <- boost_fit(boost_best$depth, boost_best$rate)
loss_test <- tibble(
forest = (mv_test$rating - predict(fit_rf, mv_test))^2,
boosting = (mv_test$rating - predict(fit_boost, X_test, iteration_range = c(1, boost_best$iters)))^2,
training_mean = (mv_test$rating - mean(mv_train$rating))^2)
round(sapply(loss_test, function(l) c(mse = mean(l), se = se_loss(l))), 3) forest boosting training_mean
mse 1.563 1.569 2.061
se 0.045 0.047 0.053
d_test <- loss_test$forest - loss_test$boosting
c(difference = mean(d_test), se = se_loss(d_test)) difference se
-0.006217656 0.011909871
# The training mean's rise from tuning to test, with its standard error (two independent sets of films):
loss_tune_mean <- (mv_tune$rating - mean(mv_train$rating))^2
c(rise = mean(loss_test$training_mean) - mean(loss_tune_mean),
se = sqrt(se_loss(loss_test$training_mean)^2 + se_loss(loss_tune_mean)^2)) rise se
0.05757665 0.08348597
The forest scores 1.56 and the boosting model 1.57, each with a standard error near 0.05; the paired difference is -0.006 with a standard error of 0.012, so the test films do not separate them. The training mean, which was never tuned, scores 2.06 against 2.00 on the tuning films: a test score can be worse with no tuning at all. Its rise, 0.06, is within its standard error of about 0.08, so the two sets of films do not differ detectably. The models’ rises are of about the same size, and these results do not separate that variation from the optimism of choosing on the tuning films (question 8 measured the optimism for choices made on halves of 1,000 films, not on all 2,000).
Common errors: choosing the pair after seeing test scores; an unpaired standard error for the difference; reading every rise from tuning to test as the optimism of the search.
Optional, can be done at home: a truth with an interaction
The lecture’s simulated truth, \(y = x_1^2\cos(\pi x_2/2) + \varepsilon\) with \(x_1\) uniform on \([-1, 1]\) and \(x_2\) uniform on \([-4, 4]\), independent, but with less noise (standard deviation 0.2), so that the differences are large enough to see. Fit an additive model (gam(y ~ s(x1) + s(x2))) and boosted trees of depth 1, 2 and 4 (rate 0.1, 400 iterations) on 2,000 units, and score each on 2,000 fresh units. What is the lowest MSE any model could reach, and which models come near it? What does the additive model’s curve for \(x_2\) look like?
f_true <- function(x1, x2) x1^2 * cos(pi * x2 / 2)
sim <- function(n) tibble(x1 = runif(n, -1, 1), x2 = runif(n, -4, 4)) |> mutate(y = f_true(x1, x2) + rnorm(n, 0, 0.2))
sim_train <- sim(2000)
sim_fresh <- sim(2000)
# ...f_true <- function(x1, x2) x1^2 * cos(pi * x2 / 2)
sim <- function(n) tibble(x1 = runif(n, -1, 1), x2 = runif(n, -4, 4)) |> mutate(y = f_true(x1, x2) + rnorm(n, 0, 0.2))
sim_train <- sim(2000)
sim_fresh <- sim(2000)
fit_add <- gam(y ~ s(x1) + s(x2), data = sim_train)
boost_sim <- function(depth) {
fit <- xgboost(x = as.matrix(sim_train[, 1:2]), y = sim_train$y, nrounds = 400, max_depth = depth, learning_rate = 0.1, nthread = 1)
mse(sim_fresh$y, predict(fit, as.matrix(sim_fresh[, 1:2])))
}
sim_mse <- c(floor = 0.2^2, training_mean = mse(sim_fresh$y, mean(sim_train$y)),
additive = mse(sim_fresh$y, predict(fit_add, sim_fresh)),
depth_1 = boost_sim(1), depth_2 = boost_sim(2), depth_4 = boost_sim(4))
round(sim_mse, 3) floor training_mean additive depth_1 depth_2
0.040 0.141 0.087 0.089 0.067
depth_4
0.051
plot(fit_add, select = 2)The lowest MSE any model can reach is the noise variance, 0.04. The additive model (0.087) and boosted stumps (0.089) agree, well above it; trees of depth 4 (0.051) come close, since each tree can split on both inputs. The best any additive model can do here is \(0.04 + \mathrm{Var}(X_1^2)\,\mathbb E[\cos^2(\pi X_2/2)] = 0.04 + (\frac15 - \frac19)\frac12 \approx 0.084\), so nearly all of the additive fit’s gap above 0.04 is the cost of assuming additivity, not of estimating the curves. The additive model is not flat in \(x_2\): with independent inputs, the best additive approximation is \(\mathbb E[Y \mid x_1] + \mathbb E[Y \mid x_2] - \mathbb E[Y]\). \(\mathbb E[\cos(\pi X_2/2)] = 0\) over \([-4, 4]\), so the curve for \(x_1\) is flat, while \(\mathbb E[X_1^2] = \frac13\), so the curve for \(x_2\) is \(\frac13\cos(\pi x_2/2)\): the additive model keeps the part of the interaction that is a function of \(x_2\) alone.
Common errors: comparing the fits with the training mean instead of the noise variance; expecting the additive curve for \(x_2\) to be flat.
Optional, can be done at home: backfitting by hand
Fit the additive model \(\text{rating} = \beta_0 + f_1(\text{length}) + f_2(\text{year})\) on the training films by backfitting: start with both curves at zero and \(\hat\beta_0\) the mean rating; then, in turn, fit a smoothing spline (smooth.spline(x, r, df = 9)) of each input’s partial residual on that input, centered to mean zero, until the fitted values stop changing. How many iterations does it take? Compare its tuning MSE with gam(rating ~ s(length) + s(year)).
y <- mv_train$rating
b0 <- mean(y)
f_len <- rep(0, nrow(mv_train))
f_yr <- rep(0, nrow(mv_train))
for (t in 1:20) {
# r_len <- ____ # the partial residual for length
# s_len <- smooth.spline(mv_train$length, r_len, df = 9)
# f_len <- predict(s_len, mv_train$length)$y; f_len <- f_len - mean(f_len)
# ... the same for year
}y <- mv_train$rating
b0 <- mean(y)
f_len <- rep(0, nrow(mv_train))
f_yr <- rep(0, nrow(mv_train))
for (t in 1:20) {
fitted_before <- f_len + f_yr
s_len <- smooth.spline(mv_train$length, y - b0 - f_yr, df = 9)
shift_len <- mean(predict(s_len, mv_train$length)$y)
f_len <- predict(s_len, mv_train$length)$y - shift_len
s_yr <- smooth.spline(mv_train$year, y - b0 - f_len, df = 9)
shift_yr <- mean(predict(s_yr, mv_train$year)$y)
f_yr <- predict(s_yr, mv_train$year)$y - shift_yr
change <- max(abs(f_len + f_yr - fitted_before))
if (change < 1e-6) break
}
pred_bf <- b0 + predict(s_len, mv_tune$length)$y - shift_len + predict(s_yr, mv_tune$year)$y - shift_yr
c(iterations = t, backfitting = mse(mv_tune$rating, pred_bf),
mgcv = mse(mv_tune$rating, predict(gam(rating ~ s(length) + s(year), data = mv_train), mv_tune))) iterations backfitting mgcv
9.000000 1.663187 1.670827
The fitted values stop changing (by less than \(10^{-6}\)) after 9 iterations. The two tuning MSEs are close and not equal: smooth.spline with df = 9 fixes each curve’s flexibility, while mgcv chooses its own. The centering keeps \(\hat\beta_0\) the mean rating; without it the curves could trade a constant back and forth.
Common errors: the full residual y - b0 - f_len - f_yr in place of the partial residual, which leaves out the curve being refitted; forgetting to center.
References
- Hoeffding, W. (1963). Probability inequalities for sums of bounded random variables. Journal of the American Statistical Association, 58(301), 13–30. doi:10.1080/01621459.1963.10500830
- The films: data note. The Spotify tracks in problem 1: data note.