Lessons › Chapter 1: Foundations
Training and test sets
Here are 20 labeled examples. If we train on all of them, we have nothing left to check whether the model really learned or just memorized.
Watch it move. This lesson is interactive on Gradient Lab: every step is an animated scene you can replay.
Start the interactive lessonStep by step
No peeking
Before building anything, Maya insists they lock part of the loan data away, so they can test honestly later.
Start with all your data
Here are 20 labeled examples. If we train on all of them, we have nothing left to check whether the model really learned or just memorized.
Shuffle first
Shuffle the rows so the split is random. Data often arrives sorted (by date, by class), and a sorted split would give the model a biased view.
Hold some back
Set aside about 20% as a test set and lock it away. The other 80% is the training set. The model never sees the test examples while learning.
Think of the test set as the final exam. Studying the exam answers would make the grade meaningless.
Train on the training set
The model learns only from the 16 training examples. It adjusts itself until it fits them well.
Test on unseen data
Now unlock the test set. The model predicts each test example and we compare against the true labels. Here it gets 3 of 4 right: 75% accuracy on data it has never seen.
This number is your best estimate of how the model will do in the real world.
Add a validation set
When you tune settings, you need a second held-out set, the validation set. Tune on validation, and touch the test set only once at the very end.
In real life: practice papers and the final exam
A student who memorizes the practice answers can ace every practice paper and still fail the real exam. Teams building medical or self-driving AI lock their test data away for the same reason: it is the only honest check of how the system will do on new cases.
Quick check: Why do we keep a test set the model never sees?
- To make training faster
- To estimate how the model will do on new data (correct)
- Because test data is lower quality
A model can score perfectly on data it memorized. Only unseen data tells you how well it generalizes.
Pseudocode
examples = all 20 labeled examples shuffle(examples) train, test = split(examples, 80% and 20%) model.learn(train) # study only the training set score = model.check(test) # final exam on unseen examples show score # 3 of 4 right = 75%
Key terms
- test set
- Examples hidden during learning, used at the end to check the model fairly.
- training set
- The examples the model is allowed to learn from.
- validation set
- A second hidden set used to tune settings, so the test set stays untouched.
Build it: Your first ML model: an iris flower classifier (20 min, runs in your browser)
See the project