The least squares coefficients make the sum of squared residuals on the training points as small as possible. With \(X\) the \(n \times (d+1)\) matrix whose columns are \(1, x, x^2, \ldots, x^d\):
R's lm() solves this with a QR decomposition of \(X\), which avoids squaring the numbers in \(X\) and so loses less to rounding than inverting \(X^\top X\).
A polynomial of degree \(d+1\) with \(\beta_{d+1} = 0\) is a polynomial of degree \(d\). The best fit of degree \(d+1\) therefore fits the training points at least as well as the best fit of degree \(d\).
On \([0, 1]\), the powers \(x^{12}, x^{13}, \ldots\) are nearly linear combinations of the lower powers. When the part of a column that the earlier columns do not explain is less than \(10^{-7}\) of its length, lm() drops it as aliased, prints NA for its coefficient, and fits the other columns. On the default sample, degree 13 keeps the same 13 columns as degree 12, so the two fits are the same, and degree 15 repeats degree 14. Which columns are dropped turns on the last digits of \(x^k\) and can differ between computers. The fits here use the columns R dropped on the computer that built them. poly(x, d) without raw = TRUE builds orthogonal polynomials and keeps every column.
The 500 test points are evenly spaced from \(x = 0\) to \(x = 1\), each with fresh noise. With real data the true curve is unknown, so the degree is chosen by cross-validation on the training set, which fits each degree on all but one slice of the training points, scores it on the slice left out, and averages over the slices. The test set grades the final model once.
The test points run a little past the smallest and largest training \(x\). There a high-degree polynomial swings far from the true curve, and those swings make up most of its test MSE.
lm(y ~ poly(x, 3, raw = TRUE), data = train) fits degree 3, and predict(fit, newdata = test) gives its predictions at the test points. Part 1 of The Script runs both at every degree.
The prediction at \(x_0\) averages the \(y\) values of the \(k\) nearest training points; no model is fit in advance.
\(N_k(x_0)\) is the set of the \(k\) training points closest to \(x_0\). When two points are the same distance away, the one that comes first in the data counts as closer, as order() in R breaks the tie.
At \(k = 1\), the prediction at a training point is that point's own \(y\), so training MSE is 0. At \(k = n\), every prediction is \(\bar y\), the mean of all \(n\) training values, and the fit is a flat line.
A KNN fit with \(k\) neighbors behaves roughly like a model with \(n/k\) parameters (Hastie, Tibshirani, and Friedman, The Elements of Statistical Learning, section 2.3.2). So \(1/k\) measures flexibility as the degree does for a polynomial: the larger \(1/k\), the more flexible the fit.
mean(y_train[order(abs(x_train - x0))[1:k]]) is the prediction at \(x_0\). The knn_predict() function in part 2 of The Script applies it at every new \(x\).
Take a new point at \(x_0\) with \(y_0 = f(x_0) + \varepsilon\), where \(\varepsilon\) has mean 0 and variance \(\sigma^2\) and is independent of the training data, and let \(\hat y(x_0)\) be the fit from a random training set. Then
Write \(y_0 - \hat y = \varepsilon + (f - E\hat y) + (E\hat y - \hat y)\) and square it. Every cross term has a factor with mean zero: \(\varepsilon\) is independent of the other two, and \(E\hat y - \hat y\) averages to zero over training sets. Averaging over \(x_0\) gives the three parts on the plot.
For each degree, the simulation draws \(S\) training sets of \(n\) points, each with fresh \(x\) and fresh noise, fits each set, and predicts at 100 evenly spaced \(x\) from 0 to 1. At each \(x\), the \(S\) predictions give an average and a variance. Bias² and variance are then averaged over the 100 values of \(x\).
The gold curve averages only \(S\) fits, so the estimated bias² includes simulation error that averages variance ÷ \(S\). The true bias² does not depend on \(\sigma\), but this error grows with \(\sigma^2\). Where the true bias² is small, the error is most of the estimate: on the default settings bias² is 0.0002 at degree 5 and 0.0261, 0.0102, and 0.2416 at degrees 6 to 8, and at degree 8 the variance is 29.4013, so variance ÷ 100 is about 0.29. More simulations shrink this error on average, but one wild fit among them can still raise the estimate, so a run of 500 can show a larger bias² than a run of 100.
For fixed \(x\), the least squares fit is \(\hat y = Hy\), where \(H\) is the matrix that turns the training \(y\) values into the fitted values and depends only on \(x\). So \(\operatorname{Var}(\hat y)\) is \(\sigma^2\) times a number set by \(x\), and doubling \(\sigma\) multiplies the variance by four. In the simulation \(x\) also changes from one training set to the next, and that part of the variance does not grow with \(\sigma\). On the default settings the factor is near four from degree 3 up and smaller at degrees 1 and 2 (2.7 and 2.1).
Part 3 of The Script writes the simulation with replicate(), colMeans(), and var().
The best candidate is the lowest test MSE on the current sample over polynomial degrees 1 to 15 and KNN with \(k\) = 1, 3, 5, 7, 10, 15, 20, and 30 (those below \(n\)). Only those values of \(k\) are searched, so a \(k\) off the list can come in below it.
A residual is \(y - \hat y\) at a training point. When a model is too rigid, its residuals follow a pattern against the fitted values, such as runs above and below zero. When it is too flexible, its residuals are small and show no pattern, so the plot cannot reveal overfitting.
With real data the test set stays untouched until the end. Training MSE is lowest for the most flexible model, so the tuning parameter has to be chosen with data the fit never used, such as cross-validation folds.
Part 4 of The Script fits every degree and every candidate \(k\) on this sample and finds the best candidate.
| Call | What it returns |
|---|---|
lm(y ~ poly(x, d, raw = TRUE), data = train) | The least squares polynomial of degree d, with columns x, x2, …, xd. |
predict(fit, newdata = test) | The fit's predictions at new x. |
fit$rank | How many columns lm() kept. Below d + 1 means some were dropped as aliased. |
mean((y - yhat)^2) | The MSE. |
order(abs(x_train - x0))[1:k] | The rows of the k training points nearest x0. |
replicate(S, expr) | The value of expr from S runs, one per simulated training set. |
colMeans(fits), apply(fits, 2, var) | The average fit and the variance of the fits at each x. |