Sub topic 1
Why We Hold Data Out
Prerequisites
This chapter assumes you know the following:
- Basic Python, including calling functions and reading NumPy arrays.
- How a table of features (the inputs) and labels (the answers) is laid out as
Xandy. - What a supervised model is: a function learned from labeled examples that maps features to labels.
You do not need to know scikit-learn in detail. The code uses only train_test_split, one classifier, and its score method.
The question every model must answer
A model is trained to work on data it has not seen yet. A spam filter has to judge tomorrow's email. A tumor classifier has to judge next month's patients. Training data is only the material used to build the model.
This gives the central question of model evaluation: how well will this model do on new data? The ability to do well on new data is called generalization. The error you can expect on new data is the generalization error.
You cannot measure generalization error directly, because the new data does not exist yet. All you can do is estimate it. The standard way is to hold some labeled data out of training and use it as a stand-in for the future.
Why training scores mislead
Scoring a model on the rows it was trained on seems natural, but the result is biased. The training procedure adjusts the model to fit those exact rows. A high training score therefore shows that the model fits those rows. It does not show that the model has learned something that holds elsewhere.
An extreme case is a model that memorizes. A 1-nearest-neighbor classifier stores every training row. When you ask it to predict a training row, it finds that same row at distance zero and returns the stored label. Its training accuracy is 100%, whatever the data contains. If the labels were random, the model would still score 100% on its training data and would be no better than guessing on new data.
Two quantities are worth keeping apart:
| Quantity | Computed on | What it tells you |
|---|---|---|
| Training error | The rows used to fit the model | How well the model fits what it saw |
| Generalization error | New rows from the same source | How well the model will work in use |
The gap between them is usually positive: the model looks better on its training data than it will on new data. A flexible model can make that gap large.
Holding data out
The fix is simple. Before training, set some labeled rows aside. Train on the rest. Then score the model on the held-out rows. Those rows played no part in fitting, so the model had no chance to adapt to them. Its score on them is an honest estimate of how it will do on other unseen rows.
The key rule is that the held-out rows must not influence the model in any way. Later chapters cover the subtle ways this rule gets broken, which are called data leakage. For now, remember the basic condition: the model never sees the held-out labels during training.
A first demonstration
The following program compares a model's score on its training data with its score on held-out data. It uses a decision tree with no depth limit, which is flexible enough to fit its training rows almost perfectly.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
model = DecisionTreeClassifier(random_state=42)
model.fit(X_train, y_train)
print("Training accuracy:", model.score(X_train, y_train))
print("Test accuracy: ", model.score(X_test, y_test))The training accuracy comes out at 1.0, because the tree keeps splitting until each training row is classified correctly. The test accuracy is lower. The exact figure depends on the split, but on this dataset it typically falls in the low 0.9 range. The difference between the two numbers is the optimism of the training score.
Notice what the test score does and does not claim. It estimates performance on data drawn from the same source as the training data. It says nothing about data that looks different, a problem covered in the last chapter of this tutorial.
Why one number is still noisy
A test score is itself an estimate, and estimates vary. Several things affect how far it may sit from the true generalization error:
- Test set size. With 114 test rows, one extra mistake changes accuracy by about 0.9 percentage points. Small test sets give coarse and unstable scores.
- Which rows landed in the test set. A different random split gives a different score, even for the same model.
- Class balance. If one class is rare, the test set may contain only a handful of its rows, so the score says little about that class.
You can see the effect of the split directly by repeating the experiment with different seeds:
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
X, y = load_breast_cancer(return_X_y=True)
for seed in range(5):
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=seed
)
model = DecisionTreeClassifier(random_state=0).fit(X_train, y_train)
print(f"seed={seed} test accuracy={model.score(X_test, y_test):.3f}")The five accuracies will differ by a few points. None of them is the "true" value. Each is one sample from a spread of plausible values. Later chapters on split sizes and cross-validation show how to reduce and measure this spread.
What holding out costs
Held-out rows are not free. Every row in the test set is a labeled example the model cannot learn from. This creates a trade-off:
- A larger test set gives a more stable score but leaves less data for training, so the model may be weaker.
- A smaller test set leaves more data for training but gives a noisier score.
With millions of rows, this trade-off barely matters, because even a small percentage is a large absolute number of rows. With a few hundred rows, it matters a great deal. The chapter on split sizes treats this in detail.
There is also a subtler cost. The test score only stays honest if you use it sparingly. Each time you look at it and change the model in response, the test set leaks a little information into your choices. The tutorial returns to this under the heading of test set discipline.
Common mistakes at this stage
These errors appear often when people first evaluate a model:
- Reporting the training score. It is easy to compute and looks good, but it measures fit rather than generalization.
- Evaluating on the training set "to check it works". This check is fine as a debugging step, such as confirming the model can fit at all. It is not an evaluation.
- Splitting after other steps. Scaling, imputing, or selecting features on the full dataset before splitting lets held-out information reach the model. Split first.
- Treating one test score as exact. A difference of one or two points between two models is often within the noise of a single split.
- Assuming the test set represents the future. The test set comes from the same collection process as the training data. If deployment data differs, the test score will be too optimistic.
How this chapter connects to the rest
Holding out data gives an honest estimate, but it raises further questions that the rest of the tutorial answers in order:
- Why does the training score rise while the test score falls? That is overfitting, the next chapter.
- How do you perform the split correctly and repeatably? The chapters on
train_test_splitand random seeds cover this. - What if you need to compare many models or tune settings? A validation set, and later cross-validation, keeps the test set clean.
- What if rows are related to each other, or ordered in time? Grouped and time-ordered splits handle those cases.
Summary of the idea
A model's job is to perform on new data, so evaluation must use data the model did not learn from. Training scores are biased upward because the model was fit to those rows. A held-out set removes that bias. The remaining score is still an estimate with noise, and it holds only for data that resembles what you held out.
Exercise
A colleague trains a random forest on 10,000 labeled rows and reports 99.8% accuracy, measured on those same 10,000 rows. Why is this number not a reliable estimate of performance on new data, and what is the minimal change that would make it more reliable?
Show answer
The model was fit to those exact rows, so it can score highly by memorizing them, and the training score is biased upward as an estimate of generalization. Random forests in particular can fit their training rows almost perfectly. The minimal change is to split the labeled data before training, for example 80/20 with traintestsplit, fit on the training part only, and report the accuracy on the held-out part. The held-out score will usually be lower, and it is the figure that estimates performance on new data.
Exercise
You run the same model with five different randomstate values in traintest_split and get test accuracies of 0.93, 0.95, 0.91, 0.96 and 0.94. What does this variation tell you about reporting a single test score, and which two factors make the variation larger?
Show answer
The spread shows that a single test score is one noisy sample, so a difference of a point or two between models may not be meaningful. The variation grows when the test set is small, because each row moves the score more, and when the data contains a rare class or few rows, because the composition of the test set changes more from split to split.