Velamuvi AIAcademy

Lesson 4 of 12 · The Setup

Generalisation

Will your model work on new data? Measure generalisation with validation and learning curves, see why test scores vary, and what happens when new data differs.

  • 13 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • Define generalisation and the generalisation gap
  • Use a validation curve to choose how complex a model should be
  • Use a learning curve to see whether more data would help
  • Treat a test score as an estimate that varies from split to split
  • Recognise when new data differs from the training data, and what that does to a model

The idea in plain words

A model is only useful if it does well on examples it has never seen. That ability is called generalisation. In Introduction to Machine Learning you saw what goes wrong when a model underfits or overfits, and the bias-variance trade-off behind it. This lesson gives you the tools to measure generalisation in scikit-learn, to diagnose what limits it, and to recognise the situations where no test score can protect you.

How well a model generalises depends on three things, and the sections below take them in turn:

  1. How flexible the model is: a model that can bend too much fits the noise.
  2. How much data it learns from: noise averages out over many examples.
  3. Whether new data looks like the training data: a model only knows the world it was shown.

Dial 1: how complex the model is

The program below trains decision trees of eight different depths. The data has 600 examples, and 10% of the labels were deliberately made wrong (flip_y=0.1), as happens with real labels. validation_curve runs 5-fold cross-validation for every depth, which means 40 trees in total:

Try it yourselfPython
from sklearn.datasets import make_classification
from sklearn.model_selection import validation_curve
from sklearn.tree import DecisionTreeClassifier

# 600 examples; 10% of the labels are deliberately noisy
X, y = make_classification(n_samples=600, n_features=10, n_informative=4,
                           flip_y=0.1, random_state=0)

depths = [1, 2, 3, 4, 6, 8, 12, 16]
train, valid = validation_curve(DecisionTreeClassifier(random_state=0), X, y,
                                param_name="max_depth", param_range=depths, cv=5)

print("depth  train  validation  gap")
for d, t, v in zip(depths, train.mean(axis=1), valid.mean(axis=1)):
    print(f"{d:>5}  {t:5.2f}  {v:10.2f}  {t - v:4.2f}")
Output
depth  train  validation  gap
    1   0.72        0.72  0.00
    2   0.77        0.75  0.02
    3   0.86        0.83  0.03
    4   0.92        0.86  0.05
    6   0.95        0.87  0.08
    8   0.98        0.86  0.12
   12   1.00        0.85  0.15
   16   1.00        0.85  0.15

Read it from top to bottom:

  • Depths 1 and 2 underfit. Training and validation scores are both low and close together: the model is too simple to capture the pattern.
  • Depth 6 has the best validation score (0.87).
  • From depth 12 the trees score 1.00 on training data, which means they also learned every one of the deliberately wrong labels. Validation drops to 0.85 and the gap grows to 0.15. This is the effect you saw in Learning From Labels: a flexible model faithfully memorises noise.

The training score keeps rising with depth, so it would always pick the deepest tree. Only the validation score shows where the sweet spot is. When several settings score about the same, prefer the simplest one: it has a smaller gap, so it is less likely to disappoint on new data.

There is a third dial besides complexity and data: regularisation, a penalty inside the model that discourages complexity, such as C in LogisticRegression or alpha in Ridge. The Linear Models lesson shows it in action; you choose it with a validation curve in exactly the same way.

Dial 2: how much data

Now fix the model (a tree of depth 8) and vary the number of training examples, from 50 to 1,600:

Try it yourselfPython
from sklearn.datasets import make_classification
from sklearn.model_selection import learning_curve
from sklearn.tree import DecisionTreeClassifier

X, y = make_classification(n_samples=2000, n_features=10, n_informative=4,
                           flip_y=0.1, random_state=0)

sizes, train, valid = learning_curve(DecisionTreeClassifier(max_depth=8, random_state=0),
                                     X, y, train_sizes=[50, 100, 200, 400, 800, 1600], cv=5)

print("training rows  train  validation  gap")
for n, t, v in zip(sizes, train.mean(axis=1), valid.mean(axis=1)):
    print(f"{n:>13}  {t:5.2f}  {v:10.2f}  {t - v:4.2f}")
Output
training rows  train  validation  gap
           50   1.00        0.54  0.46
          100   1.00        0.63  0.37
          200   0.97        0.69  0.28
          400   0.96        0.72  0.24
          800   0.94        0.78  0.16
         1600   0.92        0.81  0.11

With 50 examples the tree memorises its training data perfectly (1.00) and scores just 0.54 on new data, barely better than tossing a coin. As the data grows, memorising gets harder (the training score falls to 0.92), the validation score climbs to 0.81 and the gap shrinks from 0.46 to 0.11. The validation score is still rising at 1,600 rows, so more data would probably help further.

What the learning curve showsDiagnosisWhat helps
Both scores low and close togetherUnderfittingA more flexible model, or better features
Training high, validation much lower and still risingOverfitting that more data can fixMore data; meanwhile a simpler model or more regularisation
Validation has flattened outMore data won't help muchBetter features or a different kind of model

A test score is an estimate

Even a well-chosen test score is only an estimate of how the model will perform, and it depends on which examples happened to land in the test set. The program below tests the same model on ten different random test sets from the breast tumour dataset you met in Learning From Labels:

