Week 05 · Select and tune supervised models

Compare candidate families under the same selection budget.

← Week 4 · Subject contents · Week 6 →

Compare candidate families under the same selection budget.

Work through the problem

A grid of two settings across three validation folds requires six fit-and-score runs for a model family. Both families should see the same folds and a comparable search budget. Compare using a metric tied to the task and finish with a held-out score.

Consider a response containing an interaction x₁x₂. A linear model without an interaction term cannot represent it. Trees can approximate it through partitions. Whether they win depends on data coverage, noise, and how much room each family gets to tune.

Run the Python lab

import numpy as np
from sklearn.ensemble import RandomForestRegressor
from sklearn.linear_model import Ridge
from sklearn.model_selection import GridSearchCV, KFold
rng = np.random.default_rng(57)
X = rng.uniform(-2,2,(300,2))
y = X[:,0]*X[:,1] + rng.normal(0,.15,len(X))
folds = list(KFold(3,shuffle=True,random_state=4).split(X[:225]))
for model, grid in [(Ridge(),{"alpha":[.1,10]}),(RandomForestRegressor(n_estimators=50,random_state=4),{"max_depth":[3,7]})]:
    search = GridSearchCV(model,grid,cv=folds,scoring="neg_mean_absolute_error").fit(X[:225],y[:225])
    mae = abs(search.predict(X[225:])-y[225:]).mean()
    print(type(model).__name__,search.best_params_,f"validation {-search.best_score_:.3f}, test {mae:.3f}")

Output from the lab

Ridge {'alpha': 10} validation 0.970, test 1.101
RandomForestRegressor {'max_depth': 7} validation 0.495, test 0.494

Practice

  1. How can ridge compete more fairly in this example?

Check your reasoning

  1. Add the interaction as a training feature, then repeat the same split and selection protocol.

← Week 4 · Subject contents · Week 6 →

Further reading · Rules of Machine Learning