Lesson 2 of 226 min
Training, validation and test data
A model is judged only on data it never learned from, so keep a test set aside, choose with a validation set, and open the test set once.
After this lesson you can split data and say why a model is judged on data it has not seen.
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.
Pick how much to hold back
A quarter is a starting point. With 342 measured penguins, it leaves 86 for the test. A quarter of the remaining 256 gives validation 64. With less data, check how many examples of each species the two scores will have to go on. A few birds can move the score a lot.
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
url = "https://raw.githubusercontent.com/mwaskom/seaborn-data/master/penguins.csv"
features = ["flipper_length_mm", "bill_length_mm"]
penguins = pd.read_csv(url).dropna(subset=features)
X, y = penguins[features], penguins["species"]Keep the species in proportion
In each call, pass the labels of the rows you are splitting as stratify. It keeps the species in roughly the same proportions. The second call uses y_rest, because it splits only the rows left after setting aside the test. scikit-learn documentation
X_rest, X_test, y_rest, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=0
)
X_train, X_val, y_train, y_val = train_test_split(
X_rest, y_rest, test_size=0.25, stratify=y_rest, random_state=0
)
print(len(X_train), len(X_val), len(X_test))192 64 86
Fit the chosen tree again
Depth is the maximum number of questions one penguin can answer. After choosing depth two on validation, you can train a fresh tree of that depth on all 256 rows left after the first split. This changes what the tree learns, so the final score can move either way. Decide whether to refit before opening the test set.
final_tree = DecisionTreeClassifier(max_depth=2, random_state=0)
final_tree.fit(X_rest, y_rest)
print((final_tree.predict(X_test) == y_test).sum(), "of", len(y_test))82 of 86
Give validation several turns
Cross-validation rotates which rows are used for validation. It can help when one split gives a noisy score. Give GridSearchCV only the 256 rows left after holding out the test. With refit=True, it trains the winning setting on all those rows before you score it on the test. scikit-learn documentation
from sklearn.model_selection import GridSearchCV
search = GridSearchCV(
DecisionTreeClassifier(random_state=0),
{"max_depth": [1, 2, 3, 4, 5, None]},
cv=5, refit=True,
)
search.fit(X_rest, y_rest)
print(search.best_params_){'max_depth': 2}Run on Python 3.13.3, scikit-learn 1.9.1 and 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: What machine learning is
On the 86 penguins kept aside, tree.score(X_test, y_test) printed 0.953: the share it got right, 82 of 86. The rule by hand got 83 of the 86 right. Written as the same kind of score, what is it?
2 of 3
A tree gets all 256 of the penguins it learned from right. What does that tell you about new penguins?
3 of 3
Your loop printed each setting's score on the validation set, and two questions won with 0.9375. Then the winner, scored once on the test set, printed 0.965. Which number tells you how it will do on new penguins?
The ideas in this lesson
- Training and test sets
- Learn from the training set; score on a test set kept aside, which the model never learned from.
- Validation set
- A third set, to choose a model's settings with, so the test set is opened only once, at the end.
It leans on
Transcript
What the video says, part by part. Press a time to watch from there.
Training, validation and test
Here's a question. A model gets every penguin it learned from right. Then it meets penguins it has never seen. How many of those will it get right?
Keep your guess
Hold on to your guess. Here are the penguins from Python for AI, three hundred and forty-two of them. A tree learned from two hundred and fifty-six, and eighty-six are kept aside, sealed. With two questions, the tree gets two hundred and forty-three of its own penguins right.
Every one right
Now let the tree ask as many questions as it likes. Its training keeps cutting, until each little box holds just one species. Twenty-two boxes, and all two hundred and fifty-six penguins right. It has remembered the penguins.
Eighty-six new penguins
So how many new penguins does it get right? Open the eighty-six.
Seventy-nine of eighty-six.
Now the tree with two questions.
It made thirteen mistakes on its own penguins. On these new ones, it gets... eighty-two.
On these eighty-six, the tree that remembered did worse.
Training set and test set
It's like a student who learned the practice questions by heart. Every one right. Only the exam shows what they really learned. Being right on the penguins it learned from doesn't say much about new ones.
The penguins a model learns from are called the training set. The ones kept aside to score it... are the test set.
A deal has luck
A model learns from the training set, and it's scored on a test set kept aside. So is seventy-nine its real score?
Deal the same penguins again, at random, with another eighty-six kept aside. The tree that remembers now gets eighty of eighty-six. Again, and again. Each deal gives its own score.
Two hundred deals
Deal two hundred times, and the score lands anywhere between seventy-two and eighty-five. On average, the tree that remembered gets eighty, and the tree with two questions gets eighty-one. About the same. So the three penguins between them, on the first deal, were partly luck. With only eighty-six penguins, luck moves the score by several penguins.
Choosing on the test set
How many questions a tree can ask is a setting you choose. So try each setting on the test set, and keep the best? Spot the problem.
On this deal, two and three questions tie, at eighty-two. Deal again, and now four questions win, with eighty-four. The winner changes with the deal.
Too high
Now do this on two hundred deals. Each time, keep the best of the six scores. Those best scores average eighty-two. But stick with any one setting every time, and it doesn't average more than eighty-one. So the best score you picked is too high: higher than that setting really gets on new penguins. The test set helped you choose, so it isn't new data anymore.
Validation set
A student sees the exam once. A model can be tried on the same test set again and again.
So keep a third set, just for choosing.
Sixty-four of the two hundred and fifty-six go aside. The training set is now the other hundred and ninety-two.
This third set is called the validation set.
Each setting is scored on those sixty-four.
Two questions win, with sixty of sixty-four.
The test set, once
Then the test set is opened once, at the end.
Eighty-three of eighty-six, about what the trees got before. The validation set doesn't make the model better. It keeps the test set new, so its score still means something. So the training set is for learning. The validation set is for choosing. And the test set is opened once.
The real case
AI models are judged the same way.
There's a well-known school math test for AI models.
Researchers wrote over a thousand new questions like it, and scored the models on both.
Which models would drop?
A test it had seen
Some models scored up to eight points lower on the new questions. Models that were more likely to repeat the old questions tended to drop more. That suggests some had already seen questions from the old test. Many of the strongest models barely dropped. To see how a model does on new questions, you need questions it hasn't seen.
In code
In real code, you call train test split twice.
First the test set, kept aside. Then the validation set, out of the rest. A for loop tries each setting.
In the code, max depth is how many questions the tree can ask, and None means as many as it likes.
Each tree fits on the training set, and is scored on the validation set. Will it pick the same winner?
Yes. Two questions win again, with sixty of sixty-four. Then the winner is scored once on the test set: eighty-three of eighty-six.
Three sets
So keep the test set aside before anything else.
Choose on the validation set.
And open the test set once, at the end.
Judge it on what it never saw
Judge a model only on data it never learned from. Now try it on this lesson's page, and take the quiz. Deal again, and choose with the validation set.
You use this lesson in Lab 1: A first model, judged on new penguins, after Linear regression.
Facts last checked on .
