Skip to content

MLDay 10 of 50Supervised and Unsupervised Learning

Spot Overfitting with Cross-Validation

8 min read

A model can score almost perfectly on the rows it learned from and still miss badly on the next ones. It has memorized the noise. Its training error can't warn you, because it only grades answers the model has already seen.

The idea

A straight line can't bend, but many real patterns do. Polynomial features fix that: add x2x^2, x3x^3 and so on as extra columns, and linear regression gives each one a weight, so the fitted curve can bend. The degree is the highest power used. Degree 1 is a line, and degree 2 is a curve with one bend.

A higher degree gives the curve more freedom, and training error never goes up as the degree grows. That freedom cuts both ways:

  • Underfit: the model is too simple to follow the pattern, so it misses on training rows and new rows alike. This is high bias: it is wrong in the same way whatever rows you train it on.
  • Overfit: the model bends to chase the noise in its training rows. Training error is tiny, but error on new rows is large. This is high variance: train it on a different sample and you get a very different curve.

So you judge a model on rows it didn't train on, as in D06. But one held-out set is luck of the draw: with 20 rows, a 20% split scores the model on just 4 of them.

k-fold cross-validation (CV) uses every row. Cut the rows into kk equal parts, called folds. Train kk times; each time, hold out a different fold, train on the rest, and score on the fold you held out. Every row is scored exactly once. The mean of the kk scores is your estimate. Their spread shows how much that estimate depends on which rows the model happened to get.

A tiny example

The degree-2 features of x=3x = 3 are (3,9)(3, 9), because 32=93^2 = 9. At degree 3 they are (3,9,27)(3, 9, 27).

Now run 5-fold CV on 10 rows. Each fold holds 2 rows:

Round Scored on Trained on
1 rows 1–2 rows 3–10
2 rows 3–4 rows 1–2, 5–10
3 rows 5–6 rows 1–4, 7–10
4 rows 7–8 rows 1–6, 9–10
5 rows 9–10 rows 1–8

That's 5 trainings, each on 8 of the 10 rows (80%), and each row is scored once.

The formula

A polynomial model of degree dd is a weighted sum of powers of xx:

y^=w1x+w2x2+⋯+wdxd+b\hat{y} = w_1 x + w_2 x^2 + \dots + w_d x^d + b
Symbol Meaning
y^\hat{y} the prediction
xx the feature
dd the degree: the highest power of xx
wjw_j the weight of xjx^j, learned by fitting
bb the bias

Worked: d=2d = 2, w1=2w_1 = 2, w2=−0.5w_2 = -0.5, b=1b = 1 and x=3x = 3 give y^=2×3−0.5×9+1=2.5\hat{y} = 2 \times 3 - 0.5 \times 9 + 1 = 2.5.

The CV score is the average of the fold scores:

CV=1k∑i=1kEi\text{CV} = \frac{1}{k} \sum_{i=1}^{k} E_i
Symbol Meaning
kk the number of folds
EiE_i the error (here RMSE) on fold ii, from a model trained on the other k−1k - 1 folds

Worked: five fold RMSEs of 0.30, 0.25, 0.40, 0.35 and 0.20 give CV=1.50/5=0.30\text{CV} = 1.50 / 5 = 0.30.

Try it

How much should the tomato curve bend?

Round dots are the training points (the fit sees them); squares are validation points (held back). Raise the degree and watch both errors.

05102345Water per week (litres)Tomatoes per plant (kg)validation: x = 2, y = 3.2validation: x = 2.5, y = 3.3validation: x = 4.5, y = 4.6validation: x = 5, y = 4.3validation: x = 7, y = 4.6validation: x = 7.5, y = 4training: x = 0.5, y = 1.7training: x = 1, y = 1.9training: x = 1.5, y = 2.4training: x = 3, y = 2.7training: x = 3.5, y = 4.7training: x = 4, y = 4.7training: x = 5.5, y = 4.4training: x = 6, y = 4.9training: x = 6.5, y = 4.7training: x = 8, y = 4training: x = 8.5, y = 4.4training: x = 9, y = 3.6training: x = 9.5, y = 3.2training: x = 10, y = 2.7

