Week 04 · Resampling and model selection

Put tuning and evaluation in different levels of cross-validation.

← Week 3 · Subject contents · Week 5 →

Put tuning and evaluation in different levels of cross-validation.

Work through the problem

A validation fold used to choose between ten candidates carries information into that choice. Reporting the best validation result as final performance benefits from favourable noise. Nested cross-validation makes an outer holdout that the inner hyperparameter search cannot see.

If 60 rows are split into three outer folds, each model trains and tunes on 40 rows and predicts the 20 left out. The outer scores estimate the whole selection procedure. For the final deployable model, rerun the inner procedure on all available training rows.

Run the Python lab

import numpy as np
from sklearn.datasets import make_regression
from sklearn.linear_model import Ridge
from sklearn.model_selection import KFold, GridSearchCV, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
x,y = make_regression(n_samples=60,n_features=6,noise=25,random_state=3)
pipe = make_pipeline(StandardScaler(), Ridge())
search = GridSearchCV(pipe, {"ridge__alpha":[.1,1,10,100]}, cv=3, scoring="neg_mean_absolute_error")
scores = -cross_val_score(search,x,y,cv=KFold(3,shuffle=True,random_state=8),scoring="neg_mean_absolute_error")
print("Outer MAE:", scores.round(2))
print("Mean:", round(scores.mean(),2))
assert len(scores)==3 and np.all(scores>0)

Output from the lab

Outer MAE: [24.36 17.88 20.33]
Mean: 20.86

Practice

  1. Where does scaling belong?

Check your reasoning

  1. Inside the pipeline so each fit estimates its scaling parameters only from its training fold.

← Week 3 · Subject contents · Week 5 →

Further reading · An Introduction to Statistical Learning