Sub topic 1
What We Are Really Trying to Estimate
Prerequisites
Assume you know supervised learning, overfitting, training and test data, and the basic scikit-learn pattern of calling fit and score.
What We Are Really Trying to Estimate
A model's generalization error is its expected error on new examples from the same process as the training data. We cannot usually measure this for every future example, so we estimate it with data that the model did not use for fitting.
The estimate should represent the complete modeling procedure, including preprocessing, model selection, and hyperparameter tuning. If any of these steps use the evaluation data, the estimate becomes too favorable.
The Holdout Split and Its Limits
A holdout split separates data into training and test sets:
- The training set fits the model.
- The test set estimates performance on unseen data.
This is simple and useful, but the result depends heavily on one random split. A small test set also produces a noisy estimate. If you repeatedly inspect the test score and change the model, the test set gradually becomes part of the development process.
K-Fold Cross-Validation in a Nutshell
K-fold cross-validation divides the data into k parts, called folds. For each round, one fold is evaluated and the other k - 1 folds are used for training. The mean of the k scores is the estimated performance.
Hyperparameters and What Tuning Means
A parameter is learned from training data, such as a linear model's coefficients. A hyperparameter is chosen before training, such as an SVM's C or gamma.
Tuning tests candidate hyperparameter values and keeps the candidate with the best cross-validation score. This creates a selection problem: the winning score benefited from being the best among many candidates.
Tuning with Cross-Validated Grid Search
GridSearchCV evaluates every combination in a parameter grid and stores the winner:
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import GridSearchCV, StratifiedKFold
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
X, y = load_breast_cancer(return_X_y=True)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=1)
model = make_pipeline(StandardScaler(), SVC())
grid = {"svc__C": [0.1, 1, 10], "svc__gamma": ["scale", 0.01]}
search = GridSearchCV(model, grid, cv=cv)
search.fit(X, y)
print(search.best_params_)
print(search.best_score_)best_score_ is useful for comparing candidates, but it is usually optimistic as an estimate of future performance because the same folds selected the winner.
Exercise
Why can a grid search's best cross-validation score overstate performance on new data?
Show answer
It is the largest score among several candidates measured on the same folds, so random favorable results can influence which candidate wins.