Lesson 6 of 226 min
Cross-validation and tuning
One validation set's score is partly luck, so give every row a turn in it, average the turns, and choose a setting by that average while the test set stays closed.
After this lesson you can compare settings without touching the test set.
Loading the video…
Refreshers
An idea from an earlier lesson shows up here when the video leans on it.
In real code
What the video left out, as you will meet it in your own code.
Read the spread
Five or ten folds are common. More folds means more fits and fewer rows in each validation fold. The lowest and highest scores show how much these folds differ. Their training rows overlap, so that range is only a rough guide. See the bootstrap in the earlier confidence intervals lesson for a way to estimate uncertainty in a gap.
scores = cross_val_score(LinearRegression(), X_train, y_train, cv=5)
print(f"range: {scores.min():.3f} to {scores.max():.3f}")
print(f"average: {scores.mean():.3f}")range: 0.821 to 0.898 average: 0.852
Keep classes in each fold
With cv=5, scikit-learn uses StratifiedKFold for classifiers with binary or multiclass labels. It keeps each class's share about the same across validation folds. Here the label asks whether the penguin is a Chinstrap. Each fold gets about the same share. Cross-validation guide
from sklearn.model_selection import StratifiedKFold
chinstrap = penguins.loc[X_train.index, "species"].eq("Chinstrap")
for _, fold in StratifiedKFold(n_splits=5).split(X_train, chinstrap):
print(f"{chinstrap.iloc[fold].sum()} of {len(fold)} Chinstrap")11 of 50 Chinstrap 11 of 50 Chinstrap 11 of 50 Chinstrap 11 of 50 Chinstrap 10 of 49 Chinstrap
Read the whole search
The search ranks settings by mean validation score. These rows show the strength, average, and rank. cv_results_ also has each fold's score, so you can check if a small lead holds up on the same rows. With refit=True, the default, the search fits the winner on all the training rows. GridSearchCV reference
search = GridSearchCV(Ridge(), {"alpha": [0.1, 1, 10, 100, 1000]}, cv=5)
search.fit(X_train, y_train)
results = pd.DataFrame(search.cv_results_)
cols = ["param_alpha", "mean_test_score", "rank_test_score"]
print(results[cols].to_string(index=False, header=False, float_format=lambda score: f"{score:.4f}"))0.1000 0.8523 2 1.0000 0.8525 1 10.0000 0.8395 3 100.0000 0.7795 4 1000.0000 0.7445 5
Score after you choose
The best average helped pick a setting and can be optimistic. Once you settle on a setting, score it on the held-out test set. If you need to estimate the whole tuning process with folds, use nested cross-validation. The outer folds score the choices made by the inner folds.
print(f"held-out R²: {search.score(X_test, y_test):.3f}")held-out R²: 0.882
Try fewer settings
For a wide search, RandomizedSearchCV samples a set number of candidates. HalvingGridSearchCV starts candidates with fewer resources and gives more to the ones that score well. In scikit-learn 1.9.1 the halving search needs an experimental import. Hyperparameter tuning guide
from sklearn.experimental import enable_halving_search_cv
from sklearn.model_selection import HalvingGridSearchCV, RandomizedSearchCV
grid = {"alpha": [0.1, 1, 10, 100, 1000]}
sampled = RandomizedSearchCV(Ridge(), grid, n_iter=3, cv=5, random_state=0)
halved = HalvingGridSearchCV(Ridge(), grid, cv=5, factor=2, random_state=0)Run on Python 3.13.3, scikit-learn 1.9.1, pandas 3.1.1. Checked on .
Quiz
Two questions on this lesson, and one from earlier. Answer as often as you like.
1 of 3
From earlier: Training, validation and test data
A tree gets all 256 of the penguins it learned from right. What does that tell you about new penguins?
2 of 3
You score a model on a validation set of 50 penguins: R squared 0.92. You deal the 50 again, at random: 0.72. Which score do you trust?
3 of 3
On the same five folds, a penalty of 0.1 averages 0.8523, a penalty of 1 averages 0.8525, and 100 averages 0.780. Fold by fold, 1 beats 0.1 on two folds and loses on three. 100 is lower on every fold. What do you conclude?
The ideas in this lesson
- Cross-validation
- Cut the training set into folds; each takes one turn as the validation set; the average of their scores is steadier than one.
- Tuning a hyperparameter
- A setting the model can't learn, chosen by the best average over the folds; compare fold by fold, and call a tiny gap a tie.
It leans on
Transcript
What the video says, part by part. Press a time to watch from there.
Cross-validation and tuning
Here's a puzzle. You check a model on penguins it never learned from. It scores well. Then you pick a different set it never learned from. The same model now scores much lower. Which score do you believe?
Keep your guess
Hold on to your guess. Here's a model that guesses a penguin's mass. It reads five inputs: the flipper, the bill's length and depth, the sex and the species. It's scored with R squared, where one means no miss at all. Two hundred and forty-nine penguins are the training set. Eighty-four are sealed as the test set.
One validation set is luck
To choose a model and check it, you keep part of the training set aside, as a validation set. Keep a fifth of it: fifty penguins. The model learns from the rest, and scores zero point eight three on those fifty.
Now deal them again, at random. And again.
One deal gives zero point nine two. Another gives zero point seven two: the two scores in the puzzle. Over two hundred deals, the score lands anywhere between them. So which do you believe? Neither one alone. The score depends on which fifty penguins land in the validation set.
Five folds
Can every penguin take a turn?
It's a little like a school grade from five tests instead of one. Cut the two hundred and forty-nine into five folds, of about fifty each. Turn one: fold one is the validation set, and the model learns from the other four. It scores zero point eight five. Turn two: zero point eight four. Folds three, four and five take their turns too. Every penguin gets scored once, by a model that never learned from it. That's called cross-validation.
The average
The average of the five is zero point eight five. But the five already differ: the lowest is zero point eight two, and the highest is zero point nine.
Each one is a single set's score, with a single set's luck.
So if you deal the folds again, how far does the average move?
Over two hundred deals, the average stays between zero point eight four and zero point eight six.
One set's score ran anywhere between zero point seven two and zero point nine two. So the average of the folds tells you far more than one validation set.
A hyperparameter
Cross-validation scores a model once for each fold of the training set, and averages the scores. Now use it to choose. Some settings a model can't learn by itself, like the strength of a penalty on its weights.
A stronger penalty keeps the model simpler. A strength of zero point one is weak, and a thousand is very strong. Too strong, and the model misses more.
A setting like that... is called a hyperparameter.
To choose one, run the same five folds for each value, and keep the best average. A penalty of zero point one, or one: both about zero point eight five. Ten is a little lower. A hundred and a thousand fall further. And the test set stays closed.
A tie is not a win
A penalty of one has the best average. But it beats zero point one by less than a thousandth. Spot the problem.
Compare the two fold by fold, on the same penguins.
The penalty of one is ahead on two folds, and behind on three.
Deal the folds again, six times.
Now zero point one leads every time, by about a thousandth. Which one leads is just luck. And the gap is far too small to matter, so either will do. A hundred and a thousand are lower on every fold. That gap is real.
Then the test set, once
Each fold's model learned from only about two hundred penguins. So the final model, with the setting you kept, learns from all two hundred and forty-nine. More penguins make a better model.
Then you open the test set, once: R squared zero point eight eight, inside the folds' range. The folds did the choosing, and the test set was opened only at the very end.
In code
In real code, start from the training set and the test set.
One line runs all five folds, here for a linear regression. That's it. It prints the five scores, and their average: zero point eight five two.
Then a grid search tries Ridge, a linear regression with a penalty, at five strengths, on the same five folds. It keeps the best average. Which strength will it keep?
One, with an average of zero point eight five. It takes the top one, even when it wins by less than a thousandth. Is that win real? That's for you to check. Then it scores the test set, once: zero point eight eight. You'll use these same few lines whenever you tune a model.
The recap
So: one validation set's score is partly luck.
Five folds give every penguin a turn, and their average is steadier.
Choose a setting by that average, treat a tiny gap as a tie, and open the test set once.
The lab
That's the end of this unit. In its lab, you use these three lessons to tune a penguin model on folds, and open the test set only once.
Trust the average
Trust the average of the folds, not one score. Now try it on this lesson's page, and take the quiz. Deal the folds again, and choose.
You use this lesson in Lab 2: Tune a penguin model on folds, which comes next.
Facts last checked on .
