Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 3: Classical Machine LearningCore Concepts

Polynomial regression, underfitting and overfitting

P3.A340 min●●○ IntermediateReviewed Dec 2, 2026

Why this matters for machine learning

A model has to be flexible enough to follow the real pattern and not so flexible that it follows the noise as well. Polynomial degree is the simplest knob for this, and the same trade-off appears in every model in this course.

  • Choosing the settings that control flexibility (polynomial degree, tree depth, network size) is done on held-out validation data, never on training error. (P3.A4: Train, validation and test sets)
  • Regularization keeps a flexible model from overfitting by penalizing large weights, and it is the standard answer when you do not want to lower the degree. (P3.A6: Regularization: L1 and L2)
  • A decision tree that is allowed to grow deep enough memorises its training set in the same way as a degree-9 polynomial. (P3.B3: Decision trees)
  • Reading training and validation loss curves, to tell whether a neural network is underfitting or overfitting, uses the vocabulary of this lesson. (P4.22: The training recipe and debugging)

Before this: Linear regression, Projections and least squares

After this lesson you can

  • Fit a polynomial of any degree with ordinary least squares by building the columns 1, x, x², … and explain why this is still linear regression
  • Define underfitting and overfitting from the training error and the error on held-out points, and read a train and test error curve against the degree
  • Explain why training error can never rise as the degree grows, why degree N−1 passes through N points exactly, and why that is not a good model
  • Say how more data, a simpler model, regularization and validation each help, and what goes wrong numerically with high degrees

In P0.2 a wiggly curve passed through six training points with a training loss of 0.00, and it did far worse than a plain straight line on six new points. A lower training error did not mean a better model. That lesson showed the trap. This one explains it, measures it, and shows what to do about it.

The tool is a model whose flexibility you can turn up one notch at a time: a polynomial. By the end you will know why a perfect fit to your data is a warning sign, how to recognise too little and too much flexibility from two numbers, and which remedies exist.

From a line to a curve: polynomial features

Linear regression (P3.A2) predicts with a straight line, y^=w0+w1x\hat{y}=w_0+w_1x. If the real pattern bends, a line misses it however well you fit it. The cure is to give the model more terms. A polynomial of degree dd is

y^=w0+w1x+w2x2+⋯+wdxd.\hat{y}=w_0+w_1x+w_2x^2+\dots+w_dx^d .

It has d+1d+1 weights. Degree 0 is a flat line (one number, the mean), degree 1 a slanted line, degree 2 a parabola, and so on. Each extra degree lets the curve bend up to one more time.

Here is the trick that makes this easy. Think of xx, x2x^2, … xdx^d as separate input columns, called features. Build a table with one row per example and one column per feature, starting with a column of ones for w0w_0. For the four points x=0,1,2,3x=0,1,2,3 and degree 2:

Φ=(100111124139)y^=Φw.\boldsymbol{\Phi}=\begin{pmatrix}1&0&0\\1&1&1\\1&2&4\\1&3&9\end{pmatrix}\qquad \hat{\mathbf{y}}=\boldsymbol{\Phi}\mathbf{w}.

Row 3 says: the prediction at x=2x=2 is w0⋅1+w1⋅2+w2⋅4w_0\cdot1+w_1\cdot2+w_2\cdot4. Now the model is a matrix times a vector of weights, which is exactly the form of linear regression. The targets here are y=(1,0,1,4)\mathbf{y}=(1,0,1,4), and least squares (the projection of P1.B11) gives w=(1,−2,1)\mathbf{w}=(1,-2,1), so y^=1−2x+x2=(x−1)2\hat{y}=1-2x+x^2=(x-1)^2, with squared error 0 because the four points were chosen on that parabola.

The word “linear” in linear regression always meant linear in the weights, not in xx. A model such as w0+w1x+w2x2w_0+w_1x+w_2x^2 qualifies. A model such as sin⁡(w1x)\sin(w_1x) does not, because w1w_1 sits inside the sine, and that kind of model needs an iterative method such as gradient descent (P1.F3).

Training error never rises with the degree

We now fit degrees 0 to 5 to the six training points of P0.2 (the numbers are made up for teaching) and measure the mean squared error on those points and on the six new points. Here error means MSE, the average squared miss (P3.A2). The Try it section lets you run the code.

  • Degree 0 (flat): training error 2.252, new-point error 2.061
  • Degree 1 (line): training 0.359, new 0.286
  • Degree 2: training 0.359, new 0.289
  • Degree 3: training 0.311, new 0.533
  • Degree 4: training 0.309, new 0.601
  • Degree 5: training 0.000, new 8.565

