Train, validation and test

A model is judged on unseen designs only; the split is by design, never by point.

Outcome: Explain underfitting and overfitting with training and validation error; use a validation set for choices and a test set once; split by run, never by point, and use k-fold cross-validation on small data; hold out a whole kind of novelty (a geometry family, an enclosure, a boundary-condition layout, a Reynolds range) when the model will meet it.

Builds on Fitting a response surface

A surrogate exists to answer for new designs, and its error on the runs it was fitted to says little about that on its own. What counts is its generalisation.

DefinitionGeneralisation

The ability to predict well on new inputs. It is measured by keeping some runs out of the fit and comparing the model’s predictions with the solver there.

The slider of Figure 3-1 fits polynomials of growing degree to 10 noisy points and measures the error on 40 points it never saw, as the RMSE of the last lesson, in the units of the output.

-0.500.51-101input xoutput y
10 training pointsvalidation pointsfitted polynomial
0.010.11100123456789degreeRMSE
training RMSEvalidation RMSElog scale; zero is drawn on the axis

Error on the training points keeps falling as the degree rises; error on unseen points falls, then climbs. Degree 1: training RMSE 0.144, validation RMSE 0.187.

Figure 3-1. Training and validation error of polynomials of growing degree, fitted to 10 noisy points of a synthetic curve (not solver runs) and scored on 40 more.

At low degree the model is too simple to follow the curve, and both errors are high: underfitting. As the degree grows the training error keeps falling, but past some point the validation error rises again, because the polynomial bends to pass through the noise of each training point: overfitting. The best model sits at the bottom of the validation curve, not the training curve. A similar U-shape often appears with neural networks over training time, and there too the validation curve decides (see overfitting and regularisation).

Training, validation and test sets

Training runs fit the weights. Validation runs make the choices: the degree, the network size, when to stop training. Every choice uses them a little. Test runs stay aside until the very end and are used once, to report the error. If the model is changed after looking at them, they have become validation runs.

With few runs, holding out a third of them is costly. k-fold cross-validation splits the runs into kk groups (often 5), fits kk times, each time validating on a different group, and averages the kk errors. Every run is used for validation exactly once.

Splitting by run

Neighbouring points of the same run have almost the same value.

Held-out runs scattered inside the training range measure interpolation. A whole held-out region, such as every run above α\alpha 6°, shows how the model behaves beyond its data: an extrapolation test. Benchmarks such as AirfRANS publish both kinds of split.

The held-out runs should be as new as the problems the surrogate will meet. A random split of many morphs of one family tests interpolation within that family. If the model will meet a new family of geometries, an enclosure (open road, wind tunnel, duct), a layout of boundary conditions or a range of Reynolds number, that novelty is held out whole and the validation runs come from the training side only: the standard advice for data with groups or structure (Roberts et al. 2017). Held-out sets differ in size and difficulty, so models are compared only on the same split. Some benchmarks publish one split per kind of novelty, as AeroZoo does for geometry families, enclosures, boundary-condition layouts and Reynolds ranges.

The download’s split (from runs to arrays) was fixed before any training, with every fifth run of the Latin hypercube held out for validation.

Example 3-2. The course’s split, choosing the degree by cross-validation, and splitting by run, with scikit-learn
# Add to aircraft.py: the course's split, by run.
def split_runs(d):1
    """Run indices for training, validation and test, and a
    mask of the runs inside the training box."""
    s, a, w = d["split"], d["alpha"], d["sweep"]
    in_box = (a >= -2) & (a <= 8) & (w >= 20) & (w <= 36)
    return (np.flatnonzero(s == 0), np.flatnonzero(s == 1),
            np.flatnonzero(s == 2), in_box)

# Then, in a script:
import numpy as np
from sklearn.model_selection import (GroupShuffleSplit, KFold,
                                     cross_val_score)
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from aircraft import load_runs, split_runs

d = load_runs()
train, val, test, in_box = split_runs(d)
print(len(train), len(val), len(test), in_box[test].sum())
lhs = np.r_[train, val]  # the 44 Latin-hypercube runs
X = np.column_stack([d["alpha"], d["sweep"]])[lhs]
y = d["CL"][lhs]

# Small data: 5-fold cross-validation on whole runs,
# to choose the polynomial degree.
cv = KFold(5, shuffle=True, random_state=0)2
for degree in [1, 2, 3, 5, 8]:
    model = make_pipeline(PolynomialFeatures(degree),
                          LinearRegression())
    scores = cross_val_score(
        model, X, y, cv=cv,
        scoring="neg_root_mean_squared_error")3
    print(degree, f"validation RMSE {-scores.mean():.4f}")

# The point-wise table of all 56 runs: split by run id,
# so that no run lands on both sides. One id per row:
n_runs, n_pts = d["cp"].shape
run_id = np.repeat(np.arange(n_runs), n_pts)4
split = GroupShuffleSplit(n_splits=1, test_size=0.2,5
                          random_state=0)
rows = np.zeros(len(run_id))
tr, te = next(split.split(rows, groups=run_id))
print(len(set(run_id[te])), "test runs")
# set(): no run is shared.
print(set(run_id[tr]) & set(run_id[te]))
  1. split_runs packages the split of Example 3-1: the stored split column of Example 2-2 and the training box. The script’s first line prints 36 8 12 4: four of the test runs lie inside the box.
  2. shuffle=True deals the 44 runs into the 5 folds at random; without it, each fold would be a block of consecutive runs.
  3. scikit-learn maximises scores, so error metrics come with their sign flipped: the minus in the next line turns them back into an RMSE.
  4. One id per row: 2,000 rows for run 0, then 2,000 for run 1, and so on, as in the point-wise table of Example 2-2.
  5. With groups, test_size=0.2 is a share of the runs, not of the rows, rounded up: 12 of the 56 runs go to the test side, with all their points.

The cross-validated RMSE of Example 3-2 falls from 0.0061 at degree 1 to 0.0009 at degree 2 and 0.0001 at degree 3, then rises to 0.0079 at degree 5 and 0.1966 at degree 8, so the folds choose degree 3. The last line prints set(): no run is on both sides of the split.