Semester 1 · Week 10
Cross-validation and model selection
- Ch 13 Cross-Validation & Model Selection
+ Capstone modelling plan
Chapter 13: Cross-validation and model selection
Data used to make a decision can't also judge it.
Notes · slide 2
Time: 50 minutes. About 30 on the chapter, 10 on the worked example, and 5 to brief the capstone plan. The last 45 minutes of the session go to the plan itself, so the lab is shorter this week.
Say: A model scored on one 80/20 split reports one number, say 94%. A different split could give 91 or 97, and you can't tell which you got. Compare twenty models on that split and report the best, and the number is optimistic by construction.
Key line: data used to make a decision can't also judge it.
Next: the basic rule.
The basic rule
- Choosing hyperparameters, features, or algorithms on the test set uses it up.
- After that it no longer estimates performance on unseen data.
- Cross-validation splits the data many ways and averages.
There's no single best split. There's a distribution of performance.
Notes · slide 3
Say: Choose hyperparameters, features, or algorithms on the test set, and you've used it up. It no longer estimates performance on unseen data.
Say: Cross-validation splits the data many ways and averages. There's no single right split. There's a distribution of performance, and you want both its centre and its spread.
Ask: "You tried five feature sets and kept the one with the best test score. Is that score still honest?" Listen for: no. The test set took part in the choice.
Next: why one split isn't enough.
One split isn't enough
- 80/20 on 569 rows leaves 114 to test on.
- Which 114 land in the test set moves the score a lot.
- A model can look best or worst purely by chance.
Notes · slide 4
Say: 80/20 on 569 rows leaves 114 test rows. One or two hard cases in or out moves accuracy by a point or more. Which 114 you happen to get can make a model look best or worst by chance.
Key line: a single split is a sample of size one from the distribution of possible scores.
Next: k-fold.
k-fold cross-validation
- Split the data into k equal folds.
- Train on k−1 folds, validate on the last.
- Rotate until each fold has been the validation set.
- Report the mean and the spread.
k=5 is the usual default.
Notes · slide 5
Do: draw five boxes in a row on the board. Shade a different one as validation in each of five rows.
Say: Split into k folds. Train on k − 1, validate on the last. Rotate until every fold has been validation once. Every row is used for both training and validation.
Say: Report the mean and the spread. A tight spread and a wide spread around the same mean are different findings.
Say: k = 5 is the default. 10 gives slightly more training data per fold, at more compute.
Next: choosing the split.
Pick the split to match the data
| Situation | Strategy |
|---|---|
| Classification | Stratified k-fold: same class ratio in every fold |
| Regression | k-fold |
| Time-ordered data | TimeSeriesSplit: validate only on the future |
| Same subject in many rows | GroupKFold |
| Fewer than ~50 rows | Leave-one-out |
Notes · slide 6
Say: Classification: stratify, so every fold has the same class ratio. With 5% positives, a fold could otherwise have none. sklearn stratifies classifiers by default. Time-ordered data: TimeSeriesSplit. Several rows for one customer or patient: GroupKFold, so one person never sits in both training and validation. Very small data: leave-one-out.
Ask: "Medical images, several per patient. Which split?" Listen for: GroupKFold by patient. Otherwise the model can recognise the patient, not the disease.
Next: time series.
Time series: never shuffle
- Training on next week to predict this week leaks the future.
- The score looks great, then collapses in production.
TimeSeriesSplitkeeps every validation fold after its training data.
Notes · slide 7
Say: Shuffle time-ordered rows and you train on next week to predict this week. That leaks the future. The score looks great, then collapses in production.
Say: TimeSeriesSplit keeps every validation fold strictly after its training data. Training windows grow. Validation always looks ahead.
Key line: any sales, prices, sensors, or user behaviour over time: no shuffling.
Next: a subtler way to fool yourself.
Overfitting the test set
- Train fifty models.
- Score each on the same test set.
- Report the best one's score.
That number is optimistic. You selected on noise.
Notes · slide 8
Say: Train fifty models. Score each on the same test set. Report the best. That number is optimistic. The winning model isn't secretly worse. The selection favoured whichever one got lucky on those particular rows.
Ask: "Fifty coins, flipped ten times each. Report the coin with the most heads. Is it a biased coin?" Listen for: no, it's the luckiest of fifty fair coins.
Next: how to tune and still get an honest estimate.
Nested cross-validation
Two loops, two jobs:
- Inner loop (e.g. 3-fold): pick hyperparameters.
- Outer loop (e.g. 5-fold): estimate how well the whole procedure generalises.
Selection never sees the data it's judged on.
Notes · slide 9
Say: Two loops, two jobs. The inner loop, say 3-fold, picks hyperparameters using only the outer training data. The outer loop, say 5-fold, scores the result on data the inner search never saw.
Say: Different outer folds may pick different hyperparameters. That's fine. The outer loop estimates how well the whole tuning procedure generalises. It doesn't pick the model to ship.
Lab: nested CV is the hardest code in the semester. Have a working version ready to share.
Next: the most common leak.
The most common leak
Fitting a scaler or imputer on all the data, then cross-validating.
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
pipe = make_pipeline(StandardScaler(), LogisticRegression())
scores = cross_val_score(pipe, X, y, cv=5)A Pipeline refits preprocessing inside every fold.
Notes · slide 10
Say: Fit a scaler or imputer on all the data, then cross-validate. Each validation fold has already influenced the scaling. Scores come out optimistic, and nothing warns you.
Say: Put preprocessing in a Pipeline and cross-validate the whole pipeline. It refits the scaler inside every fold, on that fold's training rows only.
Key line: if it learns anything from data, it goes inside the pipeline.
Next: how many folds.
How many folds?
| Rows | Folds |
|---|---|
| Under 50 | Leave-one-out |
| 50–500 | 10 |
| 500–10,000 | 5 |
| Over 10,000 | 3, or a single split |
sklearn's regression scorers are negated, because it maximises. Flip the sign.
Notes · slide 11
Say: A rule of thumb by size. Under 50 rows, leave-one-out. 50 to 500, ten folds. 500 to 10,000, five. Over 10,000, three or a single split is usually enough. The estimate is already stable.
Say: A practical trap: sklearn's regression scorers are negative, because it always maximises. Negative MSE of −12 means MSE 12. Flip the sign before you report.
Say: To claim model A beats model B, compare matched fold scores with a paired test, not just two means (Procedure 13.5).
Next: the worked example.
Worked example: ten seeds
Same pipeline, same data, ten random 80/20 splits:
- Accuracy from 0.965 to 1.000.
- Each would look like a clean, confident result on its own.
5-fold stratified CV instead: folds of 0.982, 0.982, 0.974, 0.974, 0.991.
Mean 0.981, std 0.007. One number with an honest error bar.
Notes · slide 12
Say: Same pipeline, same data, ten random 80/20 splits. Accuracy from 0.965 to 1.000. Any one of them, reported alone, would look like a clean result.
Say: 5-fold stratified CV: mean 0.981, standard deviation 0.007. One number with an honest error bar.
Lab: learners plot 50 seeds. That plot is the moment the week lands. Put one learner's plot on the screen.
Next: nested CV on the same data.
Worked example: nested CV
Tune a random forest with a 3-fold inner search inside a 5-fold outer loop.
- Non-nested estimate: 0.9543.
- Nested estimate: 0.9543.
No gap here. On easier data with a small search, the bias can be tiny. The only way to know is to run it.
Notes · slide 13
Say: Tune a random forest with a 3-fold inner search inside a 5-fold outer loop. The non-nested estimate is 0.9543. The nested estimate is 0.9543. No gap.
Key line: the gap depends on how separable the data is and how much you searched. On easy data with a small search it can be tiny. The only way to know is to run it.
Ask: "When would you expect a big gap?" Listen for: small, noisy data and a large search space.
Next: your capstone plan.
Capstone: your modelling plan
The last 45 minutes are for your capstone. Write one page:
- CV scheme. Stratified, grouped, or time-based? What could leak?
- Main metric. From your error costs. Plus one to report alongside.
- Baseline. The dummy score and your rule. What must a model beat?
- Models. Three families, and what you'll tune in each.
Give a reason for each. The model report is due in week 12.
Notes · slide 14
Say: The last 45 minutes are for your capstone. Write one page: the CV scheme, the main metric, the baseline to beat, and three model families, each with a reason. It isn't marked. It becomes the opening of the week 12 model report.
Do: walk the room. Ask each pair: "What would leak if you split at random?"
Watch for: a random split on data with repeat customers or dates. A metric picked from habit, like F1 or accuracy, instead of from what each error costs.
Next: the chapter in one idea, before they start.
Mental model
Cross-validation is an estimation technique, not a selection technique.
- CV says how well a model type generalises.
- The test set says how well this fitted model does.
- Use CV during development.
- Touch the test set once, at the end. Never let it take part in a decision.
Notes · slide 15
Say: Cross-validation estimates. It doesn't select. CV tells you how well a model type generalises. The test set tells you how well this fitted model does.
Key line: use CV during development. Touch the test set once, at the end, and never let it take part in a decision.
Next: check yourself, then the capstone plan.
Check yourself
- Why stratify folds for an imbalanced classifier?
- You scaled the whole dataset, then ran CV. What's wrong?
- What does the outer loop of nested CV estimate?
- Why is random k-fold wrong for daily sales data?
Notes · slide 16
Do: two minutes this week, since the capstone plan needs the time. Take answers quickly.
Answers: 1. So every fold has a comparable class ratio, and comparable scores. 2. Statistics from the validation folds leaked into training. 3. How well the whole tuning procedure generalises. 4. It trains on the future to predict the past.
Then: move to the capstone plan.
This week
- Read Chapter 13: Cross-Validation & Model Selection.
- Take the Chapter 13 quiz.
- Run the notebooks: Chapter 13 (opens in a new tab).
- Optional: the further reading for week 10.
Slide 1 of 17: Cross-validation and model selection
Keys: → or Space next · ← back · Home/End · F full screen · N notes. Swipe on touch screens. "Save as PDF" opens the print dialog with one slide per page: choose "Save as PDF" as the printer. "Print handout" adds the speaker notes, in black on white.