The training column never goes up. Degrees 1 and 2 tie to three decimals (0.359), and the exact values are 0.35879 and 0.35871. The new-point column goes down, then up, and ends at 8.565. These are the numbers from P0.2: the straight line’s 0.29 and the wiggly curve’s 8.6.

The training column has to behave like that, and the reason is a one-line argument. Every degree-(d−1)(d-1) polynomial is also a degree-dd polynomial, one whose top weight wdw_d is zero. The models are nested: each family contains the one before it. Least squares picks the best member of the family, and the best of a bigger set cannot be worse than the best of a smaller set. So the training error cannot rise when the degree grows. (This is about the exact best fit; a badly conditioned numerical solve can wobble by a rounding error.)

The error on new points has no such guarantee. The extra flexibility is spent on whatever the training points contain, and part of that is noise, which does not repeat on new points. That is why we never judge a model by its training error.

Try the degree slider

The data in the widget is made up: 10 training points generated from a known curve, y=sin⁡(2πx)y=\sin(2\pi x), plus random noise with spread 0.3 (so a squared error of about 0.32=0.090.3^2=0.09 is the unavoidable floor). Another 30 test points came from the same recipe. The test points are held out: they are never used to fit the curve, only to measure it. The curve is fitted by least squares on the training points alone.

00.20.40.60.81−2−1012xy

● training points (the model learns from these), ■ test points (held out, used only to measure), — fitted curve, - - true curve (the model never sees it).

With 10 points, degree 9 is the highest degree with a single best fit.

weights: 4
training error: 0.061
test error: 0.091

Lowest test error of all degrees on this sample (0.091). The training error is 0.061. The noise level is about 0.09, the best any model can do on noisy points.

0.010.111010010000123456789degreeerror (log scale)

● training error, ■ test error, dashed line: noise level 0.09, blue line: current degree, green ring: lowest test error (degree 3). Tap the chart to pick a degree. Errors below 0.01 are drawn on the bottom line.

Degree slider. Pink circles are the training points, green squares the held-out test points, the blue curve is the fitted polynomial (cut off at the chart edges where it leaves the plot), and the grey dashed curve is the true pattern, which the model never sees. The chart below the readouts shows training and test error at every degree on a log scale, with the current degree marked in blue and the lowest test error ringed in green. Use the slider or tap the chart. 'New sample' draws fresh points; '40 training points' adds 30 more points to the same 10.

Things to try, in order:

  1. Start at degree 0, then raise it one step at a time. Both errors drop sharply at degree 1 and again at degree 3, where the curve can follow the S-shape. On the starting sample, degree 3 has the lowest test error.
  2. Keep raising it to 9. The pink training error falls to exactly 0, while the green test error shoots up. The curve is forced through every training point and swings wildly between them. For this sample it reaches about 56 between the points, which is far outside the chart.
  3. Press New sample a few times. The exact numbers change, but the shape stays: training error falls steadily, test error is high, dips, and rises.
  4. Switch to 40 training points and go back to degree 9. The curve is calm and the test error is low. We come back to this below.

Underfitting and overfitting

The two failures have exact definitions in terms of two numbers: the training error and the test error (the error on held-out points).

  • Underfitting. The model is too simple for the pattern. Both the training error and the test error are high, and they are close to each other. Degree 0 and degree 1 in the widget do this: a flat line or a slanted line cannot follow the S-shape.
  • Overfitting. The model is flexible enough to fit the noise of the training points. The training error is low and the test error is much higher: a large gap between them. Degree 9 with 10 points does this.
  • A good fit. The test error is as low as the model family can reach, and close to the noise floor. The training error is a little lower than the test error, which is normal because the weights were chosen to suit those exact points.

“High” and “low” need a yardstick. In the widget we know the noise floor, 0.09. With real data you do not, so you compare with a simple baseline (always predict the mean), with other models, with the best error reached by any degree, or with what the application needs. The pair of numbers still tells the story: a gap between test and training error points to overfitting, and both high points to underfitting.

A fitted model has no idea what is signal and what is noise. It only sees yy values. Overfitting is the model treating a random bump in one yy value as part of the pattern.

Why degree N−1N-1 goes through NN points

