Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Chapter 9: Parameters, Hyperparameters and Model Fit — Implementation

Open in Colab

Each section below takes one idea of the chapter and measures it on real data:

  1. Hyperparameters and fitted parameters in scikit-learn

  2. A validation curve: kk in k-nearest neighbours

  3. The lasso path: regularisation as feature selection

  4. Early stopping with gradient boosting

  5. Bagging: the variance of one tree against a forest

  6. Data augmentation: shifted digits

  7. Grid search against random search on an SVM

1. Hyperparameters and Fitted Parameters

get_params() lists an estimator’s hyperparameters. Fitted parameters appear as attributes ending in _ after fit. clone copies the hyperparameters but none of the learning, which is what cross-validation does before each fold.

{'logisticregression__C': 0.5, 'logisticregression__max_iter': 5000, 'logisticregression__tol': 0.0001}
fitted: ['n_features_in_', 'classes_', 'n_iter_', 'coef_', 'intercept_']
the clone is fitted? False

2. A Validation Curve

validation_curve refits a model for each value of one hyperparameter and returns cross-validated training and validation scores. For k-NN, a small kk follows every neighbour (high variance), a large kk averages over half the dataset (high bias).

k =   1: training 1.000   validation 0.955
k =   2: training 0.983   validation 0.951
k =   3: training 0.986   validation 0.974
k =   5: training 0.979   validation 0.962
k =   7: training 0.979   validation 0.970
k =  10: training 0.978   validation 0.970
k =  15: training 0.967   validation 0.958
k =  20: training 0.961   validation 0.953
k =  30: training 0.954   validation 0.951
k =  50: training 0.948   validation 0.941
k =  80: training 0.931   validation 0.923
k = 120: training 0.914   validation 0.911
best k: 3
Source
<Figure size 650x330 with 1 Axes>

With k=1k = 1 the training accuracy is 1.0 by construction (each point is its own nearest neighbour); the validation accuracy peaks at a moderate kk, and falls slowly as kk grows and the model becomes too smooth. Read the curve right to left: decreasing kk increases capacity.

3. The Lasso Path

The lasso’s penalty λ∑∣wj∣\lambda \sum |w_j| pushes weights to exactly zero. As λ\lambda (called alpha in scikit-learn) grows, fewer features survive: regularisation doubles as feature selection. The diabetes dataset has 10 standardised features.

alpha = 0.001: 10 features kept, test R² 0.359
alpha = 0.01 :  9 features kept, test R² 0.354
alpha = 0.1  :  7 features kept, test R² 0.355
alpha = 0.5  :  4 features kept, test R² 0.329
alpha = 1    :  2 features kept, test R² 0.278
alpha = 2    :  2 features kept, test R² 0.099
alpha = 5    :  0 features kept, test R² -0.000
ridge (alpha = 1) keeps 10 of 10: it shrinks weights, never to exactly zero

A little regularisation costs almost nothing in accuracy and removes useless features; too much removes useful ones, and the model underfits.

4. Early Stopping

Gradient boosting adds one small tree at a time, so the number of trees is a capacity dial that turns during training. staged_predict gives the predictions after each tree, so we can watch the validation error as training goes on.

validation loss is lowest after 62 trees (0.151); after 500 trees it is 0.388
training loss after 500 trees: 0.00000
Source
<Figure size 650x330 with 1 Axes>

The training loss keeps falling towards zero; the validation loss falls, then creeps back up as the later trees fit noise. Stopping at the minimum is early stopping. Scikit-learn can do it automatically with n_iter_no_change and validation_fraction.

5. Bagging Reduces Variance

One deep tree changes a lot when its training set changes. We train 30 trees and 30 random forests, each on a different bootstrap sample of the training set, and look at how much their test accuracies vary.

one tree:      mean 0.915, standard deviation 0.015
random forest: mean 0.939, standard deviation 0.012

The forest is more accurate on average, and its accuracy varies less from one training sample to another: averaging trees that each overfit differently cancels part of their variance. Inside the forest the effect is stronger than these numbers suggest, since 100 trees vote on every prediction.

6. Data Augmentation

With only 150 training images of handwritten digits (8 × 8 pixels), a classifier has little to learn from. Shifting each image by one pixel in four directions creates four new, plausible images per example. We test on the usual test images, and on the same test images shifted by one pixel, as a slightly off-centre scan would be.

SVM (RBF)            test 0.916 -> 0.962   shifted test 0.436 -> 0.930
logistic regression  test 0.914 -> 0.825   shifted test 0.382 -> 0.666

For the SVM, augmentation lifts the accuracy from 0.916 to 0.962, and on shifted scans from 0.436 (it had never seen a digit off-centre) to 0.930. The linear model tells the other half of the story: it gets worse on ordinary test images. A straight-line boundary in pixel space cannot represent “the same digit, one pixel to the left”; the extra variety only makes its task harder, and it underfits. Augmentation adds information; the model needs the capacity to use it.

An SVM with an RBF kernel has two important hyperparameters, CC (the penalty for misclassified points) and γ\gamma (how local each training point’s influence is). Both act on a logarithmic scale.

grid, 16 settings: best {'C': 10.0, 'gamma': 0.01}, cross-validated 0.981, test 0.983
random, 16 settings: best {'C': 6.4312, 'gamma': 0.0043}, cross-validated 0.982, test 0.987
Source
<Figure size 460x360 with 2 Axes>

The grid’s heatmap shows a diagonal ridge of good settings: a larger CC can be compensated by a smaller γ\gamma. With the same budget, random search tries 16 different values of each hyperparameter instead of 4, and lands on the ridge as well.

Summary

  • Constructor arguments are hyperparameters; attributes ending in _ are learned; clone copies only the former.

  • A validation curve shows where a hyperparameter moves the model from overfitting to underfitting.

  • The lasso both regularises and selects features; ridge only shrinks.

  • Early stopping picks the number of boosting rounds (or epochs) where validation loss is lowest.

  • Bagging (random forests) cuts the variance of deep trees.

  • Augmentation adds plausible variety when data are scarce, for a model with the capacity to use it.

  • Random search covers each hyperparameter more finely than a grid of the same size.