Sub topic 1
Why We Hold Data Out
Prerequisites
Assume you know basic Python, arrays or tables of features and labels, and the general idea of supervised learning. A feature is an input value. A label is the value a model learns to predict.
Why We Hold Data Out
A model should work on new examples, not only on examples it has already seen. This ability is called generalization. To measure it, we hold out some labeled data during training.
The model learns from the training set. We then evaluate it on a separate test set. Because the model did not use the test features or labels while learning, the test score can estimate performance on unseen data.
Overfitting: When Training Scores Mislead
Overfitting happens when a model learns details that fit the training examples but do not represent useful patterns. A flexible model may memorize noise, unusual cases, or even the labels indirectly.
This creates a misleading result: training performance is high, but performance on new data is lower. A test score exposes this gap.
Underfitting is the opposite problem. The model is too simple to capture important patterns, so both training and test performance are poor.
Splitting Data into Training and Test Sets
Use train_test_split to create a random split. Here, 80% of the rows train the model and 20% evaluate it.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
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, stratify=y, random_state=42
)
print(X_train.shape, X_test.shape)X contains features and y contains labels. stratify=y keeps the class proportions similar in both sets.
Making Splits Reproducible
Random splitting can produce different rows each time. Set random_state to a fixed integer when you need repeatable experiments. The seed does not make the split better. It makes the result reproducible for debugging, comparison, and review.
Exercise
Why should a final evaluation use data that was not used to fit or choose the model?
Show answer
Because performance on unseen data gives a less biased estimate of how the model will generalize.