Take NN points with different xx values. A polynomial of degree N−1N-1 has NN weights. Putting the NN points into the model gives NN equations in NN unknown weights, a square system (P1.B9), and when the xx values differ the system has exactly one solution. So one polynomial of degree N−1N-1 passes through all the points, and its training error is 0. In the widget, 10 points and degree 9 give this.

That exact fit is a fact about counting, not about the data: it works for any yy values, including pure noise. Because it would fit anything, it says nothing about the pattern. With NN points and a degree above N−1N-1, even more curves pass through the points (the system has more unknowns than equations), so a fit is not unique and a least-squares routine picks the one with the smallest weights. That is why the widget stops at degree 9 for 10 points.

A degree below N−1N-1 usually leaves some training error, because the data does not lie exactly on a low-degree curve. Part of the leftover error is noise the model refused to chase (and, for a model that is too simple, part is pattern it cannot follow).

Go deeper Why a model with zero training error can be so wrong between the points

Fix the xx values and move one yy by a small amount. A low-degree fit shifts a little. The degree N−1N-1 curve has to pass through the moved point, and with the other N−1N-1 points holding it in place, it can only do so by bending sharply nearby and swinging in the gaps. Its output is therefore very sensitive to the noise in each yy. In P3.A5 this sensitivity is called variance. On the sample in the widget, the degree-9 fit has weights in the hundreds (in the centred variable t=2x−1t=2x-1), the largest about 1,200 in size, compared with about 1 for the line, and the curve reaches about 56 between points even though all the targets are between about −1.0-1.0 and 1.11.1.

Capacity: how much a model can fit

The word for “how flexible a family of models is” is capacity. A polynomial’s capacity grows with its degree, and in this lesson it is measured by the number of weights, d+1d+1. Low capacity risks underfitting, high capacity risks overfitting, and the best capacity depends on how much data there is and how noisy it is.

Capacity is a general idea. The knob that sets it differs by model:

  • polynomial: the degree
  • decision tree: the maximum depth (P3.B3)
  • k-nearest neighbours: a small kk means high capacity (P3.B1)
  • neural network: the number of layers and units (Part 4)

The number of weights is a good guide inside one family, but it is not a complete measure of capacity across families.

More data lets the same model overfit less

Overfitting is a pairing of flexibility and a small amount of data: noise matters when there are few points to average it out. With the same degree-9 curve but more points, a single noisy point has less pull on the curve.

The widget shows it. On the starting sample, degree 9 has test error 7.1 with 10 points. Switch to 40 points and the same degree has training error 0.054 and test error 0.107, close to the noise floor. More data does not repair a model that is too simple, though: the degree-1 line cannot bend, however many points you give it (table below).

A plot of training and test error against the number of training points is called a learning curve. For one degree, the two curves move toward each other as the data grows. A small gap with both errors high means underfitting; a large gap that shrinks as data grows means overfitting. P4.22 reads the related loss curves (loss against training steps) of neural networks. Medians over 300 resamples of this recipe:

Median error (300 resamples)TrainingTest
Degree 1, 10 points0.2580.301
Degree 1, 40 points0.2720.297
Degree 3, 10 points0.0540.124
Degree 3, 40 points0.0830.104
Degree 9, 10 points0.00014.391
Degree 9, 20 points0.0410.291
Degree 9, 40 points0.0660.125

The line stays stuck near 0.30 however much data it gets. Degree 3 approaches the noise floor of 0.09 from both sides. Degree 9 goes from a huge test error to one close to degree 3’s.

Notice how the training error of degree 9 rises as data is added. More points mean there are more noisy values the curve can no longer all hit. A training error that is a little higher with more data is healthy.

Numerical problems at high degree

There is a second, separate way for a high degree to go wrong: arithmetic. The columns x,x2,x3,…x,x^2,x^3,\dots look more and more alike. On [0,1][0,1], x8x^8 and x9x^9 are both tiny for most of the range and shoot up together near 1, so one column can nearly be written as a combination of the others. The table Φ\boldsymbol{\Phi} is then ill-conditioned: it has a huge condition number (P1.B9), and tiny rounding errors turn into huge errors in the weights.

