Week 7 seminar (complete)

Author

Joshua Loftus

library(tidyverse)       # should've already install.packages("tidyverse")
library(glmnet)          # might need to install.packages("glmnet")
library(mgcv)            # penalized splines; ships with R
theme_set(theme_minimal())
mse <- function(y, pred) mean((y - pred)^2)
se_loss <- function(y, pred) sd((y - pred)^2) / sqrt(length(y))   # standard error of an MSE
# k-NN regression with several standardized inputs, as in the lecture: squared distances by
# matrix algebra, then the mean outcome of the k nearest training rows.
knn_predict <- function(Xnew, Xtrain, ytrain, k) {
  d2 <- outer(rowSums(Xnew^2), rowSums(Xtrain^2), "+") - 2 * Xnew %*% t(Xtrain)
  apply(d2, 1, function(d) mean(ytrain[order(d)[1:k]]))
}

Before the seminar

The lecture stated the bias–variance decomposition in ridge form and left its proof to you (exercise 1). It proved the \(k\)-nearest-neighbor rate from a stated lemma; exercise 2 is that proof again, with the slides closed. Do both on paper before the seminar; the seminar’s problems are variations on them. You may use, without proof: linearity of expectation; that the variance of a sum of independent variables is the sum of their variances; that for a symmetric matrix \(\mathbf A\) the gradient of \(\beta^T\mathbf A\beta\) is \(2\mathbf A\beta\) and its Hessian is \(2\mathbf A\); and the tower property, \(\mathbb E[W] = \mathbb E\big[\mathbb E[W \mid V]\big]\). Throughout, assume that every expectation that appears exists.

WarningHints

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 (bias–variance decomposition, ridge form). \(\mathbf X\) is \(n \times p\) with orthonormal columns, \(\mathbf X^T\mathbf X = \mathbf I\) (so \(p \le n\); the lecture’s identity design is the case \(\mathbf X = \mathbf I\), \(n = p\)). The outcome is \(\mathbf y = \mathbf X\beta + \boldsymbol\varepsilon\) with \(\beta\) fixed and unknown and the \(\varepsilon_i\) independent, mean \(0\), variance \(\sigma^2 > 0\). Expectations are over \(\boldsymbol\varepsilon\), with \(\mathbf X\) fixed. The least-squares estimator solves the normal equations \(\mathbf X^T\mathbf X\beta = \mathbf X^T\mathbf y\), so here \(\hat\beta = \mathbf X^T\mathbf y\). For \(\lambda > 0\) the ridge estimator \(\hat\beta_\lambda\) minimizes \(\|\mathbf y - \mathbf X\beta\|^2 + \lambda\|\beta\|^2\).

  1. Show that \(\hat\beta\) is unbiased, \(\mathbb E[\hat\beta] = \beta\), and that each coordinate has variance \(\mathrm{Var}(\hat\beta_j) = \sigma^2\). Deduce \(\mathbb E\|\hat\beta - \beta\|^2 = p\sigma^2\).

  2. Derive the stationarity condition of the ridge objective, \((\mathbf X^T\mathbf X + \lambda\mathbf I)\beta = \mathbf X^T\mathbf y\), and show that in this design \(\hat\beta_\lambda = \hat\beta/(1 + \lambda)\).

  3. Compute the bias \(\mathbb E[\hat\beta_{\lambda,j}] - \beta_j\) and the variance \(\mathrm{Var}(\hat\beta_{\lambda,j})\) of each coordinate, and show \[ \mathrm{MSE}(\lambda) = \mathbb E\|\hat\beta_\lambda - \beta\|^2 = \sum_{j=1}^p \frac{\lambda^2\beta_j^2 + \sigma^2}{(1 + \lambda)^2}. \]

  4. Differentiate \(\mathrm{MSE}(\lambda)\) and show that its derivative at \(\lambda = 0\) is \(-2p\sigma^2\), whatever \(\beta\) is. Conclude that for every \(\beta\) there is a \(\lambda > 0\) with \(\mathrm{MSE}(\lambda) < \mathrm{MSE}(0) = p\sigma^2\).

  5. For \(\beta \ne \mathbf 0\), find the \(\lambda\) that minimizes \(\mathrm{MSE}(\lambda)\), in terms of \(\sigma^2\) and \(\|\beta\|^2/p\), and the minimum value. What happens when \(\beta = \mathbf 0\)? Why can this \(\lambda\) not be used in practice?

  1. \(\hat\beta = \mathbf X^T(\mathbf X\beta + \boldsymbol\varepsilon) = \beta + \mathbf X^T\boldsymbol\varepsilon\). What are the mean vector and the covariance matrix of \(\mathbf X^T\boldsymbol\varepsilon\)? The covariance matrix of \(\mathbf A\boldsymbol\varepsilon\) is \(\mathbf A\,\mathrm{Cov}(\boldsymbol\varepsilon)\,\mathbf A^T\).

(b), (c) With \(\mathbf X^T\mathbf X = \mathbf I\) the stationarity condition reads \((1 + \lambda)\beta = \mathbf X^T\mathbf y\). For a constant \(c\), the estimator \(c\hat\beta_j\) has bias \((c - 1)\beta_j\) and variance \(c^2\sigma^2\).

