Training, validation and test data
Why This Matters
A model’s test score is only worth something if the test data played no part in building the model. Use it to choose between models, let a copy of a training record slip into it, or fit a scaler on it, and the score is too optimistic. The model then disappoints in production, and nobody understands why. Keeping data apart is a tester’s job as much as a data scientist’s.
What you will learn
- The purpose of the training, validation and test dataset, and why they must be kept apart
- What to do when there is too little data for three sets: k-fold cross-validation with a holdout test set
- How to test that the split is clean
Syllabus: AI-3.2.3.
Three datasets, three jobs
| Dataset | Used for | When |
|---|---|---|
| Training | Training the model: the model learns from it | Model generation, step 5 |
| Validation | Evaluating and tuning: comparing models and hyperparameters | Model generation, steps 6 and 7 |
| Test (holdout) | Testing the final, tuned model, once | Step 8 |
Why a separate validation set? Every time you look at a score and change something, you adapt the model to that data a little. After 50 rounds of tuning on the validation set, the model is good at the validation set, and its validation score is too optimistic. The test set has not been looked at, so it still gives an honest estimate. Use it once; if you tune again after looking at it, it has become a second validation set.
How big should each set be? It depends on the complexity of the model, the algorithm, the available resources (memory, storage, computing power, bandwidth, time) and the confidence you need in the result. A common starting point is 60/20/20 or 70/15/15.
Not enough data: cross-validation
With little data, splitting three ways leaves too little to train on, and the model underfits. The usual solution:
- Put a small holdout test set aside.
- On the rest, use k-fold cross-validation: split it into k equal parts (folds), usually 5 or 10. Train k times, each time on k − 1 folds, and validate on the remaining fold. The average of the k validation scores is the validation score.
- Choose the model and hyperparameters with the best average.
- Train the final model on all non-holdout data, and test it once on the holdout set.
rest of the data, 5 folds train on validate on
[ 1 ][ 2 ][ 3 ][ 4 ][ 5 ] run 1: 2 3 4 5 1
run 2: 1 3 4 5 2
run 3: 1 2 4 5 3
run 4: 1 2 3 5 4
run 5: 1 2 3 4 5 → average of 5 scores
holdout test set: [ T ] final model: train on 1-5, test once on T
The folds are usually stratified: every fold has the same share of each class as the whole. Without a holdout set, the cross-validation average is optimistically biased, because it was used to choose the model. Two variants the syllabus names: leave-one-out cross-validation (k is the number of records: train on all but one, n times) and bootstrap (repeatedly sample with replacement).
Hands-on: tune with cross-validation, test once
The loan data has 48 rows after preparation, too few for three sets. You continue in the practice project; create module-3/test_splits.py. It uses prepare from the previous lesson:
"""Lesson "Training, validation and test data": tune with cross-validation, test once on a holdout set."""
import pandas as pd
import pytest
from sklearn.metrics import accuracy_score
from sklearn.model_selection import StratifiedKFold, cross_val_score, train_test_split
from sklearn.tree import DecisionTreeClassifier
from test_data_preparation import prepare
LABEL = "approved"
DEPTHS = [1, 2, 3, None]
@pytest.fixture(scope="module")
def data(api):
response = api.get(f"{api.base}/datasets/loans-train", timeout=10)
response.raise_for_status()
return prepare(pd.DataFrame(response.json()["data"]))
@pytest.fixture(scope="module")
def split(data):
"""Put the test data aside first. It is not touched until the very end."""
rest, test = train_test_split(data, test_size=0.25, random_state=42, stratify=data[LABEL])
return rest, test
def features(df):
return df.drop(columns=["id", LABEL])
@pytest.fixture(scope="module")
def tuning(split):
"""Choose max_depth with 5-fold cross-validation on the non-test data only."""
rest, _ = split
folds = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
scores = {}
for depth in DEPTHS:
model = DecisionTreeClassifier(max_depth=depth, random_state=0)
scores[depth] = cross_val_score(model, features(rest), rest[LABEL], cv=folds).mean()
print(f"\n max_depth={depth}: validation accuracy {scores[depth]:.3f}", end="")
best = max(scores, key=scores.get)
return best, scores[best]
Two tests. The first checks the split itself: no application may be in both sets, not by id and not as a copy with another id. The second trains the final model on all non-test data with the chosen depth, and tests it once:
def test_test_data_is_independent(split):
rest, test = split
assert set(rest["id"]).isdisjoint(test["id"])
together = pd.concat([features(rest), features(test)])
assert not together.duplicated().any(), "the same application is in both sets"
def test_final_model_on_the_holdout_set(split, tuning):
rest, test = split
best_depth, validation_accuracy = tuning
model = DecisionTreeClassifier(max_depth=best_depth, random_state=0).fit(features(rest), rest[LABEL])
test_accuracy = accuracy_score(test[LABEL], model.predict(features(test)))
print(f"\n chosen max_depth={best_depth}: validation {validation_accuracy:.3f}, test {test_accuracy:.3f}"
f" ({len(rest)} rows for training and validation, {len(test)} for the test)")
assert test_accuracy >= 0.75
Run it
pytest module-3/test_splits.py -v -s
module-3/test_splits.py::test_test_data_is_independent PASSED
module-3/test_splits.py::test_final_model_on_the_holdout_set
max_depth=1: validation accuracy 0.782
max_depth=2: validation accuracy 0.868
max_depth=3: validation accuracy 0.868
max_depth=None: validation accuracy 0.843
chosen max_depth=2: validation 0.868, test 0.833 (36 rows for training and validation, 12 for the test)
PASSED
============================== 2 passed
Read it as a tester:
- Depth 2 and 3 tie on validation; the code takes the first, the simpler model. With equal scores, simpler is the safer choice.
- No limit (
None) is worse on validation than depth 2, although it is perfect on its training folds. That is overfitting, seen through validation data (lesson 48). - Test (0.833) is lower than validation (0.868). That is normal: the validation score was used to choose, so it is slightly optimistic. A small drop is expected. A large drop means the model was tuned to the validation data, or the test data differs from the rest; then you go back to model generation or data preparation.
- 12 test rows is very few: one wrong prediction is 8 percentage points. Lesson 44 shows how to say how much a score from a small test set is worth.
See the leak
The duplicates of Grace Lee’s application show why the first test matters. Without the drop_duplicates step in prepare, the three copies (ids 7, 8 and 9) are split as: id 7 in the training data, ids 8 and 9 in the test data. The model is then tested on an application it was trained on, and gets it right for free. test_test_data_is_independent fails with the same application is in both sets.
Duplicates are only one kind of data leakage: information from the test data reaching the model. Others: imputing or scaling with values calculated on all data (lesson 15, exercise 1), several records of the same customer split over both sets, and features that are only known after the outcome (the date a loan was paid back, used to predict whether it will be paid back).
Exercise
A team has 100,000 labelled images. They train on 80,000, and after every training run they check the accuracy on the other 20,000 and adjust the network. After three weeks they report: “test accuracy 97%”. What is wrong, and what should they have done?
Show suggested answer
The 20,000 images were used for tuning, so they are a validation set, not a test set. After three weeks of adjusting the network to them, 97% is an optimistic number. There is no independent estimate of how the model will do on new images.
They should have put a test set aside at the start (for example 15,000 images), tuned on a validation set (or with cross-validation on the rest), and run the final model once on the test set. With 100,000 images there is enough data for three sets; cross-validation is mainly needed when data is scarce. The 97% can still be reported, but as validation accuracy.
Exam-style questions
1. What is the purpose of the validation dataset?
- A. Training the model
- B. Evaluating and tuning the model during model generation
- C. Testing the final model once, independently
- D. Monitoring the model in production
Show answer
2. A team has very little labelled data. Which approach is recommended?
- A. Use all data for training and skip testing
- B. Keep a small holdout test set and use k-fold cross-validation on the rest
- C. Use the test data for tuning to make better use of it
- D. Use only the training data for testing
Show answer
3. Why is a cross-validation average optimistically biased when there is no holdout test set?
- A. Cross-validation always uses too little data
- B. The same data was used to choose the model, so the score is not an independent estimate
- C. Cross-validation does not use stratification
- D. The folds overlap
Show answer
Your project so far
ai-testing-practice/
├── ...
└── module-3/
├── test_first_model.py
├── test_data_preparation.py
└── test_splits.py new in this lesson
The finished version is in the example repository: module-3/test_splits.py.