The effect is worst for raw xx values that are far from zero. Take xx as the years 1990 to 2020 and fit a cubic. The condition number of Φ\boldsymbol{\Phi} is about 1.2×10171.2\times10^{17} with raw years. NumPy’s 64-bit numbers keep about 16 digits, so the columns are, to the computer, almost exactly combinations of each other, and the fit is no longer reliable. Subtracting the centre and dividing by the spread, t=(x−2005)/15t=(x-2005)/15, brings it down to 7.7. Two habits prevent most of this:

  • Centre and scale xx before building the powers (P3.A11 teaches scaling for all features). The widget uses t=2x−1t=2x-1.
  • Solve with a least-squares routine such as np.linalg.lstsq, which uses an orthogonal factorization, and not by forming Φ⊤Φ\boldsymbol{\Phi}^\top\boldsymbol{\Phi} and inverting it. Forming it squares the condition number: for degree 12 on [0,1][0,1] the condition number of Φ\boldsymbol{\Phi} is 1.7×1041.7\times10^4 and that of Φ⊤Φ\boldsymbol{\Phi}^\top\boldsymbol{\Phi} is 2.8×1082.8\times10^8.

The Try it section prints these numbers. High-degree numerical trouble and overfitting are different problems: a well-conditioned degree-9 fit through noisy points still overfits.

Go deeper A better basis than powers of x

Powers of xx are not the only choice of features. Chebyshev or Legendre polynomials span the same set of curves, so the fitted curve is the same, but their columns are far less alike. For 40 evenly spaced points on [−1,1][-1,1], the condition number of the Chebyshev table stays between 2 and 2.5 from degree 3 to 12, against 7.87.8 to 1.7×1041.7\times10^4 for powers. NumPy’s np.polynomial.Polynomial.fit maps your xx onto [−1,1][-1,1] for you. Scaling and a good basis change the arithmetic only, not what the model can fit or whether it overfits.

What to do about overfitting (and underfitting)

Diagnose first with the two errors, then pick a remedy:

  • Both errors high (underfitting). Give the model more capacity (a higher degree, more features) or better features. More data alone will not help.
  • Large gap (overfitting). Get more data if you can. Or lower the capacity: a smaller degree, fewer features.
  • Keep the flexible model but tame it: regularization. Add a penalty for large weights, so that a wild curve with weights in the thousands costs more than a gentle one (P3.A6). Neural networks have their own versions: weight decay, dropout and early stopping (P4.17).
  • Choose the degree honestly. Training error always picks the highest degree. Compare degrees on a validation set held out from training, then report the error once on a separate test set (P3.A4). If you pick the degree by looking at the test error, the test error stops being an honest estimate of performance on new data.

Two warnings go with these:

  • Test error is itself an estimate. The widget’s 30 test points are a small sample, so its test error moves from sample to sample, and a difference of 0.01 between two degrees means nothing.
  • A curve that fits well inside the data range can be absurd outside it. On the widget’s starting sample, the degree-9 fit predicts about 5,700 at x=1.2x=1.2, while the true pattern gives 0.95. Even the cubic gives 4.2 there. A polynomial model describes the range its data covers, not what lies beyond it.

Where this leads

Two later lessons put numbers on what you have seen. Bias is the error from being too simple (underfitting), and variance is the sensitivity to noise in the training points (overfitting). P3.A5 splits the test error into these two parts plus the noise floor, and explains why the curve is U-shaped on average.

Go deeper Do very large models always overfit more? A hedged preview of double descent

The U-shaped picture of this lesson is the classical one for models whose size is raised until they can just fit the training data. In some modern settings, mainly large neural networks and some linear models with many more features than examples, researchers have measured test error that rises near the point where the model can fit the training data exactly and then falls again as the model grows further. This is called double descent (Belkin and co-authors, 2019; Nakkiran and co-authors, 2019). Whether it shows up depends on the model, the data, the noise and how training stops, and it does not make the classical rules of this lesson wrong: you still need held-out data to know. P4.24 covers it. For the degree range in this lesson (up to N−1N-1 points) you will see only the classical U.

Depth: three ways to see it

Intuition

Imagine two students before an exam. One memorises last year’s papers word for word, including the typing mistakes. The other learns the subject. On last year’s papers the first student scores 100%. On a new paper with different questions, the second student wins. The memoriser is the degree-9 curve and last year’s papers are the training points. The analogy breaks in one place: a curve does not decide to memorise. Least squares simply gives it the weights that match the training points most closely, and a flexible model has the freedom to match the noise too.

Math