Try it yourselfPython
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score, train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

X, y = load_breast_cancer(return_X_y=True)
model = make_pipeline(StandardScaler(), LogisticRegression())

# The same model, tested on ten different random 20% test sets
scores = []
for seed in range(10):
    X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.2, random_state=seed)
    scores.append(model.fit(X_tr, y_tr).score(X_te, y_te))
print("ten test scores:", [round(s, 3) for s in scores])
print(f"lowest {min(scores):.3f}, highest {max(scores):.3f}")

cv = cross_val_score(model, X, y, cv=5)
print(f"5-fold cross-validation: {cv.mean():.3f} +/- {cv.std():.3f}")
Output
ten test scores: [0.965, 0.974, 0.974, 0.974, 0.965, 0.974, 0.991, 0.982, 0.982, 0.982]
lowest 0.965, highest 0.991
5-fold cross-validation: 0.981 +/- 0.007

Nothing about the model changed, yet its test accuracy ranged from 0.965 to 0.991. Each test set holds 114 tumours, so a single example is worth almost a full percentage point. If two models differ by one point on one split, that may be pure luck.

Cross-validation helps twice: the mean of the five folds (0.981) is steadier than any single split, and the spread across folds (the standard deviation, 0.007) tells you how much the score wobbles. Report both, and be wary of differences between models that are smaller than the spread.

When new data is different

Everything above assumes that new data comes from the same source as the training data. When it doesn't, the validation score can be badly wrong. The program below trains on homes of 50 to 150 m², then tests on similar homes and on homes of 200 to 300 m²:

Try it yourselfPython
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error
from sklearn.tree import DecisionTreeRegressor

rng = np.random.RandomState(0)
def houses(n, smallest, largest):
    size = rng.uniform(smallest, largest, size=n)            # square metres
    price = 50 + 3 * size + rng.normal(0, 20, size=n)        # thousands
    return size.reshape(-1, 1), price

X_train, y_train = houses(300, 50, 150)      # training data: small and medium homes
X_same, y_same = houses(100, 50, 150)        # new homes like the training ones
X_big, y_big = houses(100, 200, 300)         # new homes much bigger than any in training

for model in [DecisionTreeRegressor(max_depth=4, random_state=0), LinearRegression()]:
    model.fit(X_train, y_train)
    same = mean_absolute_error(y_same, model.predict(X_same))
    big = mean_absolute_error(y_big, model.predict(X_big))
    print(f"{type(model).__name__:<21} MAE on similar homes {same:5.1f}   on bigger homes {big:6.1f}")

tree = DecisionTreeRegressor(max_depth=4, random_state=0).fit(X_train, y_train)
print("Tree's prices for 200, 250 and 300 m2:", tree.predict([[200], [250], [300]]).round(0))
Output
DecisionTreeRegressor MAE on similar homes  15.5   on bigger homes  303.4
LinearRegression      MAE on similar homes  15.5   on bigger homes   15.9
Tree's prices for 200, 250 and 300 m2: [492. 492. 492.]

On homes like the training ones, both models are equally good (an average error of 15.5 thousand). On the bigger homes, the tree's error explodes to 303.4 thousand. The last line shows why: a tree can only predict prices it saw during training, so every home above 150 m² gets the price of the largest training homes, 492 thousand, whether it is 200 m² or 300 m². Linear regression happens to cope, but only because the real relationship here is a straight line. With real data you rarely know that, so a model's predictions outside its training range should never be trusted blindly.

To protect against it, make the test set resemble the future (for example, split by time), check whether new inputs fall inside the range of the training data, and keep measuring the model after it goes live.

Common mistakes

Practice

Practice exercise

Several trees were trained with different depths. Pick the simplest one that generalises almost as well as the best, and report its gap.

Your solutionPython
# depth: (training accuracy, validation accuracy)
results = {2: (0.80, 0.79), 4: (0.88, 0.86), 6: (0.93, 0.865), 10: (0.99, 0.86), 20: (1.00, 0.84)}

# 1. Find the best validation accuracy.
# 2. Choose the SMALLEST depth whose validation accuracy is within 0.01 of the best.
# 3. Print it with its validation accuracy and its gap (training minus validation):
# Chosen depth: 6 (validation 0.865, gap 0.065)
best = 0
chosen = 6

train, valid = results[chosen]
print(f"Chosen depth: {chosen} (validation {valid}, gap {train - valid:.3f})")
Knowledge check

A learning curve shows a training score of 0.99 and a validation score that is still rising steadily as you add data. What is the most promising next step?

Summary

  • Generalisation is performance on new data; the generalisation gap is the difference between the training score and the score on new data.
  • A validation curve shows how complexity affects both scores: pick the best validation score, or the simplest setting that is almost as good.
  • A learning curve shows whether more data would help: a validation score that is still rising says yes.
  • A test score is an estimate that varies from split to split; report cross-validation's mean and spread.
  • Models generalise only to data like their training data. Under distribution shift, for example values outside the training range, a validation score can be badly misleading.

Next: Linear Models, the first family of supervised algorithms.

Finished reading? Tick it off to track your progress.