Chapter 10 — Lab: Model Evaluation and Training Control
Lab Overview¶
You will write the machinery behind KFold, StratifiedKFold and TimeSeriesSplit, run your own cross-validation, and build the two reflexes of a training loop: reading a loss curve and stopping early.
| Exercise | Topic | Points |
|---|---|---|
| 1 | k-fold indices | 15 |
| 2 | Cross-validation | 15 |
| 3 | Stratified folds | 20 |
| 4 | Time-series splits | 15 |
| 5 | Reading a loss curve | 15 |
| 6 | Early stopping with patience | 20 |
| Challenge | A paired comparison | +10 |
How it works. Each exercise has a function to complete where you see # TODO. Run the check cell under it: ✅ means your function is right, ❌ tells you what is wrong. Use NumPy and plain Python; scikit-learn appears only in the checks. Do not change the check cells.
import numpy as np
from sklearn.model_selection import KFold, TimeSeriesSplit
def check(name, test):
"""Run one self-check: test() must return True; any exception or False is reported."""
try:
ok = test()
except NotImplementedError:
print(f'❌ {name}: not implemented yet'); return
except Exception as e:
print(f'❌ {name}: {type(e).__name__}: {e}'); return
print(f'✅ {name}' if ok else f'❌ {name}: wrong result')
print('Setup complete.')Exercise 1: k-Fold Indices (15 points)¶
kfold(n, k) splits the indices 0 … n−1, in order, without shuffling, into k consecutive folds. The first n % k folds get one extra index (as scikit-learn’s KFold does). Return a list of k pairs (train_indices, val_indices) of NumPy arrays.
def kfold(n, k):
# TODO
raise NotImplementedErrorcheck('10 into 3: sizes 4, 3, 3', lambda: [len(v) for _, v in kfold(10, 3)] == [4, 3, 3])
check('the same folds as KFold', lambda: all(np.array_equal(a[1], b[1]) for a, b in zip(kfold(17, 5), KFold(5).split(np.zeros(17)))))
check('training and validation never overlap, and cover everything', lambda: all(set(t) | set(v) == set(range(12)) and not set(t) & set(v) for t, v in kfold(12, 4)))Exercise 2: Cross-Validation (15 points)¶
cross_val(score, n, k) calls score(train_indices, val_indices) for each fold of kfold(n, k) and returns (mean, standard deviation) of the scores (np.std, ddof=0).
The check uses it to cross-validate a polynomial fit on noisy sine data.
def cross_val(score, n, k):
# TODO
raise NotImplementedErrorrng = np.random.default_rng(0)
xs = rng.uniform(-1, 1, 60); ys = np.sin(np.pi * xs) + rng.normal(0, 0.25, 60)
def poly_mse(degree):
def score(tr, va):
w = np.polyfit(xs[tr], ys[tr], degree)
return np.mean((np.polyval(w, xs[va]) - ys[va]) ** 2)
return score
m1, _ = cross_val(poly_mse(1), 60, 5); m3, _ = cross_val(poly_mse(3), 60, 5)
check('constant scores give mean 1 and spread 0', lambda: cross_val(lambda tr, va: 1.0, 10, 5) == (1.0, 0.0))
check('the mean of fold sizes', lambda: cross_val(lambda tr, va: len(va), 10, 3)[0] == 10 / 3)
check('cross-validation prefers degree 3 to a line on a sine', lambda: m3 < m1)Exercise 3: Stratified Folds (20 points)¶
stratified_folds(y, k) returns a list of k arrays of validation indices. For each class, in sorted order, take that class’s indices in increasing order and deal them out to the folds in turn: the first to fold 0, the second to fold 1, …, the k-th to fold k−1, the next to fold 0 again. Return each fold’s indices sorted.
def stratified_folds(y, k):
# TODO
raise NotImplementedErrory_rare = np.array([0] * 18 + [1] * 2)
f = stratified_folds(y_rare, 2)
check('both positives are not in the same fold', lambda: sorted(y_rare[v].sum() for v in f) == [1, 1])
check('every index exactly once', lambda: sorted(np.concatenate(stratified_folds(np.arange(30) % 3, 4)).tolist()) == list(range(30)))
yb = (np.random.default_rng(1).random(200) < 0.1).astype(int)
shares = [yb[v].mean() for v in stratified_folds(yb, 5)]
check('each fold keeps the share of positives within 0.03', lambda: max(abs(s - yb.mean()) for s in shares) <= 0.03)Exercise 4: Time-Series Splits (15 points)¶
time_splits(n, n_splits) returns n_splits pairs (train_indices, val_indices) as scikit-learn’s TimeSeriesSplit does: each validation block has n // (n_splits + 1) rows; the last block ends at row n − 1; the blocks follow each other; each training set is every row before its validation block.
def time_splits(n, n_splits):
# TODO
raise NotImplementedErrorcheck('the same splits as TimeSeriesSplit(4) on 12 rows', lambda: all(np.array_equal(a[0], b[0]) and np.array_equal(a[1], b[1]) for a, b in zip(time_splits(12, 4), TimeSeriesSplit(4).split(np.zeros(12)))))
check('and on 23 rows with 5 splits', lambda: all(np.array_equal(a[1], b[1]) for a, b in zip(time_splits(23, 5), TimeSeriesSplit(5).split(np.zeros(23)))))
check('never trains on the future', lambda: all(t.max() < v.min() for t, v in time_splits(30, 3)))Exercise 5: Reading a Loss Curve (15 points)¶
diagnose(losses) returns, checked in this order:
'diverging'if any loss is not finite (np.isfinite) or the last loss is above the first;'stalled'if the last loss is above 90% of the first;'oscillating'if the loss went up on at least a third of the steps (a step is a pair of consecutive losses);'converging'otherwise.
def diagnose(losses):
# TODO
raise NotImplementedErrorcheck('a smooth decline', lambda: diagnose([1.0, 0.68, 0.51, 0.49, 0.486]) == 'converging')
check('a blow-up', lambda: diagnose([1.0, 0.88, 1.51, 38.4]) == 'diverging')
check('a NaN', lambda: diagnose([2.3, 1.1, 0.9, float('nan')]) == 'diverging')
check('barely moving', lambda: diagnose([1.0, 0.99, 0.98, 0.97]) == 'stalled')
check('up and down', lambda: diagnose([1.0, 0.6, 0.8, 0.5, 0.7, 0.4]) == 'oscillating')Exercise 6: Early Stopping with Patience (20 points)¶
early_stop(val_losses, patience) walks through the validation losses. It remembers the lowest loss and its epoch (a new minimum must be strictly lower). It stops at the first epoch that is patience epochs after the best one, and returns (best epoch, stop epoch), both counted from 0. If it never stops, the stop epoch is the last one.
def early_stop(val_losses, patience):
# TODO
raise NotImplementedErrorcurve = [1.0, 0.6, 0.4, 0.35, 0.36, 0.34, 0.37, 0.38, 0.39, 0.40]
check('patience 1 stops at the first uptick', lambda: early_stop(curve, 1) == (3, 4))
check('patience 2 survives it and finds epoch 5', lambda: early_stop(curve, 2) == (5, 7))
check('a curve that keeps falling never stops early', lambda: early_stop([5, 4, 3, 2, 1], 2) == (4, 4))
check('an equal value is not a new minimum', lambda: early_stop([1.0, 0.5, 0.5, 0.5], 2) == (1, 3))Question. Which patience would you choose for a validation loss measured on 50 examples, and which for one measured on 50 000? Why?
Challenge: A Paired Comparison (+10 points)¶
paired(a, b) takes the fold scores of two models on the same folds and returns (mean difference a − b, standard deviation of the differences, share of folds where a > b).
def paired(a, b):
# TODO
raise NotImplementedErrora = [0.95, 0.97, 0.96, 0.98, 0.94]; b = [0.94, 0.95, 0.96, 0.96, 0.93]
m, s, share = paired(a, b)
check('the mean difference', lambda: abs(m - 0.012) < 1e-9)
check('a wins 4 folds of 5', lambda: share == 0.8)
check('the spread of the differences is smaller than the spread of a', lambda: s < np.std(a))Lab Report¶
Submit this notebook with:
every check cell showing ✅,
your answer to the question of Exercise 6,
one paragraph: for a dataset you know, which splitter would you use (k-fold, stratified, group, time series), and why?