Model: y^=∑j=0dwjxj=ϕ(x)⊤w\hat{y}=\sum_{j=0}^{d}w_jx^j=\boldsymbol{\phi}(x)^\top\mathbf{w} with ϕ(x)=(1,x,…,xd)\boldsymbol{\phi}(x)=(1,x,\dots,x^d). For NN examples, y^=Φw\hat{\mathbf{y}}=\boldsymbol{\Phi}\mathbf{w} with Φij=xi j\Phi_{ij}=x_i^{\,j} (a Vandermonde matrix).

Loss: L(w)=1N∥Φw−y∥2\mathcal{L}(\mathbf{w})=\frac1N\lVert\boldsymbol{\Phi}\mathbf{w}-\mathbf{y}\rVert^2. It is a convex quadratic in w\mathbf{w}. Its minimizers satisfy the normal equations Φ⊤Φw=Φ⊤y\boldsymbol{\Phi}^\top\boldsymbol{\Phi}\mathbf{w}=\boldsymbol{\Phi}^\top\mathbf{y} (P3.A2), and numerically one solves min⁡w∥Φw−y∥\min_{\mathbf{w}}\lVert\boldsymbol{\Phi}\mathbf{w}-\mathbf{y}\rVert by QR or SVD, because κ(Φ⊤Φ)=κ(Φ)2\kappa(\boldsymbol{\Phi}^\top\boldsymbol{\Phi})=\kappa(\boldsymbol{\Phi})^2 (P1.B9).

Nesting: H0⊂H1⊂…\mathcal{H}_0\subset\mathcal{H}_1\subset\dots, so min⁡HdLtrain≤min⁡Hd−1Ltrain\min_{\mathcal{H}_d}\mathcal{L}_{\text{train}}\le\min_{\mathcal{H}_{d-1}}\mathcal{L}_{\text{train}}.

Interpolation: for distinct x1,…,xNx_1,\dots,x_N the square Vandermonde matrix with d=N−1d=N-1 has determinant ∏i<j(xj−xi)≠0\prod_{i<j}(x_j-x_i)\neq0, so Φw=y\boldsymbol{\Phi}\mathbf{w}=\mathbf{y} has exactly one solution.

Noise floor: if y=f(x)+εy=f(x)+\varepsilon with E[ε]=0\mathbb{E}[\varepsilon]=0 and Var(ε)=σ2\mathrm{Var}(\varepsilon)=\sigma^2, the best possible test MSE is σ2\sigma^2, reached only by ff itself.

Code

import numpy as np
from numpy.polynomial import Polynomial

x = np.linspace(0, 1, 10)
y = np.sin(2 * np.pi * x) + 0.3 * np.random.default_rng(0).normal(size=10)

# Build the features yourself, then solve least squares
Phi = np.vander(2 * x - 1, 4, increasing=True)      # columns 1, t, t^2, t^3
w, *_ = np.linalg.lstsq(Phi, y, rcond=None)

# Or let NumPy centre and scale x for you
p = Polynomial.fit(x, y, deg=3)

With scikit-learn the same model is a pipeline of two steps. This block is shown, not run in the browser (scikit-learn is not available there). It was run on the six points of P0.2, and it printed a training error of 0.311 and a new-point error of 0.533, the same degree-3 numbers as above:

from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
from sklearn.linear_model import LinearRegression

model = make_pipeline(StandardScaler(),
                      PolynomialFeatures(degree=3, include_bias=False),
                      LinearRegression())
model.fit(x_train.reshape(-1, 1), y_train)

Try it

Three cells, all NumPy only. The first reproduces the table above from the six points of P0.2. The second draws its own data from the same recipe as the widget (its random numbers differ, so its figures differ a little from the widget’s) and shows degree 9 at three data sizes. The third prints the condition numbers of this lesson.

Try it: P0.2's six points, degrees 0 to 5

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Try it: more data, same degree

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Try it: why centring x matters

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Try these changes: in the second cell, add 100 to the list of sizes and see how little the degree-9 error improves after a point (it approaches the noise floor, 0.09). In the first cell, change range(6) to range(7): what does lstsq do with six points and seven weights? (It still returns weights: the smallest ones that fit exactly.)

Common mistakes

Quiz