degree 1train RMSE 0.99validation RMSE 0.67weights' size ‖w‖ 0.68

Fitted by least squares, with x rescaled to −1…1 first; ‖w‖ leaves out the intercept.

The curve is fitted to the 14 training points only. Start at degree 1, where both errors are high (train 0.99, validation 0.67), and find the degree with the lowest validation RMSE. Then drag to 12: train RMSE drops to 0.02 while validation climbs to 2.05.

In code

PolynomialFeatures makes the power columns. cross_val_score runs the folds (5 unless you say otherwise) and returns one score per fold. This grows 20 seeded tomato plants and tries every degree from 1 to 12.

# script_id: day_010_overfitting_and_cross_validation/degrees
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.metrics import root_mean_squared_error
from sklearn.model_selection import cross_val_score
from sklearn.preprocessing import PolynomialFeatures

rng = np.random.default_rng(0)
litres = rng.uniform(0, 10, size=(20, 1))                  # 20 plants, in random order
kg = 1 + 1.2 * litres[:, 0] - 0.1 * litres[:, 0] ** 2 + rng.normal(0, 0.4, 20)
x = (litres - 5) / 5                                       # rescale to -1..1 so x**12 stays small

folds = {}
for degree in range(1, 13):
    X = PolynomialFeatures(degree, include_bias=False).fit_transform(x)   # x, x², ..., x^degree
    train = root_mean_squared_error(kg, LinearRegression().fit(X, kg).predict(X))
    folds[degree] = -cross_val_score(LinearRegression(), X, kg, scoring="neg_root_mean_squared_error")
    print(f"degree {degree:2d}: train {train:.2f}   CV {folds[degree].mean():.2f} ± {folds[degree].std():.2f}")

print("degree 3 folds: ", folds[3].round(2))
print("degree 12 folds:", folds[12].round(2))
degree  1: train 0.86   CV 0.90 ± 0.31
degree  2: train 0.26   CV 0.29 ± 0.10
degree  3: train 0.22   CV 0.25 ± 0.04
degree  4: train 0.22   CV 0.26 ± 0.05
degree  5: train 0.20   CV 0.27 ± 0.06
degree  6: train 0.20   CV 0.28 ± 0.06
degree  7: train 0.19   CV 0.28 ± 0.05
degree  8: train 0.19   CV 0.34 ± 0.07
degree  9: train 0.19   CV 0.47 ± 0.13
degree 10: train 0.18   CV 0.61 ± 0.24
degree 11: train 0.17   CV 1.08 ± 1.16
degree 12: train 0.17   CV 1.53 ± 1.34
degree 3 folds:  [0.22 0.32 0.2  0.24 0.26]
degree 12 folds: [0.51 0.92 4.04 1.72 0.45]

Train error never goes up, from 0.86 down to 0.17. CV error falls to 0.25 at degree 3, then climbs to 1.53: a U-shape. Degree 1 underfits. Past degree 3 the CV error creeps up, and from degree 9 it climbs fast: the model overfits. The ± is the standard deviation of the five fold scores. At degree 3 the folds agree, from 0.20 to 0.32. At degree 12 one fold misses by 4.04: it holds the driest and the wettest plants, so the curve has to reach past its 16 training rows, and out there it swings wildly (7.7 kg too high at 9.35 litres). That is high variance, in numbers.

scikit-learn treats a bigger score as better, so it reports RMSE as a negative number; the minus sign in front of cross_val_score flips it back. Making the power columns before the folds leaks nothing, because PolynomialFeatures learns nothing from the rows.

Quick check

Quick check

1. A model has train RMSE 0.05 and CV RMSE 1.20. What is going on?

2. You run 5-fold cross-validation on 1,000 rows. How many models are trained, and on how many rows each?

3. A straight line gets train RMSE 0.86 and CV RMSE 0.90 on a curved pattern. What should you try?

Next

Cutting the degree isn't the only cure for overfitting: D11: Regularize with Ridge and Lasso keeps degree 12 and tames it by penalizing big weights.

Next · Day 11 · 8 minRegularize with Ridge and Lasso← Previous: Day 9 · Gradient Descent, and Why Scaling Matters
Not tapped yet