Sub topic 2
How Much Data Goes Where
Assume you know basic Python, arrays or tables, and that supervised learning maps features to labels. This chapter focuses on choosing evaluation splits and avoiding misleading scores.
How much data goes where
A training set is the data used to fit model parameters. A test set is held back until the end to estimate performance on unseen data.
A common starting point is 80% training data and 20% test data. With a small dataset, use more data for training. With a large dataset, a smaller test percentage may still provide a stable estimate.
| Goal | Typical split |
|---|---|
| Training and final test | 80% / 20% |
| Training, validation, and test | 60% / 20% / 20% |
Stratified splits for imbalanced classes
An imbalanced dataset has unequal numbers of examples in its classes. A random split might place too few minority-class examples in the test set.
A stratified split preserves approximately the same class proportions in each part:
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)Use random_state to make the result repeatable. Repeatable splits make experiments easier to compare.
Adding a validation set for model selection
A validation set helps you choose between models or hyperparameters. A hyperparameter is a setting chosen before training, such as a tree's maximum depth.
First separate the test set. Then split the remaining data:
X_train_full, X_test, y_train_full, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42
)
X_train, X_val, y_train, y_val = train_test_split(
X_train_full, y_train_full, test_size=0.25,
stratify=y_train_full, random_state=42
)This produces approximately 60% training, 20% validation, and 20% test data.
Using the test set only once
Use validation performance to select the model. After selection, evaluate the final model on the test set once. Repeatedly changing the model based on test scores makes the test set part of the training process. Its score then becomes optimistic.
Data leakage and how it happens
Data leakage occurs when information unavailable at prediction time influences training. For example, scaling all rows before splitting lets test-set statistics affect the training features.
Split first, then fit preprocessing only on training data. Apply the learned transformation to validation and test data without refitting it.
Exercise
Why should an imbalanced classification dataset usually use stratify=y during a random split?
Show answer
It keeps class proportions approximately equal in the training and test sets, giving both sets a more representative class distribution.