Sub topic 1
Why We Need to Estimate Generalization Error
Prerequisites
Assume you know supervised learning, features and labels, basic evaluation metrics such as accuracy, and the scikit-learn fit and predict API.
Generalization Error
A model’s generalization error is its error on new data from the same process as the training data. Training performance is usually optimistic because the model has already seen those examples. A flexible model can memorize training details while performing poorly on unseen cases. This is overfitting.
We need an evaluation procedure that separates model fitting from performance measurement.
The Holdout Split
A holdout split divides the dataset into a training set and a test set. The model fits only the training set. We then calculate the chosen metric on the test set.
This is simple, but one split can be noisy. Its result depends on which examples happen to enter each set. A difficult test set may make the model look worse; an unusually easy one may make it look better. This problem is stronger with small datasets or imbalanced classes.
| Method | Main use | Main weakness |
|---|---|---|
| Holdout split | Fast first estimate | High sensitivity to one split |
| k-fold cross-validation | More stable estimate | Requires several model fits |
How k-Fold Cross-Validation Works
In k-fold cross-validation, the data is divided into k folds. Each fold becomes the test fold once. The model trains on the other k - 1 folds each time.
For five folds, every example is used for testing once and training four times. The resulting scores estimate performance across several possible test sets.
For classification, use stratified folds when possible. Stratification keeps class proportions similar across folds.
Scoring and Reporting Fold Results
Choose a metric before evaluation. Accuracy is suitable when class errors have similar costs and classes are reasonably balanced. For each fold, record the score, then report the mean and standard deviation.
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
scores = cross_val_score(model, X, y, cv=cv, scoring="accuracy")
print(f"accuracy={scores.mean():.3f} +/- {scores.std():.3f}")The mean summarizes typical performance. The standard deviation shows how much scores vary across folds. It describes split-to-split variation, not every source of uncertainty.
Exercise
Why can a single holdout score be misleading?
Show answer
Its value depends heavily on which examples were assigned to the test set, so it may not represent typical performance on unseen data.