(d), (e) Write \(\mathrm{MSE}(\lambda) = (\lambda^2\|\beta\|^2 + p\sigma^2)/(1 + \lambda)^2\) and use the quotient rule; after cancelling a factor \((1 + \lambda)\) the numerator of the derivative is \(2\lambda\|\beta\|^2 - 2p\sigma^2\).

  1. \(\hat\beta = \mathbf X^T\mathbf y = \mathbf X^T\mathbf X\beta + \mathbf X^T\boldsymbol\varepsilon = \beta + \mathbf X^T\boldsymbol\varepsilon\). Since \(\mathbb E[\boldsymbol\varepsilon] = \mathbf 0\), \(\mathbb E[\hat\beta] = \beta\). The covariance matrix of \(\mathbf X^T\boldsymbol\varepsilon\) is \(\mathbf X^T\,\mathrm{Cov}(\boldsymbol\varepsilon)\,\mathbf X = \sigma^2\mathbf X^T\mathbf X = \sigma^2\mathbf I\) (independence with equal variances makes \(\mathrm{Cov}(\boldsymbol\varepsilon) = \sigma^2\mathbf I\)), so each coordinate has variance \(\sigma^2\) and the coordinates are uncorrelated. Then \(\mathbb E\|\hat\beta - \beta\|^2 = \sum_j \mathbb E(\hat\beta_j - \beta_j)^2 = \sum_j \mathrm{Var}(\hat\beta_j) = p\sigma^2\).

  2. \(\|\mathbf y - \mathbf X\beta\|^2 + \lambda\|\beta\|^2 = \mathbf y^T\mathbf y - 2\beta^T\mathbf X^T\mathbf y + \beta^T\mathbf X^T\mathbf X\beta + \lambda\beta^T\beta\), with gradient \(-2\mathbf X^T\mathbf y + 2\mathbf X^T\mathbf X\beta + 2\lambda\beta\). Setting it to zero gives \((\mathbf X^T\mathbf X + \lambda\mathbf I)\beta = \mathbf X^T\mathbf y\). With \(\mathbf X^T\mathbf X = \mathbf I\) this is \((1 + \lambda)\beta = \mathbf X^T\mathbf y = \hat\beta\), so \(\hat\beta_\lambda = \hat\beta/(1 + \lambda)\). (The Hessian \(2(1 + \lambda)\mathbf I\) is positive definite, so the stationary point is the minimizer.)

  3. \(\mathbb E[\hat\beta_{\lambda,j}] = \beta_j/(1 + \lambda)\), so the bias is \(\beta_j/(1 + \lambda) - \beta_j = -\lambda\beta_j/(1 + \lambda)\): a multiple of \(\beta_j\), toward zero. The variance is \(\sigma^2/(1 + \lambda)^2\). Each coordinate’s mean squared error is bias squared plus variance, \((\lambda^2\beta_j^2 + \sigma^2)/(1 + \lambda)^2\); summing over \(j\) gives the formula. \(\blacksquare\)

  4. \(\mathrm{MSE}(\lambda) = (\lambda^2\|\beta\|^2 + p\sigma^2)/(1 + \lambda)^2\). By the quotient rule, \[ \mathrm{MSE}'(\lambda) = \frac{2\lambda\|\beta\|^2(1 + \lambda)^2 - 2(1 + \lambda)(\lambda^2\|\beta\|^2 + p\sigma^2)}{(1 + \lambda)^4} = \frac{2\lambda\|\beta\|^2(1 + \lambda) - 2\lambda^2\|\beta\|^2 - 2p\sigma^2}{(1 + \lambda)^3} = \frac{2\lambda\|\beta\|^2 - 2p\sigma^2}{(1 + \lambda)^3}. \] At \(\lambda = 0\) this is \(-2p\sigma^2 < 0\), and \(\beta\) does not appear. A differentiable function with a negative derivative at \(0\) is below its value at \(0\) on some interval \((0, \delta)\), so \(\mathrm{MSE}(\lambda) < p\sigma^2\) for every small enough \(\lambda > 0\): some bias, on purpose, beats least squares, whatever the truth is.

  5. For \(\beta \ne \mathbf 0\) the derivative is zero at \(\lambda^\star = p\sigma^2/\|\beta\|^2 = \sigma^2 / (\|\beta\|^2/p)\), the noise variance over the mean squared coefficient; it is negative below \(\lambda^\star\) and positive above, so \(\lambda^\star\) is the minimizer. Substituting, with \(B = \|\beta\|^2\): \(\mathrm{MSE}(\lambda^\star) = \big(p^2\sigma^4/B + p\sigma^2\big)/\big(1 + p\sigma^2/B\big)^2 = p\sigma^2 \cdot B/(B + p\sigma^2) < p\sigma^2\). When \(\beta = \mathbf 0\), \(\mathrm{MSE}(\lambda) = p\sigma^2/(1 + \lambda)^2\) decreases to \(0\) as \(\lambda \to \infty\): there is no finite minimizer, and every \(\lambda > 0\) beats least squares. It cannot be used because \(\beta\) and \(\sigma^2\) are what we do not know; \(\lambda\) is chosen on the data, by cross-validation, and the decomposition is about a fixed \(\lambda\), not a data-chosen one.

Common errors: forgetting to square the bias in (c); in (d), claiming \(\mathrm{MSE}(\lambda) < \mathrm{MSE}(0)\) for every \(\lambda > 0\) (false: as \(\lambda \to \infty\), \(\mathrm{MSE}(\lambda) \to \|\beta\|^2\), which exceeds \(p\sigma^2\) when the signal is strong); writing the variance of \(\hat\beta_{\lambda,j}\) as \(\sigma^2/(1 + \lambda)\) (a constant \(c\) multiplies a variance by \(c^2\)).

Exercise 2 (the \(k\)-nearest-neighbor rate, with the slides closed). Inputs \(x_1, \ldots, x_n\) i.i.d. uniform on \([0, 1]^p\); outcomes \(y_i = f^\star(x_i) + \varepsilon_i\) with the \(\varepsilon_i\) independent of each other and of the inputs, mean \(0\), variance \(\sigma^2\); \(f^\star\) is \(L\)-Lipschitz, \(|f^\star(x) - f^\star(x')| \le L\|x - x'\|\), with \(L > 0\) and \(\sigma^2 > 0\). For a point \(x_0\), \(r_k(x_0)\) is the distance from \(x_0\) to its \(k\)th nearest input, \(x_{(1)}, \ldots, x_{(k)}\) are the \(k\) nearest inputs, and \(\hat f_k(x_0) = \tfrac1k\sum_{l=1}^k y_{(l)}\) is the mean of their outcomes. You may use the lemma stated in the lecture: for \(x_0\) away from the boundary, \(\mathbb E[r_k(x_0)^2] \le C_p (k/n)^{2/p}\), with \(C_p\) depending on \(p\) only.

  1. Conditional on the inputs, write \(\hat f_k(x_0) - f^\star(x_0)\) as the sum of a term that depends only on \(f^\star\) and the inputs and a term that depends on the noise. Show that the first term is at most \(L\,r_k(x_0)\) in absolute value.

  2. Show that, conditional on the inputs, the noise term has mean \(0\) and variance \(\sigma^2/k\).

  3. Deduce \(\mathbb E\big[(\hat f_k(x_0) - f^\star(x_0))^2 \mid \text{inputs}\big] \le L^2 r_k(x_0)^2 + \sigma^2/k\), then take the expectation over the inputs and apply the lemma.

  4. Treat \(k\) as a continuous variable and minimize the bound \(C_p L^2 (k/n)^{2/p} + \sigma^2/k\) over \(k\). Show that the minimizer is \(k = c\,n^{2/(p+2)}\) for a constant \(c\) that depends on \(p\), \(L\), \(\sigma^2\) and \(C_p\) but not on \(n\), and that the minimized bound is proportional to \(n^{-2/(p+2)}\).

  5. By what factor must \(n\) grow to halve the bound when \(p = 10\)? When \(p = 1\)?

  1. \(\hat f_k(x_0) - f^\star(x_0) = \tfrac1k\sum_l \big(f^\star(x_{(l)}) - f^\star(x_0)\big) + \tfrac1k\sum_l \varepsilon_{(l)}\). Every one of the \(k\) nearest inputs is within \(r_k(x_0)\) of \(x_0\).

(b), (c) Given the inputs, which \(k\) noise terms are averaged is fixed, and they are independent with variance \(\sigma^2\). For (c), expand \((a + b)^2\) with \(a\) the first term and \(b\) the noise term; what is the conditional mean of the cross term?

  1. Write the bound as \(A k^{2/p} + B/k\) with \(A = C_p L^2 n^{-2/p}\) and \(B = \sigma^2\). The derivative is zero when \((2A/p)\,k^{2/p - 1} = B/k^2\), that is, \(k^{(p+2)/p} = pB/(2A)\).
  1. Given the inputs, the \(k\) nearest are determined, and \(\hat f_k(x_0) = \tfrac1k\sum_l y_{(l)} = \tfrac1k\sum_l f^\star(x_{(l)}) + \tfrac1k\sum_l \varepsilon_{(l)}\). Subtracting \(f^\star(x_0)\), \[ \hat f_k(x_0) - f^\star(x_0) = \underbrace{\tfrac1k\textstyle\sum_l \big(f^\star(x_{(l)}) - f^\star(x_0)\big)}_{a} + \underbrace{\tfrac1k\textstyle\sum_l \varepsilon_{(l)}}_{b}. \] Each \(x_{(l)}\) is within \(r_k(x_0)\) of \(x_0\), so by the Lipschitz condition \(|f^\star(x_{(l)}) - f^\star(x_0)| \le L\|x_{(l)} - x_0\| \le L\,r_k(x_0)\), and an average of \(k\) numbers each at most \(L\,r_k(x_0)\) in absolute value is at most \(L\,r_k(x_0)\) in absolute value: \(|a| \le L\,r_k(x_0)\).

  2. Given the inputs, \(b\) is the mean of \(k\) fixed noise variables, independent with mean \(0\) and variance \(\sigma^2\) (the noise is independent of the inputs, so conditioning on the inputs does not change its distribution). Its conditional mean is \(0\) and its conditional variance is \(k\sigma^2/k^2 = \sigma^2/k\).

  3. \(a\) is fixed given the inputs, so \(\mathbb E[(a + b)^2 \mid \text{inputs}] = a^2 + 2a\,\mathbb E[b \mid \text{inputs}] + \mathbb E[b^2 \mid \text{inputs}] = a^2 + 0 + \sigma^2/k \le L^2 r_k(x_0)^2 + \sigma^2/k\). Taking the expectation over the inputs (the tower property) and applying the lemma, \(\mathbb E\big[(\hat f_k(x_0) - f^\star(x_0))^2\big] \le C_p L^2 (k/n)^{2/p} + \sigma^2/k\). \(\blacksquare\)

  4. With \(A = C_p L^2 n^{-2/p}\) and \(B = \sigma^2\), the bound is \(g(k) = A k^{2/p} + B/k\): the first term grows with \(k\), the second shrinks. \(g'(k) = (2A/p) k^{2/p - 1} - B/k^2 = 0\) gives \(k^{2/p + 1} = pB/(2A)\), that is, \(k^{(p+2)/p} = \big(p\sigma^2/(2C_pL^2)\big)\, n^{2/p}\), so \(k = c\,n^{2/(p+2)}\) with \(c = \big(p\sigma^2/(2C_pL^2)\big)^{p/(p+2)}\). This is the minimizer: \(k^2 g'(k) = (2A/p)k^{1 + 2/p} - B\) increases with \(k\) from \(-B < 0\), so \(g'\) is negative below this \(k\) and positive above it. (The real \(k\) is a stand-in for an integer between \(1\) and \(n\); the nearest integer gives the same order.) At this \(k\) the two terms are of the same order: \(A k^{2/p} \propto n^{-2/p}\,n^{4/(p(p+2))} = n^{-2/(p+2)}\), since \(-2/p + 4/(p(p+2)) = -2(p + 2)/(p(p+2)) + 4/(p(p+2)) = -2/(p+2)\), and \(B/k \propto n^{-2/(p+2)}\). So the minimized bound is proportional to \(n^{-2/(p+2)}\).

  5. The bound halves when \(n^{-2/(p+2)}\) halves, that is, when \(n\) grows by \(2^{(p+2)/2}\): for \(p = 10\), \(2^6 = 64\) times the data; for \(p = 1\), \(2^{3/2} \approx 2.8\) times.

Common errors: bounding \(|a|\) by \(L\,r_k\) without the triangle inequality on the average (each term is bounded, then the average); dropping the cross term in (c) “by independence” (it vanishes because the noise has conditional mean zero); carrying \(C_p\) and \(L\) into the exponent in (d) (they set the constant \(c\); the exponent \(2/(p+2)\) does not depend on them).

Problems

Problem 1 (soft thresholding). One coordinate of an orthonormal design: \(z\) is the least-squares coefficient, a number, and \(b\) the estimate. The lasso’s one-coordinate objective is \(\tfrac12(z - b)^2 + \lambda|b|\) with \(\lambda > 0\).

  1. Show that the minimizer is \(\hat b = \mathrm{sign}(z)\,(|z| - \lambda)_+\): \(z\) moved toward zero by \(\lambda\), stopping at zero.

  2. The lecture writes the lasso objective as \(\|\mathbf y - \mathbf X\beta\|^2 + \lambda\|\beta\|_1\), without the \(\tfrac12\). In the orthonormal design (\(\mathbf X\) is \(n \times p\) with \(\mathbf X^T\mathbf X = \mathbf I\)), show that this objective splits into one problem per coefficient, and find by how much that lasso moves each coefficient toward zero.

  1. For \(b > 0\) the objective is \(\tfrac12(z - b)^2 + \lambda b\), differentiable: set the derivative to zero and check that the solution is positive. Likewise for \(b < 0\). If neither case gives a valid solution, the minimum is at the kink.
  1. Let \(\mathbf z = \mathbf X^T\mathbf y\), the least-squares estimate in this design. Write \(\mathbf y - \mathbf X\beta = (\mathbf y - \mathbf X\mathbf z) + \mathbf X(\mathbf z - \beta)\) and show that the two pieces are orthogonal.
  1. For \(b > 0\) the derivative is \(-(z - b) + \lambda\), zero at \(b = z - \lambda\), which is positive only if \(z > \lambda\). For \(b < 0\) the derivative is \(-(z - b) - \lambda\), zero at \(b = z + \lambda\), negative only if \(z < -\lambda\). If \(|z| \le \lambda\) neither case gives a solution; the objective is convex (a convex quadratic plus \(\lambda|b|\)), so its minimum is at the one remaining candidate, the kink \(b = 0\). Together: \(\hat b = z - \lambda\) for \(z > \lambda\), \(z + \lambda\) for \(z < -\lambda\), \(0\) between, which is \(\mathrm{sign}(z)(|z| - \lambda)_+\).

  2. First, the reduction to one coefficient at a time. Let \(\mathbf z = \mathbf X^T\mathbf y\). With \(\mathbf X^T\mathbf X = \mathbf I\) the normal equations \(\mathbf X^T\mathbf X\beta = \mathbf X^T\mathbf y\) read \(\beta = \mathbf z\), so \(\mathbf z\) is the least-squares estimate and \(z_j\) the least-squares coefficient of the problem’s statement. For any \(\beta\), \[ \mathbf y - \mathbf X\beta = (\mathbf y - \mathbf X\mathbf z) + \mathbf X(\mathbf z - \beta). \] The two pieces are orthogonal: \(\mathbf X^T(\mathbf y - \mathbf X\mathbf z) = \mathbf z - \mathbf X^T\mathbf X\mathbf z = \mathbf 0\), so the residual is orthogonal to every column of \(\mathbf X\), and the second piece is a combination of those columns. By Pythagoras, and because \(\|\mathbf X\mathbf v\|^2 = \mathbf v^T\mathbf X^T\mathbf X\mathbf v = \|\mathbf v\|^2\), \[ \|\mathbf y - \mathbf X\beta\|^2 = \|\mathbf y - \mathbf X\mathbf z\|^2 + \|\mathbf X(\mathbf z - \beta)\|^2 = \|\mathbf y - \mathbf X\mathbf z\|^2 + \sum_{j=1}^p (z_j - \beta_j)^2. \] The first term does not involve \(\beta\), and \(\lambda\|\beta\|_1 = \lambda\sum_j|\beta_j|\), so minimizing the lecture’s objective means minimizing \(\sum_{j=1}^p \big[(z_j - \beta_j)^2 + \lambda|\beta_j|\big]\). Each term involves one coefficient only, so the sum is smallest when each term is: \(p\) separate problems, \((z_j - b)^2 + \lambda|b|\) in \(b\). (In the lecture’s identity design, \(\mathbf X = \mathbf I\) and \(n = p\), so \(\mathbf z = \mathbf y\) and the first term is zero.) Second, the scale. \((z - b)^2 + \lambda|b| = 2\big[\tfrac12(z - b)^2 + \tfrac\lambda2|b|\big]\), and doubling an objective does not move its minimizer, so this is the problem of (a) with \(\lambda/2\) in place of \(\lambda\): \(\hat\beta_j = \mathrm{sign}(z_j)\,(|z_j| - \lambda/2)_+\). The lecture’s lasso moves each coefficient toward zero by \(\lambda/2\) and stops at zero.

Common errors: forgetting to check the sign condition in (a) (\(b = z - \lambda\) with \(z < \lambda\) is negative, which is not in the case \(b > 0\)); in (b), answering \(2\lambda\): the factor 2 multiplies the whole objective, so it halves \(\lambda\) relative to the \(\tfrac12\) form; or splitting the objective into coordinates without using \(\mathbf X^T\mathbf X = \mathbf I\), which is what makes the cross terms vanish.

Problem 2 (the distance lemma in one dimension). \(n\) inputs i.i.d. uniform on \([0, 1]\), the point \(x_0 = \tfrac12\), and \(r_1\) the distance from \(x_0\) to the nearest input.

  1. For \(0 \le r \le \tfrac12\), show that \(\mathbb P(r_1 > r) = (1 - 2r)^n\).

  2. Compute \(\mathbb E[r_1]\). You may use \(\mathbb E[W] = \int_0^\infty \mathbb P(W > w)\,dw\) for \(W \ge 0\).

  3. Compute \(\mathbb E[r_1^2]\) (use \(\mathbb E[W^2] = \int_0^\infty 2w\,\mathbb P(W > w)\,dw\)) and compare it with the lemma’s \((k/n)^{2/p}\) at \(k = 1\), \(p = 1\).

  4. Let \(N(r)\) be the number of inputs within distance \(r\) of \(x_0\). What is its distribution? The distance \(r_k\) to the \(k\)th nearest input satisfies \(r_k > r\) exactly when \(N(r) < k\). Without computing, explain why \(r_k\) is about \(k/(2n)\) when \(k\) is much smaller than \(n\).

  5. In \(p\) dimensions a ball of radius \(r\) has volume \(c_p r^p\). Repeat the argument of (d) to find the order of \(r_k\), and hence of \(r_k^2\), in \(p\) dimensions. Why does the lemma say “away from the boundary”?

  1. \(r_1 > r\) means that no input landed in the interval \((\tfrac12 - r, \tfrac12 + r)\). Each input falls in it with probability \(2r\), independently of the others.

(b), (c) Substitute \(u = 1 - 2r\). \(\int_0^1 u^n\,du = 1/(n + 1)\) and \(\int_0^1 u^n(1 - u)\,du = 1/((n + 1)(n + 2))\).

(d), (e) The expected number of inputs in a region is \(n\) times its volume. The \(k\)th nearest input is at the radius where that count reaches \(k\).

  1. Each input misses the interval \((\tfrac12 - r, \tfrac12 + r)\), of length \(2r\), with probability \(1 - 2r\); the inputs are independent, so all \(n\) miss it with probability \((1 - 2r)^n\), and that is the event \(r_1 > r\).

  2. \(\mathbb E[r_1] = \int_0^{1/2} (1 - 2r)^n\,dr\) (the tail is zero beyond \(\tfrac12\)). With \(u = 1 - 2r\), \(dr = -du/2\): \(\tfrac12\int_0^1 u^n\,du = 1/(2(n + 1))\), about \(1/(2n)\): the nearest input is half a spacing away, on one side or the other.

  3. \(\mathbb E[r_1^2] = \int_0^{1/2} 2r(1 - 2r)^n\,dr\). With the same substitution, \(r = (1 - u)/2\): \(\int_0^1 (1 - u)\,u^n\,\tfrac{du}{2} = \tfrac12\big[\tfrac1{n+1} - \tfrac1{n+2}\big] = \frac{1}{2(n + 1)(n + 2)}\), about \(1/(2n^2)\). The lemma at \(k = 1\), \(p = 1\) says \(\mathbb E[r_1^2] \le C_1 (1/n)^2\): the same order, with \(C_1 = \tfrac12\) (and a little better, because of the \(+1\) and \(+2\)).

  4. Each input is within \(r\) of \(x_0\) with probability \(2r\) (for \(r \le \tfrac12\)), independently, so \(N(r) \sim \mathrm{Binomial}(n, 2r)\) with mean \(2rn\). The \(k\)th nearest input is at the radius where the count reaches \(k\); setting the count’s mean to \(k\) gives \(2rn = k\), so \(r_k\) is about \(k/(2n)\). This is a statement about its typical size, its mean, not a claim that \(r_k\) concentrates: at that radius the count is close to Poisson with mean \(k\), so it fluctuates by about \(\sqrt k\) however large \(n\) is, and \(r_k\) by a relative amount of about \(1/\sqrt k\). (Exactly: the distances \(|x_i - \tfrac12|\) are i.i.d. uniform on \([0, \tfrac12]\), so \(r_k\) is their \(k\)th order statistic and \(\mathbb E[r_k] = k/(2(n + 1))\), \(\mathbb E[r_k^2] = k(k + 1)/(4(n + 1)(n + 2))\), which for \(k = 1\) is (c).)

  5. The count within radius \(r\) has mean \(n c_p r^p\); setting it to \(k\) gives \(r_k \approx (k/(c_p n))^{1/p}\), so \(r_k^2 \approx c_p^{-2/p} (k/n)^{2/p}\): the lemma’s order, with the constant depending on \(p\) through \(c_p\). Near the boundary of the cube part of the ball lies outside \([0, 1]^p\) and holds no inputs, so the ball must be bigger to hold \(k\) of them: the constant changes (the exponent does not), and the lemma as stated is for interior points.

Common errors: using \(\mathbb P(r_1 \le r)\) in the tail formula; forgetting that the interval has length \(2r\) (both sides of \(x_0\)); in (c), computing \(\mathbb E[r_1]^2\) instead of \(\mathbb E[r_1^2]\).

Problem 3 (the smoothing penalty as weighted ridge). A one-input curve written in a spline basis, \(f(x) = \sum_{j=1}^J \beta_j b_j(x)\): the \(b_j\) are twice differentiable and their span contains the constant and the linear functions. \(\lambda \ge 0\). \(\mathbf B\) is the \(n \times J\) matrix with \(B_{ij} = b_j(x_i)\), and \(\boldsymbol\Omega\) the \(J \times J\) matrix with \(\Omega_{jk} = \int b_j''(x)\,b_k''(x)\,dx\). The smoothing objective is \(\sum_{i=1}^n (y_i - f(x_i))^2 + \lambda\int f''(x)^2\,dx\).

  1. Show that \(\int f''(x)^2\,dx = \beta^T\boldsymbol\Omega\beta\), so the objective is \(\|\mathbf y - \mathbf B\beta\|^2 + \lambda\beta^T\boldsymbol\Omega\beta\). Show that \(\boldsymbol\Omega\) is symmetric and positive semidefinite.

  2. Show that the minimizer satisfies \((\mathbf B^T\mathbf B + \lambda\boldsymbol\Omega)\beta = \mathbf B^T\mathbf y\), and that \(\mathbf B^T\mathbf B + \lambda\boldsymbol\Omega\) is invertible when \(\mathbf B\) has full column rank.

  3. Suppose \(\mathbf B\) has full column rank and the basis has been chosen so that \(\mathbf B^T\mathbf B = \mathbf I\) and \(\boldsymbol\Omega = \mathrm{diag}(w_1, \ldots, w_J)\) with every \(w_j \ge 0\) (such a basis exists; the lecture’s figure showed four of its functions, ordered by wiggliness). With \(\mathbf z = \mathbf B^T\mathbf y\), show that \(\hat\beta_j = z_j/(1 + \lambda w_j)\).

  4. Which basis functions have \(w_j = 0\)? What happens to their coefficients as \(\lambda \to \infty\), and to the others? What does the fit tend to?

  1. \(f''(x) = \sum_j \beta_j b_j''(x)\); square it (a double sum) and integrate term by term. For semidefiniteness, what is \(\beta^T\boldsymbol\Omega\beta\) as an integral?
  1. Expand \(\|\mathbf y - \mathbf B\beta\|^2 + \lambda\beta^T\boldsymbol\Omega\beta\) and take the gradient; the gradient of \(\beta^T\boldsymbol\Omega\beta\) is \(2\boldsymbol\Omega\beta\). For invertibility, show \(v^T(\mathbf B^T\mathbf B + \lambda\boldsymbol\Omega)v > 0\) for \(v \ne \mathbf 0\).
  1. With \(\mathbf B^T\mathbf B = \mathbf I\) and a diagonal \(\boldsymbol\Omega\), the system in (b) is \(J\) separate equations, one per coefficient.
  1. \(f''(x) = \sum_j \beta_j b_j''(x)\), so \(f''(x)^2 = \sum_j\sum_k \beta_j\beta_k\,b_j''(x)b_k''(x)\), and integrating, \(\int f''^2 = \sum_j\sum_k \beta_j\beta_k\Omega_{jk} = \beta^T\boldsymbol\Omega\beta\). Since \(f(x_i) = (\mathbf B\beta)_i\), the sum of squares is \(\|\mathbf y - \mathbf B\beta\|^2\). \(\Omega_{jk} = \Omega_{kj}\) because the integrand is symmetric in \(j\) and \(k\); and \(\beta^T\boldsymbol\Omega\beta = \int f''^2 \ge 0\) for every \(\beta\), which is positive semidefiniteness. (It is not positive definite: a \(\beta\) whose curve \(f\) is a straight line gives \(0\).)

  2. \(\|\mathbf y - \mathbf B\beta\|^2 + \lambda\beta^T\boldsymbol\Omega\beta = \mathbf y^T\mathbf y - 2\beta^T\mathbf B^T\mathbf y + \beta^T\mathbf B^T\mathbf B\beta + \lambda\beta^T\boldsymbol\Omega\beta\), with gradient \(-2\mathbf B^T\mathbf y + 2\mathbf B^T\mathbf B\beta + 2\lambda\boldsymbol\Omega\beta\); zero when \((\mathbf B^T\mathbf B + \lambda\boldsymbol\Omega)\beta = \mathbf B^T\mathbf y\): ridge regression’s equations with the penalty matrix \(\boldsymbol\Omega\) in place of \(\mathbf I\). For \(v \ne \mathbf 0\), \(v^T(\mathbf B^T\mathbf B + \lambda\boldsymbol\Omega)v = \|\mathbf Bv\|^2 + \lambda v^T\boldsymbol\Omega v \ge \|\mathbf Bv\|^2 > 0\) when \(\mathbf B\) has full column rank, so the matrix is positive definite and invertible, and the Hessian is positive definite, so the stationary point is the minimizer.

  3. With \(\mathbf B^T\mathbf B = \mathbf I\) and \(\boldsymbol\Omega = \mathrm{diag}(w)\) the system is \((\mathbf I + \lambda\,\mathrm{diag}(w))\beta = \mathbf z\), that is, \((1 + \lambda w_j)\beta_j = z_j\) for each \(j\): \(\hat\beta_j = z_j/(1 + \lambda w_j)\), the orthonormal-design ridge formula with its own \(\lambda w_j\) per coefficient. A wiggly basis function (large \(w_j\)) is shrunk hard; a smooth one barely.

  4. \(w_j = \int b_j''^2 = 0\) exactly when \(b_j'' \equiv 0\), that is, when \(b_j\) is a straight line (constant or linear). Those coefficients are \(\hat\beta_j = z_j\) for every \(\lambda\): never shrunk. Every coefficient with \(w_j > 0\) goes to \(0\) as \(\lambda \to \infty\). The fit tends to the least-squares fit on the unpenalized functions alone: the straight line through the data, which is what the lecture’s slide said \(\lambda \to \infty\) gives.

Common errors: writing \(\int f''^2 = \sum_j \beta_j^2\int b_j''^2\), dropping the cross terms (making them vanish is what the diagonal basis in (c) arranges); claiming \(\boldsymbol\Omega\) is positive definite; in (d), saying the fit tends to zero (the line is not penalized).

Problem 4 (how many folds?). \(y_1, \ldots, y_n\) are i.i.d. with mean \(\mu\) and variance \(\sigma^2\), and \(K\) divides \(n\). The method predicts a new \(Y\) (independent of the \(y_i\), with the same distribution) by the mean of the rows it is fitted on, with squared-error loss. \(K\)-fold cross-validation scores each \(y_i\) against the mean of the \(n - n/K\) rows outside its fold, and averages the \(n\) losses.

  1. Show that the mean \(\bar Y_m\) of \(m\) such rows has expected loss \(\mathbb E[(Y - \bar Y_m)^2] = \sigma^2(1 + 1/m)\) on a new \(Y\). Deduce that the \(K\)-fold CV score has expectation \(\sigma^2\big(1 + \tfrac{K}{(K-1)n}\big)\), and that it overestimates the expected loss of the mean fitted on all \(n\) rows by \(\tfrac{\sigma^2}{(K-1)n}\). Compare \(K = 2\), \(K = 10\) and \(K = n\).

  2. Leave-one-out is \(K = n\). With \(\bar y\) the mean of all \(n\) rows and \(\bar y_{(-i)}\) the mean without row \(i\), show that \(y_i - \bar y_{(-i)} = \tfrac{n}{n-1}(y_i - \bar y)\), so that the leave-one-out score needs only one fit: \(\mathrm{CV}_{(n)} = \tfrac{n}{n-1}\,s^2\) with \(s^2 = \tfrac{1}{n-1}\sum_i (y_i - \bar y)^2\). Check its expectation against (a).

  3. For tuning, the question is what \(K\) does to the choice. Take \(k\)-NN with \(p\) inputs, and suppose, as an idealization, that fitted on \(m\) rows its excess risk (its expected loss minus the noise variance \(\sigma^2\)) is exactly \(g_m(k) = a\,(k/m)^{2/p} + \sigma^2/k\), with \(a > 0\) and \(k\) treated as a continuous variable. First, show that \(g_m\) has a unique minimizer \(k^\star(m)\), proportional to \(m^{2/(p+2)}\). Second, suppose \(K\)-fold cross-validation measured \(g_m\) without error at \(m = n(K-1)/K\), so that it chooses \(k^\star(m)\), which is then used with all \(n\) rows. Show that this choice is \(\rho\,k^\star(n)\) with \(\rho = \big(\tfrac{K-1}{K}\big)^{2/(p+2)}\), and that \[ \frac{g_n(\rho\,k^\star(n))}{g_n(k^\star(n))} = \frac{p\,\rho^{2/p} + 2/\rho}{p + 2}. \] Third, show that this ratio is \(1 + (1 - \rho)^2/p\) up to terms of order \((1 - \rho)^3\), and say why there is no term of first order. Evaluate the ratio for \(p = 1\) and \(p = 11\) with \(K = 2\) and \(K = 10\): what does it say about the choice of \(K\) for tuning, as against for reporting the error?

  1. \(Y\) and \(\bar Y_m\) are independent with the same mean, so \(\mathbb E[(Y - \bar Y_m)^2] = \mathrm{Var}(Y) + \mathrm{Var}(\bar Y_m)\). In the CV score, row \(i\) is not among the rows its prediction was fitted on.
  1. \(\bar y_{(-i)} = (n\bar y - y_i)/(n - 1)\), and \(\mathbb E[s^2] = \sigma^2\).
  1. At \(k^\star(n)\) the derivative is zero, which fixes the ratio of the two terms: \(a\,(k^\star/n)^{2/p} = \tfrac p2\,\sigma^2/k^\star\). Write \(g_n(k^\star)\) and \(g_n(\rho k^\star)\) as multiples of \(\sigma^2/k^\star\). For the expansion, put \(\rho = 1 - \varepsilon\).
  1. \(Y - \bar Y_m\) has mean \(\mu - \mu = 0\), and \(Y\) is independent of \(\bar Y_m\), so \(\mathbb E[(Y - \bar Y_m)^2] = \mathrm{Var}(Y - \bar Y_m) = \sigma^2 + \sigma^2/m\). In the \(K\)-fold score, \(y_i\) is predicted by the mean of the \(m = n - n/K = n(K-1)/K\) rows outside its fold, which do not include \(y_i\), so each of the \(n\) losses has expectation \(\sigma^2(1 + 1/m) = \sigma^2\big(1 + \tfrac{K}{(K-1)n}\big)\), and so does their average. The mean fitted on all \(n\) rows has expected loss \(\sigma^2(1 + 1/n)\), and the difference is \(\sigma^2\big(\tfrac{K}{(K-1)n} - \tfrac1n\big) = \tfrac{\sigma^2}{(K-1)n}\): \(\sigma^2/n\) for \(K = 2\), \(\sigma^2/(9n)\) for \(K = 10\), \(\sigma^2/((n-1)n)\) for \(K = n\). The score is pessimistic because each fit uses fewer rows than the final one, and the bias shrinks as \(K\) grows. For the mean it is tiny next to \(\sigma^2\), because the mean’s loss barely depends on \(m\); a method whose loss falls faster with \(m\) has a larger bias at small \(K\).

  2. \(\bar y_{(-i)} = (n\bar y - y_i)/(n - 1)\), so \(y_i - \bar y_{(-i)} = \frac{(n - 1)y_i - n\bar y + y_i}{n - 1} = \frac{n}{n - 1}(y_i - \bar y)\). Then \[ \mathrm{CV}_{(n)} = \frac1n\sum_{i=1}^n \frac{n^2}{(n-1)^2}(y_i - \bar y)^2 = \frac{n}{n-1}\cdot\frac{1}{n-1}\sum_{i=1}^n (y_i - \bar y)^2 = \frac{n}{n-1}\,s^2: \] one fit, \(\bar y\) and \(s^2\), gives all \(n\) leave-one-out losses. It is the mean’s case of the least-squares shortcut, which divides each residual by \(1 - h_i\), here with leverage \(h_i = 1/n\) (ISLR, equation 5.2). Since \(\mathbb E[s^2] = \sigma^2\), \(\mathbb E[\mathrm{CV}_{(n)}] = \frac{n}{n-1}\sigma^2 = \sigma^2\big(1 + \frac{1}{n-1}\big)\), which is (a)’s expectation at \(K = n\), since \(\frac{K}{(K-1)n} = \frac{1}{n-1}\) there.

  3. The minimizer: \(g_m'(k) = \frac2p\,a\,m^{-2/p}k^{2/p - 1} - \sigma^2/k^2\) is zero when \(k^{(p+2)/p} = \frac{p\sigma^2}{2a}m^{2/p}\), that is at \(k^\star(m) = \big(\frac{p\sigma^2}{2a}\big)^{p/(p+2)} m^{2/(p+2)}\). It is the only stationary point, and \(g_m \to \infty\) both as \(k \to 0\) and as \(k \to \infty\), so it is the minimum. The choice: \(k^\star(m)/k^\star(n) = (m/n)^{2/(p+2)} = \rho\). Write \(k^\star = k^\star(n)\). Stationarity at \(k^\star\) says \(a\,(k^\star/n)^{2/p} = \frac p2\cdot\frac{\sigma^2}{k^\star}\), so \(g_n(k^\star) = \big(\frac p2 + 1\big)\frac{\sigma^2}{k^\star}\) and \(g_n(\rho k^\star) = \rho^{2/p}\,a\,(k^\star/n)^{2/p} + \frac{\sigma^2}{\rho k^\star} = \big(\frac p2\rho^{2/p} + \frac1\rho\big)\frac{\sigma^2}{k^\star}\), and the ratio is \(\frac{p\rho^{2/p} + 2/\rho}{p+2}\). The expansion: with \(\rho = 1 - \varepsilon\), \(\rho^{2/p} = 1 - \frac2p\varepsilon + \frac1p\big(\frac2p - 1\big)\varepsilon^2 + O(\varepsilon^3)\) and \(1/\rho = 1 + \varepsilon + \varepsilon^2 + O(\varepsilon^3)\), so the numerator is \(p + 2 + \frac{p+2}{p}\varepsilon^2 + O(\varepsilon^3)\) and the ratio is \(1 + \varepsilon^2/p + O(\varepsilon^3)\). The first-order terms cancel because \(k^\star\) minimizes \(g_n\): the derivative is zero there, so a small error in \(k\) costs only its square. The exact ratios are 1.19 (\(p = 1\), \(K = 2\)), 1.005 (\(p = 1\), \(K = 10\)), 1.001 (\(p = 11\), \(K = 2\)) and 1.00002 (\(p = 11\), \(K = 10\)). For tuning, \(K\) makes little difference unless the problem is low-dimensional and \(K\) is 2: the choice is pushed by a factor \(\rho\), but a flat minimum forgives it. For reporting the error, what counts is the bias of the score itself, which is of first order: in (a) it is \(\sigma^2/((K-1)n)\), and it is larger for a method whose error falls faster with the number of rows.

Common errors: in (a), predicting \(y_i\) with the mean of all \(n\) rows, which includes \(y_i\); in (b), forgetting that \(\bar y_{(-i)}\) leaves \(y_i\) out; in (c), comparing the two minima \(g_m(k^\star(m))\) and \(g_n(k^\star(n))\) instead of evaluating \(g_n\) at the chosen \(k\).

Coding

1. The cross-validation pipeline

The structures seminar’s task: predict a track’s popularity from ten audio features and its release year, squared loss (data note), genre left out. The same split as there: 5,000 training, 2,000 tuning and 3,000 test tracks, one seed. Today the tuning tracks are a check on cross-validation and the test tracks are not opened; the last step uses a split by year of the 7,000 development tracks instead of the random one.

feat <- c("danceability", "energy", "loudness", "speechiness", "acousticness",
          "instrumentalness", "liveness", "valence", "tempo", "duration_min", "release_year")
sp_file <- read_csv("https://ml4ds.com/files/spotify_tracks.csv", show_col_types = FALSE) |>
  distinct(track_id, .keep_all = TRUE) |>          # one row per track
  mutate(duration_min = duration_ms / 60000)
sp <- sp_file |> select(track_popularity, all_of(feat))   # the outcome and the eleven inputs
set.seed(310)   # change this number: a different split, and different numbers below
id <- sample(nrow(sp))
sp_train <- sp[id[1:5000], ]
sp_tune <- sp[id[5001:7000], ]
sp_test <- sp[id[7001:10000], ]
y_train <- sp_train$track_popularity
y_tune <- sp_tune$track_popularity
K <- 10          # folds, for the whole seminar

Step 1. One function for every pipeline. cv_mse(fit_predict, d, fold) takes a function fit_predict(tr, ho) that fits on the rows tr and returns predictions for the rows ho, the data d, and a vector fold giving each row’s fold. For each fold it fits on the other folds, predicts the held-out fold, and stores each held-out row’s squared loss; it returns the mean of all the losses, so every row is scored once. Assign the folds at random, the same folds for every method today.

fold <- sample(rep(1:K, length.out = nrow(sp_train)))   # each row's fold, 500 rows in each
cv_mse <- function(fit_predict, d, fold) {
  loss <- rep(NA, nrow(d))
  for (k in 1:max(fold)) {
    # tr <- ____                        # the rows whose fold is not k
    # ho <- ____                        # the rows whose fold is k
    # loss[fold == k] <- (ho$track_popularity - ____)^2
  }
  mean(loss)
}
fold <- sample(rep(1:K, length.out = nrow(sp_train)))
cv_mse <- function(fit_predict, d, fold) {
  loss <- rep(NA, nrow(d))
  for (k in 1:max(fold)) {
    tr <- d[fold != k, ]
    ho <- d[fold == k, ]
    loss[fold == k] <- (ho$track_popularity - fit_predict(tr, ho))^2
  }
  mean(loss)
}

Checkpoint (run it; if it stops, fix step 1 before going on): the mean of the training rows, as a pipeline, should score close to the variance of y_train.

mean_fp <- function(tr, ho) rep(mean(tr$track_popularity), nrow(ho))
stopifnot(abs(cv_mse(mean_fp, sp_train, fold) - var(y_train)) < 5)

Step 2. The CV curve for \(k\) nearest neighbors. knn_fp(k) returns a fit_predict function for one value of \(k\): it standardizes the inputs with the fold’s training rows (the means and standard deviations of tr, applied to both tr and ho), then calls knn_predict(). Run it over ks, find the \(k\) at the minimum, and draw the curve.

ks <- c(1, 2, 5, 10, 20, 50, 100, 200, 500)
knn_fp <- function(k) function(tr, ho) {
  mu <- colMeans(tr[, feat]); s <- apply(tr[, feat], 2, sd)
  # knn_predict(____, ____, tr$track_popularity, k)
}
# cv_knn <- sapply(ks, function(k) ____)
# k_cv <- ____
# plot: cv_knn against ks, log scale on k
ks <- c(1, 2, 5, 10, 20, 50, 100, 200, 500)
knn_fp <- function(k) function(tr, ho) {
  mu <- colMeans(tr[, feat]); s <- apply(tr[, feat], 2, sd)
  knn_predict(scale(ho[, feat], mu, s), scale(tr[, feat], mu, s), tr$track_popularity, k)
}
cv_knn <- sapply(ks, function(k) cv_mse(knn_fp(k), sp_train, fold))
k_cv <- ks[which.min(cv_knn)]
rbind(k = ks, cv_mse = round(cv_knn))
       [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
k         1    2    5   10   20   50  100  200  500
cv_mse 1026  773  614  557  537  524  522  524  533
ggplot(tibble(k = ks, mse = cv_knn), aes(k, mse)) + geom_line() + geom_point() + scale_x_log10() +
  labs(y = "10-fold CV MSE", title = paste0("k nearest neighbors: minimum at k = ", k_cv))

Question 1. The structures seminar chose \(k\) on the 2,000 tuning tracks instead. The chunk below scores the same ks that way, from fits on all 5,000 training tracks. Compare the two curves: where is each minimum, and how far apart are the two curves at the bottom? Which curve do you trust more, and what did each cost in rows? The tuning scores come with a standard error (the lecture’s formula); why does cv_mse() not return one?

mu <- colMeans(sp_train[, feat]); s <- apply(sp_train[, feat], 2, sd)
X_train <- scale(sp_train[, feat], mu, s); X_tune <- scale(sp_tune[, feat], mu, s)
tune_knn <- sapply(ks, function(k) mse(y_tune, knn_predict(X_tune, X_train, y_train, k)))
tune_se <- sapply(ks, function(k) se_loss(y_tune, knn_predict(X_tune, X_train, y_train, k)))
rbind(k = ks, cv = round(cv_knn), tune = round(tune_knn), tune_se = round(tune_se))
        [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
k          1    2    5   10   20   50  100  200  500
cv      1026  773  614  557  537  524  522  524  533
tune    1002  732  581  556  531  525  523  523  530
tune_se   29   22   16   14   13   13   12   12   12

Both curves have the same shape, a steep fall from \(k = 1\) and a flat bottom from about \(k = 20\) to \(200\); the CV minimum is at \(k = 100\) and the tuning minimum at \(k = 100\), within the flat part, where the two curves differ by less than a tuning standard error. The CV curve costs no rows: every training track is fitted on nine times and scored once, and the tuning tracks are still unused. The tuning curve left 2,000 tracks out of every fit and scored on them alone. The CV scores average over 5,000 held-out rows, but those rows were scored by ten fits that share rows, so the curve is not simply two and a half times as precise as the tuning curve’s 2,000 independent losses; its level is a little different because each CV fit used 4,500 rows, not 5,000.

cv_mse() returns no standard error because the formula needs the losses to be independent, and the pooled CV losses are not: the ten fits share rows. A standard error from them, or from the ten fold scores, is a heuristic (the lecture’s plot(cv.glmnet) bars are the second kind); the tuning set’s standard error is valid for each fixed \(k\), because its rows were held out of every fit. It is conditional on that fitted predictor, and it does not cover the minimum, which was chosen on the same tuning scores.

Step 3. The lasso through the same pipeline. lasso_fp(lam) standardizes inside the fold, fits the path on the training rows and predicts at the one \(\lambda\) lam. The sequence lam_seq comes from a fit on all 5,000 training tracks, so every fold uses the same values (a small step outside the folds, which cv.glmnet() takes too). Run the pipeline over lam_seq and find \(\lambda\) at the minimum.

lam_seq <- glmnet(X_train, y_train, standardize = FALSE, nlambda = 20)$lambda
lasso_fp <- function(lam) function(tr, ho) {
  mu <- colMeans(tr[, feat]); s <- apply(tr[, feat], 2, sd)
  fit <- glmnet(scale(tr[, feat], mu, s), tr$track_popularity, lambda = lam_seq, standardize = FALSE)
  as.vector(predict(fit, scale(ho[, feat], mu, s), s = lam))
}
# cv_lasso <- ____
# lam_cv <- ____
lam_seq <- glmnet(X_train, y_train, standardize = FALSE, nlambda = 20)$lambda
lasso_fp <- function(lam) function(tr, ho) {
  mu <- colMeans(tr[, feat]); s <- apply(tr[, feat], 2, sd)
  fit <- glmnet(scale(tr[, feat], mu, s), tr$track_popularity, lambda = lam_seq, standardize = FALSE)
  as.vector(predict(fit, scale(ho[, feat], mu, s), s = lam))
}
cv_lasso <- sapply(lam_seq, function(lam) cv_mse(lasso_fp(lam), sp_train, fold))
lam_cv <- lam_seq[which.min(cv_lasso)]
setNames(round(cv_lasso), signif(lam_seq, 2))     # the CV MSE at each lambda, large to small
     3    1.9    1.2   0.71   0.44   0.27   0.17    0.1  0.063  0.039  0.024 
   565    550    540    534    532    532    531    531    531    531    532 
 0.015  0.009 0.0056 0.0034 0.0021 
   532    532    532    532    532 

The minimum is at \(\lambda = 0.1\) (glmnet’s scale), near the small end of the path, as in the structures seminar: with 5,000 tracks and eleven inputs the data can afford every coefficient, and the lasso’s score is least squares’.

Question 2. cv.glmnet() does the same with its own code. Run it on X_train (standardized once, on all 5,000 training rows, which is why the call says standardize = FALSE) with the same folds (foldid = fold) and compare lambda.min with your lam_cv. Its lambda.1se is larger: what rule chose it, and how many coefficients does the lasso set to zero at each of the two?

cvg <- cv.glmnet(X_train, y_train, foldid = fold, standardize = FALSE)
c(lambda.min = signif(cvg$lambda.min, 2), lambda.1se = signif(cvg$lambda.1se, 2), lam_cv = signif(lam_cv, 2))
lambda.min lambda.1se     lam_cv 
      0.13       0.99       0.10 
c(zero_at_min = sum(coef(cvg, s = "lambda.min")[-1] == 0), zero_at_1se = sum(coef(cvg, s = "lambda.1se")[-1] == 0))
zero_at_min zero_at_1se 
          1           5 

lambda.min and lam_cv agree up to the coarseness of the two sequences (cv.glmnet uses a finer path, and standardizes once on all 5,000 rows rather than inside each fold, which changes the numbers very little here). lambda.1se is the one-standard-error rule: the largest \(\lambda\) whose CV error is within one (heuristic) standard error of the minimum, a flat-bottom rule that prefers the simpler model. At lambda.min the lasso sets 1 of the eleven coefficients to zero; at lambda.1se, 5.

Question 3 (how many folds?). Ten folds is a convention. The chunk below reruns the CV curves of \(k\)-NN and of the lasso with \(K = 2, 5, 10\) and \(50\) folds, twice for each \(K\) with fresh random folds, the same folds for both methods. lasso_curve() does for the lasso’s whole path what cv_mse() does for one method, on X_train, standardized once as in question 2 (cv.glmnet() refuses fewer than three folds). The \(k\)-NN curves take a minute or more, so read the questions while it runs. (a) With \(K\) folds, each fit uses what share of the 5,000 training tracks? Which \(K\) should estimate the error of a fit on all 5,000 most pessimistically? Do the curves agree, and for which method is the effect larger? (b) For which \(K\) do the scores move most between the two draws of folds? (c) The best \(k\) for \(k\)-NN grows with the number of fitting rows (where the rate’s two terms balance, \(k\) is proportional to \(n^{2/(p+2)}\)); the best \(\lambda\) for the lasso, on glmnet’s scale, shrinks, since the chance correlations the penalty has to overrule shrink as rows are added. Which way should a small \(K\) push each choice, toward a more or a less complex fit, and by about how much for \(k\)-NN here, with \(p = 11\)? Do the chosen values show it? (d) Leave-one-out cross-validation is \(K = n\). What would it cost, and what would it gain?

Ks <- c(2, 5, 10, 50)
ks_K <- c(20, 50, 100, 200)
lam_path <- glmnet(X_train, y_train, standardize = FALSE)$lambda   # cv.glmnet()'s path in question 2
lam_K <- lam_path[lam_path <= 1]
lasso_curve <- function(fold, lam) {          # the lasso's CV MSE at every lambda, for any folds
  loss <- matrix(NA, nrow(X_train), length(lam))
  for (k in 1:max(fold)) {
    fit <- glmnet(X_train[fold != k, ], y_train[fold != k], lambda = lam, standardize = FALSE)
    loss[fold == k, ] <- (y_train[fold == k] - predict(fit, X_train[fold == k, ]))^2
  }
  colMeans(loss)
}
cv_by_K <- map_dfr(Ks, function(K_try) map_dfr(1:2, function(draw) {
  # fresh folds for each K and each draw, the same for both methods
  fold_K <- sample(rep(1:K_try, length.out = nrow(sp_train)))
  bind_rows(
    tibble(method = "k-NN", knob = ks_K,
           mse = sapply(ks_K, function(k) cv_mse(knn_fp(k), sp_train, fold_K))),
    tibble(method = "lasso", knob = lam_K, mse = lasso_curve(fold_K, lam_K))) |>
    mutate(K = K_try, draw = draw)
}))
by_K <- cv_by_K |> group_by(method, K, draw) |>
  summarize(chosen = signif(knob[which.min(mse)], 2), min_cv_mse = round(min(mse), 1),
            .groups = "drop")
by_K |> pivot_wider(names_from = method, values_from = c(chosen, min_cv_mse))
# A tibble: 8 x 6
      K  draw `chosen_k-NN` chosen_lasso `min_cv_mse_k-NN` min_cv_mse_lasso
  <dbl> <int>         <dbl>        <dbl>             <dbl>            <dbl>
1     2     1           100        0.035              528.             534.
2     2     2            50        0.13               527.             533.
3     5     1           100        0.13               522.             531.
4     5     2           100        0.081              522              530.
5    10     1           100        0.061              521.             531.
6    10     2           100        0.088              521.             530.
7    50     1           100        0.067              521.             530.
8    50     2           100        0.061              520.             531.
ggplot(cv_by_K, aes(knob, mse, colour = factor(K), group = interaction(K, draw))) +
  geom_line() + scale_x_log10() + facet_wrap(~ method, scales = "free") +
  labs(x = "k for k-NN, lambda for the lasso", y = "CV MSE", colour = "K",
       title = "two draws of folds for each K")

knn_K <- cv_by_K |> filter(method == "k-NN")
lasso_K <- cv_by_K |> filter(method == "lasso")
spread <- cv_by_K |> group_by(method, K, knob) |>
  summarize(gap = abs(diff(mse)), .groups = "drop") |>
  group_by(method, K) |> summarize(largest_gap = round(max(gap), 1), .groups = "drop")
spread |> pivot_wider(names_from = method, values_from = largest_gap)
# A tibble: 4 x 3
      K `k-NN` lasso
  <dbl>  <dbl> <dbl>
1     2    3.9   1.8
2     5    1.6   1.8
3    10    3     0.7
4    50    0.9   0.3
at_100 <- knn_K |> filter(knob == 100) |> group_by(K) |> summarize(mse = mean(mse))
two_above <- knn_K |> group_by(knob) |> summarize(above = min(mse[K == 2]) > max(mse[K != 2]))
lam_mid <- lam_K[which.min(abs(lam_K - 0.05))]
at_lam <- lasso_K |> filter(knob == lam_mid) |> group_by(K) |> summarize(mse = mean(mse))
gap_text <- function(m) with(filter(spread, method == m),
                              paste0(format(largest_gap, nsmall = 1), " for K = ", K, collapse = ", "))
chosen_text <- function(m) by_K |> filter(method == m) |> group_by(K) |>
  summarize(t = paste0(paste(chosen, collapse = " and "), " (K = ", K[1], ")")) |>
  pull(t) |> paste(collapse = ", ")
  1. Each fit uses the share \((K - 1)/K\): half the tracks for \(K = 2\), 80% for 5, 90% for 10, 98% for 50. A fit on fewer tracks predicts worse, so the score estimates the error of a fit on fewer than 5,000 tracks and is pessimistic, most for \(K = 2\). For \(k\)-NN at \(k = 100\) the two draws with 2 folds average 528 against 520 with 50 folds, and the 2-fold curves lie above every other curve at 4 of the 4 values of \(k\); the curves for \(K = 5, 10, 50\) almost coincide. For the lasso at \(\lambda = 0.051\) they average 534 against 531: the same direction, a smaller gap. Both are consistent with the usual pessimism of fitting on half the tracks; the gaps also contain fold-assignment variation, of the size in (b), and two draws per \(K\) cannot separate the two exactly. (Comparing at one value of the knob avoids comparing minima, each chosen on its own noisy curve.) The effect is larger for \(k\)-NN because its error keeps falling as rows are added, while least squares on eleven inputs gains little from 4,900 rows over 2,500 (if the linear model were right, the estimation part of its error would be about \(\sigma^2 p/m\): with \(\sigma^2 \approx 520\) and \(p = 11\), about 2 at \(m = 2{,}500\) and 1 at \(m = 4{,}900\)): a small \(K\)’s pessimism is the drop in the learning curve between \(n(K-1)/K\) rows and \(n\), larger where the curve is steeper.

  2. For \(k\)-NN the largest gap between the two draws of folds, over the values of \(k\), is 3.9 for K = 2, 1.6 for K = 5, 3.0 for K = 10, 0.9 for K = 50; for the lasso, over the values of \(\lambda\), it is 1.8 for K = 2, 1.8 for K = 5, 0.7 for K = 10, 0.3 for K = 50. Two draws per \(K\) are too few to rank the \(K\)’s finely; what is general is that the fold assignment makes less difference as the folds get more numerous, and leave-one-out has none to draw. That is only the variation from the fold assignment, with the training tracks fixed. The variance that counts for estimating the risk is over new training samples, which this chunk cannot see. ISLR (section 5.1.4) argues that it grows with \(K\): leave-one-out averages \(n\) fits on almost the same rows, which are highly correlated, while 5 or 10 folds average fewer, less correlated fits. With the bias of (a), that is the trade-off behind the usual choice of 5 or 10. The argument is a heuristic: whether and how the variance changes with \(K\) depends on the method and the data.

  3. Fewer fitting rows push \(k\)-NN’s best \(k\) down, toward a more complex fit, and the lasso’s best \(\lambda\) up, toward a simpler one: the direction of the push depends on how the method’s best complexity changes with \(n\). For \(k\)-NN the push should be small here: if the rate’s balance applied, going from 4,900 to 2,500 fitting rows would move \(k\) by a factor \((2500/4900)^{2/13} \approx 0.90\), much finer than the grid’s steps. The chosen \(k\)’s are 100 and 50 (K = 2), 100 and 100 (K = 5), 100 and 100 (K = 10), 100 and 100 (K = 50); the chosen \(\lambda\)’s are 0.035 and 0.13 (K = 2), 0.13 and 0.081 (K = 5), 0.061 and 0.088 (K = 10), 0.067 and 0.061 (K = 50): both curves have flat bottoms, and a difference between two draws of the same \(K\) is their noise, not the push. With one input the factor for \(k\) would be \((2500/4900)^{2/3} \approx 0.64\), and a small \(K\) would choose visibly smaller \(k\)’s.

  4. Cost: \(n\) fits instead of 10. For \(k\)-NN the arithmetic is about the same as 10 folds, since every track is still scored once against about 5,000 others, but for a method whose fits are slow (the lasso’s path, a network) it is 500 times the work. For least squares it is free: one fit gives every leave-one-out residual (ISLR, equation 5.2). What it gains: the smallest bias of (a), fits on 4,999 tracks, and no random fold assignment.

Common errors: reading the gap between \(K = 2\) and \(K = 50\) as noise alone (both draws show it, so it is mostly the pessimism of fitting on half the tracks); expecting the chosen \(k\) or \(\lambda\) to move a lot with \(K\).

2. Learning curves and the rate

The lecture’s rate says how the error of \(k\) nearest neighbors falls with \(n\): the bound on the squared estimation error at a point is proportional to \(n^{-2/(p+2)}\), with \(p\) the number of inputs, at the best \(k\). The simulation below checks it. Inputs uniform on \([0, 1]^p\) for \(p = 1, 2, 5, 10\); the truth \(f^\star(x) = \sum_{j=1}^p \sin(2\pi x_j)/\sqrt p\), which depends on every input and is Lipschitz; noise with variance \(1\). For each \(n\) it fits \(k\)-NN at every \(k\) in ks, measures the squared estimation error \(\tfrac1{400}\sum (\hat f_k(x_0) - f^\star(x_0))^2\) on 400 new points (against the truth, not the noisy outcome), averages over three draws of the training data, and keeps the best \(k\). The chunk takes about 40 seconds.

f_star <- function(X) rowSums(sin(2 * pi * X)) / sqrt(ncol(X))
ps <- c(1, 2, 5, 10)
ns <- c(100, 200, 400, 800, 1600, 3200, 6400)
ks_lc <- c(1, 2, 5, 10, 20, 50, 100, 200, 500)
lc <- map_dfr(ps, function(p) map_dfr(ns, function(n) {
  err <- rowMeans(sapply(1:3, function(rep) {
    X <- matrix(runif(n * p), n, p); y <- f_star(X) + rnorm(n)
    X0 <- matrix(runif(400 * p), 400, p); f0 <- f_star(X0)
    sapply(ks_lc, function(k) if (k <= n / 2) mean((knn_predict(X0, X, y, k) - f0)^2) else NA)
  }))
  tibble(p = p, n = n, k_best = ks_lc[which.min(err)], mse = min(err, na.rm = TRUE))
}))
ggplot(lc, aes(n, mse, colour = factor(p))) + geom_line() + geom_point() +
  scale_x_log10() + scale_y_log10() +
  labs(colour = "p", y = "squared estimation error at the best k (log scale)", x = "n (log scale)")

Step 4. On log scales a rate is a slope: if the error is \(c\,n^{-a}\) then \(\log(\text{error}) = \log c - a\log n\). For each \(p\), fit a line of log(mse) on log(n) and read off the slope. Put the slopes next to the rate’s exponent, \(-2/(p + 2)\).

# slopes <- lc |> group_by(p) |> summarize(slope = ____)
# slopes |> mutate(rate = ____)
slopes <- lc |> group_by(p) |> summarize(slope = coef(lm(log(mse) ~ log(n)))[2])
slopes |> mutate(rate = -2 / (p + 2), across(c(slope, rate), ~ round(.x, 2)))
# A tibble: 4 x 3
      p slope  rate
  <dbl> <dbl> <dbl>
1     1 -0.71 -0.67
2     2 -0.57 -0.5 
3     5 -0.31 -0.29
4    10 -0.18 -0.17

The fitted slopes, -0.71, -0.57, -0.31, -0.18, sit beside the exponents -0.67, -0.5, -0.29, -0.17: the same order and about the same size, each a little steeper. The bound is a worst case over Lipschitz truths, so this one truth is allowed to do a little better than the exponent; what the theorem promises is that no estimator beats the exponent for every Lipschitz \(f^\star\).

Question 4. Read the figure against the lecture. (a) From \(n = 100\) to \(n = 6400\) is 64 times the data. By what factor did the error fall for \(p = 1\), and for \(p = 10\)? What does the rate predict for each? (b) Look at lc$k_best: how does the best \(k\) move with \(n\) for \(p = 1\) and for \(p = 10\), and what does the rate’s derivation say it should do?

lc_ratio <- lc |> group_by(p) |> summarize(ratio = round(mse[n == 6400] / mse[n == 100], 2), predicted = round(64^(-2 / (p[1] + 2)), 2),
                                           k_at_100 = k_best[n == 100], k_at_6400 = k_best[n == 6400])
lc_ratio
# A tibble: 4 x 5
      p ratio predicted k_at_100 k_at_6400
  <dbl> <dbl>     <dbl>    <dbl>     <dbl>
1     1  0.06      0.06       20       500
2     2  0.09      0.12       20       100
3     5  0.3       0.3        20        50
4    10  0.45      0.5        20        50
  1. For \(p = 1\) the error fell to 0.06 of its value (the rate: \(64^{-2/3} = 0.06\)); for \(p = 10\) to 0.45 (\(64^{-1/6} = 0.5\)). Sixty-four times the data about halves the error in ten dimensions; the Spotify inputs are eleven, and there halving the bound takes \(2^{(11 + 2)/2} \approx 90\) times the data, about 450,000 tracks, if popularity were a Lipschitz function of them and the bound were tight. (b) The best \(k\) grows with \(n\), fast for \(p = 1\) and slowly for \(p = 10\): the derivation balances the two terms at \(k \propto n^{2/(p+2)}\), which is \(n^{2/3}\) in one dimension and \(n^{1/6}\) in ten. The lesson: with only smoothness assumed, more data helps slowly in many dimensions, and a method that assumes more (additive, sparse) can do better when the assumption holds.

3. Three ways cross-validation goes wrong

Cross-validation has worked. It assumes that a held-out row is like a new draw: independent of the rows it was fitted on, and from the same population. Three ways that fails: copies of a track break the independence, drift over time breaks the same population, and a step that looks at the outcome outside the folds lets the held-out rows into the fit.

Step 5. The same track on both sides of a fold. The file has 11,554 rows for 10,000 tracks: 1,101 tracks are in more than one playlist, and every copy has the same audio features, year and popularity. The loader removed the copies with distinct(). Load the rows again without it, keep the 5,000 training tracks with all their copies, and build two fold assignments: fold_row, at random over rows, and fold_track, at random over tracks, so that every copy of a track is in the same fold. Then run the \(k\)-NN pipeline at \(k = 1\), \(5\) and \(50\) with each.

rows <- read_csv("https://ml4ds.com/files/spotify_tracks.csv", show_col_types = FALSE) |>
  mutate(duration_min = duration_ms / 60000) |>
  filter(track_id %in% sp_file$track_id[id[1:5000]]) |>   # the training tracks, copies kept
  select(track_id, track_popularity, all_of(feat))
fold_row <- sample(rep(1:K, length.out = nrow(rows)))
tracks <- unique(rows$track_id)
fold_of_track <- sample(rep(1:K, length.out = length(tracks)))   # one fold per track
# fold_track <- ____                                              # each row gets its track's fold
# cv_row <- sapply(c(1, 5, 50), function(k) ____)
# cv_track <- sapply(c(1, 5, 50), function(k) ____)
# rbind(k = c(1, 5, 50), by_row = round(cv_row), by_track = round(cv_track))

match(rows$track_id, tracks) gives each row the position of its track in tracks; index fold_of_track by it.

rows <- read_csv("https://ml4ds.com/files/spotify_tracks.csv", show_col_types = FALSE) |>
  mutate(duration_min = duration_ms / 60000) |>
  filter(track_id %in% sp_file$track_id[id[1:5000]]) |>
  select(track_id, track_popularity, all_of(feat))
c(rows = nrow(rows), tracks = n_distinct(rows$track_id))
  rows tracks 
  5774   5000 
fold_row <- sample(rep(1:K, length.out = nrow(rows)))
tracks <- unique(rows$track_id)
fold_of_track <- sample(rep(1:K, length.out = length(tracks)))
fold_track <- fold_of_track[match(rows$track_id, tracks)]
cv_row <- sapply(c(1, 5, 50), function(k) cv_mse(knn_fp(k), rows, fold_row))
cv_track <- sapply(c(1, 5, 50), function(k) cv_mse(knn_fp(k), rows, fold_track))
rbind(k = c(1, 5, 50), by_row = round(cv_row), by_track = round(cv_track))
         [,1] [,2] [,3]
k           1    5   50
by_row    768  600  554
by_track 1068  711  570

Checkpoint:

stopifnot(length(fold_track) == nrow(rows), all(tapply(fold_track, rows$track_id, function(f) length(unique(f))) == 1))

Question 5. What happened to the scores at \(k = 1\), and why is the effect smaller at \(k = 50\)? Which of the two numbers is the one to believe, and what is the rule? About a quarter of these rows have a copy; in a dataset of patients with several visits each, or of songs in many playlists, what would you expect?

With folds over rows, a copied track can have one copy in the held-out fold and another among the fitting rows. At \(k = 1\) its nearest neighbor is then its own copy, at distance zero and with the same popularity, so its loss is zero, and the CV score at \(k = 1\) drops from about 1068 (folds by track) to about 768: cross-validation is scoring the method’s memory of the fitting rows, which is exactly what it was meant not to do. At \(k = 50\) the copy is one neighbor among fifty, so the effect is small (554 against 570). The number to believe is the one with folds by track: the unit of the fold is the unit that repeats, and anything that is the same unit must stay on one side. Folds by track are not the same as removing the copies, as the data note’s distinct() does: the copies still count in fitting and in scoring, which is why folds by track score 1068 at \(k = 1\) where step 2, with one row per track, scored 1026. With one row per track the question does not arise; with several visits per patient or a song in many playlists, most rows have a twin, and the row-level CV score of a flexible method can be far too good, enough to choose the wrong method or the wrong knob.

Common errors: assigning fold_track by rep(1:K, ...) over the rows in track order, which puts a track’s consecutive copies in different folds (the checkpoint catches it); concluding that the copies should be removed from the fitting rows too (they can stay; the rule is that a track is not scored against itself).

Step 6. A random split against a split in time. Popularity is Spotify’s score in January 2020, and it rewards recent plays: the mean popularity by release year, below, rises through the 2010s. A random split mixes the years, so cross-validation answers “how well does this predict a track like the ones we have?”. The question a user of the model might ask is “how well will it predict this year’s releases?”. Fit least squares on the eleven inputs to the development tracks (training and tuning, 7,000) released up to 2018 (old), and score it two ways: by cross-validation on old, and on the development tracks released in 2019 and 2020 (new). For each, report the MSE and the mean error, \(\tfrac1m\sum_j (y_j - \hat f(x_j))\); cv_mean_error() does for the mean error what cv_mse() does for the MSE.

sp_dev <- sp[id[1:7000], ]                              # the training and tuning tracks
sp_dev |> filter(release_year >= 2012) |> group_by(release_year) |>
  summarize(tracks = n(), mean_popularity = round(mean(track_popularity), 1)) |> t()
                  [,1]   [,2]   [,3]   [,4] [,5]   [,6]   [,7]   [,8]   [,9]
release_year    2012.0 2013.0 2014.0 2015.0 2016 2017.0 2018.0 2019.0 2020.0
tracks           152.0  220.0  342.0  388.0  433  552.0  714.0 1823.0  155.0
mean_popularity   34.3   28.2   27.4   33.9   36   39.1   42.9   47.3   41.7
old <- sp_dev |> filter(release_year <= 2018)
new <- sp_dev |> filter(release_year >= 2019)
fold_old <- sample(rep(1:K, length.out = nrow(old)))
plane_fp <- function(tr, ho) predict(lm(track_popularity ~ ., tr), ho)
cv_mean_error <- function(fit_predict, d, fold) {        # cv_mse() with the loss replaced by the error
  err <- rep(NA, nrow(d))
  for (k in 1:max(fold)) {
    tr <- d[fold != k, ]; ho <- d[fold == k, ]
    err[fold == k] <- ho$track_popularity - fit_predict(tr, ho)
  }
  mean(err)
}
# cv_plane <- ____                                     # the MSE by cross-validation on old
# cv_me <- ____                                        # the mean error by cross-validation on old
# pred_new <- ____                                     # the plane fitted on old, predicting new
# c(cv_mse = cv_plane, cv_mean_error = cv_me, new_mse = ____, new_mean_error = ____)
# the two baselines on new: the mean of old, and the mean of new itself
# c(old_mean = ____, new_mean = ____)
cv_plane <- cv_mse(plane_fp, old, fold_old)
cv_me <- cv_mean_error(plane_fp, old, fold_old)
pred_new <- plane_fp(old, new)
round(c(cv_mse = cv_plane, cv_mean_error = cv_me, new_mse = mse(new$track_popularity, pred_new), new_mean_error = mean(new$track_popularity - pred_new)), 1)
        cv_mse  cv_mean_error        new_mse new_mean_error 
         587.4            0.0          436.0           11.0 
round(c(old_mean = mse(new$track_popularity, mean(old$track_popularity)), new_mean = mse(new$track_popularity, mean(new$track_popularity))))
old_mean new_mean 
     469      348 

Question 6. The plane’s predictions for the new tracks are too low on average, and nothing in the cross-validation scores hinted at it. Why can a random split not see this? Its MSE on the new tracks is lower than its CV score; is that good news? Which of the two scores answers the user’s question?

Cross-validation’s held-out rows come from the same years as the fitting rows, so its mean error is near zero (0 here): the drift in popularity from one year to the next is inside every fold and averages away. (Least squares makes the mean error exactly zero on the fitting rows, not on a held-out fold; here it is small because the folds are random draws from the same years.) The new tracks are all from after the fitting rows, where popularity is higher than the fitted trend predicts (the plane’s year coefficient is -0.17 per year, estimated on 1957 to 2018, and it extrapolates), so the predictions are biased low by about 11. The lower MSE on the new tracks is not evidence that the model does better there: the new tracks are more alike (their popularity has variance about 348, against about 616 for the older ones), so compare on the same tracks, with a baseline that could have been used at prediction time. The old tracks’ mean scores 469 on the new tracks, so the plane beats it by about 33, close to its margin over the mean on random folds (29): what the random split hid is the calibration, the bias of about 11, not the ranking. The new tracks’ own mean scores 348, but it uses the outcomes being predicted: it is a diagnostic after the fact, not a competitor, and says how much of the plane’s 436 is the spread of the new tracks themselves. The split in time answers the user’s question; the random split answers a different one. Which to report depends on which question is being asked, and cross-validation cannot tell you that.

Common errors: fitting the plane on old and new together before scoring on new (the fit must not see the future); reading the lower MSE on new as “the model does better on new tracks”; treating the new tracks’ own mean as a baseline a model could have used.

Step 7. The wrong way to cross-validate. Every step of a pipeline that looks at the outcome belongs inside the fold. Here is the classic way to get that wrong (ESL, section 7.10.2). Pure noise: \(n = 100\) rows, \(p = 1{,}000\) inputs and an outcome, all independent standard normal, so the best possible risk is \(1\) and no method can do better than the mean. The wrong way: screen the 20 inputs most correlated with the outcome on all 100 rows, then cross-validate least squares on those 20. The right way: screen inside each fold, on the fitting rows only. Write both as fit_predict functions for cv_mse() and compare the two CV scores with the mean’s.

n_w <- 100; p_w <- 1000
noise <- as_tibble(matrix(rnorm(n_w * p_w), n_w, p_w), .name_repair = ~ paste0("x", seq_along(.x))) |>
  mutate(track_popularity = rnorm(n_w))              # named so that cv_mse() finds the outcome
fold_w <- sample(rep(1:K, length.out = n_w))
top20 <- function(d) {                               # the 20 inputs most correlated with the outcome in d
  r <- cor(select(d, -track_popularity), d$track_popularity)
  rownames(r)[order(-abs(r))[1:20]]
}
# wrong: screened once, on all rows, before cross-validation
# keep <- top20(noise)
# wrong_fp <- function(tr, ho) predict(lm(____), ho)
# right: screened inside the fold
# right_fp <- function(tr, ho) { keep <- top20(tr); predict(lm(____), ho) }
# c(wrong = cv_mse(wrong_fp, noise, fold_w), right = cv_mse(right_fp, noise, fold_w), mean = cv_mse(mean_fp, noise, fold_w))

A formula from a character vector of names: reformulate(keep, "track_popularity"), or paste the names with +.

n_w <- 100; p_w <- 1000
noise <- as_tibble(matrix(rnorm(n_w * p_w), n_w, p_w), .name_repair = ~ paste0("x", seq_along(.x))) |>
  mutate(track_popularity = rnorm(n_w))
fold_w <- sample(rep(1:K, length.out = n_w))
top20 <- function(d) {
  r <- cor(select(d, -track_popularity), d$track_popularity)
  rownames(r)[order(-abs(r))[1:20]]
}
keep <- top20(noise)
wrong_fp <- function(tr, ho) predict(lm(reformulate(keep, "track_popularity"), tr), ho)
right_fp <- function(tr, ho) { keep <- top20(tr); predict(lm(reformulate(keep, "track_popularity"), tr), ho) }
cv_w <- round(c(wrong = cv_mse(wrong_fp, noise, fold_w), right = cv_mse(right_fp, noise, fold_w), mean = cv_mse(mean_fp, noise, fold_w)), 2)
cv_w
wrong right  mean 
 0.50  1.30  0.91 

Question 7. On pure noise nothing can beat the mean. Why does the wrong way score far below it? Which steps of a pipeline have to happen inside the fold?

On pure noise the best predictor is the outcome’s mean, zero, with risk \(1\); the fitting rows’ mean is the baseline a method can actually use, and it scores 0.91 here. The wrong way scores 0.5, far below it: the twenty inputs were chosen for their correlation with the outcome on the very rows that are later held out, so the held-out rows are not fresh, and their chance correlations with the chosen inputs make the fit look good on them. The right way scores 1.3, at or above the baseline, as a least-squares fit of 20 noise inputs on 90 rows will usually be. Every step that looks at the outcome (screening inputs, choosing a transformation by its fit) belongs inside the fold; so does tuning, when the score is to estimate the error of the tuned pipeline, which is why the minimum of a CV curve is a slightly optimistic estimate of the chosen fit’s error. Steps that look only at the inputs, such as standardizing, leak much less; this notebook standardizes inside the fold anyway, except in questions 2 and 3, which call glmnet() on X_train, standardized once on all 5,000 training tracks.

Common errors: screening inside wrong_fp by accident, which makes it the right way; reading the right way’s score above 1 as a mistake (twenty noise inputs fitted on 90 rows add variance).

Optional, can be done at home: the weighted-ridge form on a real fit

Problem 3 says the penalized spline’s coefficients solve \((\mathbf B^T\mathbf B + \lambda\boldsymbol\Omega)\beta = \mathbf B^T\mathbf y\). Check it on mgcv’s fit of popularity on the release year, as in the lecture: model.matrix() gives \(\mathbf B\) (the intercept and nineteen smooth columns), g$smooth[[1]]$S[[1]] gives the penalty matrix of the smooth columns, and g$sp the \(\lambda\) that GCV chose. Build \(\boldsymbol\Omega\) with a row and column of zeros for the intercept, solve, and compare with coef(g).

g <- gam(track_popularity ~ s(release_year, k = 20, bs = "cr"), data = sp_train)
B <- model.matrix(g)
S <- g$smooth[[1]]$S[[1]]
Omega <- matrix(0, ncol(B), ncol(B)); Omega[-1, -1] <- S
# beta <- solve(____, ____)
# max(abs(beta - coef(g)))
g <- gam(track_popularity ~ s(release_year, k = 20, bs = "cr"), data = sp_train)
B <- model.matrix(g)
S <- g$smooth[[1]]$S[[1]]
Omega <- matrix(0, ncol(B), ncol(B)); Omega[-1, -1] <- S
beta <- solve(t(B) %*% B + g$sp * Omega, t(B) %*% sp_train$track_popularity)
max(abs(as.vector(beta) - coef(g)))
[1] 1.031566e-10

The two agree to rounding: mgcv’s fit is ridge regression with the penalty matrix \(\boldsymbol\Omega\), at the \(\lambda\) it chose. (mgcv scales its penalty matrix, so g$sp is \(\lambda\) on that scale, not the one of \(\int f''^2\); the equations are the same.)

References

  • Hastie, T., Tibshirani, R. and Friedman, J. (2009). The Elements of Statistical Learning: Data Mining, Inference, and Prediction, 2nd edition. Springer, New York. Section 7.10.2, “The Wrong and Right Way to Do Cross-validation”, pp. 245–247. hastie.su.domains/ElemStatLearn
  • James, G., Witten, D., Hastie, T. and Tibshirani, R. (2021). An Introduction to Statistical Learning with Applications in R, 2nd edition. Springer, New York. Section 5.1.4, “Bias-Variance Trade-Off for k-Fold Cross-Validation”, pp. 205–206, and equation (5.2), p. 202. statlearning.com