Check your understanding

  1. You fit polynomials of degree 4 and degree 5 to the same training points by least squares. Which statement is always true about the training errors?

  2. A model has a training error of 0.02 and a test error of 3.5. The noise level of the data is about 0.09. What is the best description?

  3. Training error 0.55 and test error 0.60 for a degree-0 model, when the best degree reaches a test error of 0.09. What is going on and what helps?

  4. Why do we compute t=(x−2005)/15t=(x-2005)/15 from years xx before building the columns 1,t,t2,t31,t,t^2,t^3?

  5. You have 12 noisy points and want a polynomial that predicts well on new points. Which approach is a bad idea?

Exercises

  1. Write the table Φ\boldsymbol{\Phi} for x=(1,2,3)x=(1,2,3) and a polynomial of degree 2. How many weights are there? With how many points that have different xx values is a degree-2 polynomial no longer guaranteed to fit every set of yy values exactly?
    Show answerThe rows are (1,1,1)(1,1,1), (1,2,4)(1,2,4) and (1,3,9)(1,3,9). There are 3 weights, so a degree-2 polynomial can pass exactly through any 3 points with different xx. With 4 or more points it can do so only if the points happen to lie on a parabola, as in the example x=0,1,2,3x=0,1,2,3 with y=(1,0,1,4)y=(1,0,1,4).
  2. A model with polynomial features of pp inputs and total degree at most dd has (d+pp)\binom{d+p}{p} weights. How many weights for p=2p=2, d=2d=2 and for p=10p=10, d=3d=3?
    Show answer(42)=6\binom{4}{2}=6 (the features 1,x1,x2,x12,x1x2,x221,x_1,x_2,x_1^2,x_1x_2,x_2^2) and (133)=286\binom{13}{3}=286. The number of weights, and therefore the capacity, grows quickly with the number of inputs, so polynomial features overfit easily when there are many inputs.
  3. You have 7 points with different xx values. What is the training error of the degree-6 least-squares polynomial, and why?
    Show answer0 (up to rounding). Degree 6 has 7 weights, and the 7×77\times7 table of powers has a unique solution when the xx values differ, so one polynomial passes through all 7 points.
  4. A degree-3 model has training error 0.30 and test error 0.31, and the noise level is 0.09. Is this overfitting? What would you try?
    Show answerNo: there is no gap, and both errors are well above the noise level. That is underfitting for this feature set. Try more capacity (a higher degree), better features, or less regularization if there is any. More data would not help much.
  5. In the widget, set 10 points, degree 9, and press New sample five times. Record the test errors. Then set 40 points and repeat. What do you see?
    Show answerWith 10 points the degree-9 test error is usually many times the best degree’s test error (the median over 300 samples is 14.4), and it varies enormously from sample to sample; occasionally a sample is mild. With 40 points it is much lower and steadier (median 0.125, near the noise level of 0.09). The exact values depend on the samples.
  6. Explain in one or two sentences why a degree-9 fit to 10 points cannot tell you anything about whether the data has a pattern.
    Show answerIt would pass exactly through any 10 points with different xx values, even pure noise, so a training error of 0 is guaranteed whatever the data holds. Only error on held-out points can show whether there is a pattern.

Next: P3.A4 sets up the training, validation and test split so you can choose capacity honestly, P3.A5 explains the U-shape as bias and variance, and P3.A6 shows regularization.

Key takeaways

  • Polynomial regression builds the features 1, x, x², …, x^d and fits their weights by least squares. The model is curved in x but linear in the weights, so everything from linear regression (the loss, the normal equations, lstsq) applies unchanged.
  • The degree-d models contain the degree-(d−1) models (set the top weight to 0), so the best training error can only fall or stay the same as the degree grows. Training error alone therefore always prefers the most flexible model.
  • Underfitting means the model is too simple for the pattern: training and test error are both high. Overfitting means the model has fitted noise: training error is low and test error is much higher. Only error on held-out points can show the difference.
  • With N points that have different x values, a polynomial of degree N−1 passes through all of them (training error 0). On the made-up data of this lesson (10 points, noise level 0.09) its test error is typically many times the best test error; in the widget sample it is 7.1 against 0.09.
  • More data lets the same flexible model overfit much less (degree 9: typical test error about 14 with 10 points and about 0.13 with 40), but it does not cure underfitting. Other remedies are a simpler model, regularization (P3.A6), and choosing the degree on validation data (P3.A4).
  • Powers of a raw x make nearly parallel columns with a huge condition number (years 1990 to 2020, degree 3: about 1e17). Centre and scale x first, and solve with a least-squares routine, not the normal equations.
Found a mistake? Tell us