Chapter 9: Parameters, Hyperparameters and Model Fit — Implementation
Each section below takes one idea of the chapter and measures it on real data:
Hyperparameters and fitted parameters in scikit-learn
A validation curve: in k-nearest neighbours
The lasso path: regularisation as feature selection
Early stopping with gradient boosting
Bagging: the variance of one tree against a forest
Data augmentation: shifted digits
Grid search against random search on an SVM
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_breast_cancer, load_diabetes, load_digits
from sklearn.model_selection import train_test_split, validation_curve, GridSearchCV, RandomizedSearchCV
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler1. 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.
from sklearn.base import clone
from sklearn.neighbors import KNeighborsClassifier
from sklearn.linear_model import LogisticRegression
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=0, stratify=y)
model = make_pipeline(StandardScaler(), LogisticRegression(C=0.5, max_iter=5000))
print({k: v for k, v in model.get_params().items() if k.startswith('logisticregression__') and k.split('__')[1] in ('C', 'tol', 'max_iter')})
model.fit(X_train, y_train)
print('fitted:', [a for a in vars(model[-1]) if a.endswith('_') and not a.startswith('_')])
fresh = clone(model)
print('the clone is fitted?', hasattr(fresh[-1], 'coef_')){'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 follows every neighbour (high variance), a large averages over half the dataset (high bias).
ks = [1, 2, 3, 5, 7, 10, 15, 20, 30, 50, 80, 120]
knn = make_pipeline(StandardScaler(), KNeighborsClassifier())
tr, va = validation_curve(knn, X_train, y_train, param_name='kneighborsclassifier__n_neighbors', param_range=ks, cv=5)
for k, a, b in zip(ks, tr.mean(axis=1), va.mean(axis=1)):
print(f'k = {k:3d}: training {a:.3f} validation {b:.3f}')
best = ks[int(np.argmax(va.mean(axis=1)))]
print('best k:', best)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
plt.figure(figsize=(6.5, 3.3))
plt.plot(ks, tr.mean(axis=1), 'o-', label='training'); plt.plot(ks, va.mean(axis=1), 's-', label='validation')
plt.xscale('log'); plt.xlabel('k (log scale)'); plt.ylabel('accuracy'); plt.title('k-NN on breast cancer'); plt.legend()
plt.tight_layout(); plt.show()
With the training accuracy is 1.0 by construction (each point is its own nearest neighbour); the validation accuracy peaks at a moderate , and falls slowly as grows and the model becomes too smooth. Read the curve right to left: decreasing increases capacity.
3. The Lasso Path¶
The lasso’s penalty pushes weights to exactly zero. As (called alpha in scikit-learn) grows, fewer features survive: regularisation doubles as feature selection. The diabetes dataset has 10 standardised features.
from sklearn.linear_model import Lasso, Ridge
Xd, yd = load_diabetes(return_X_y=True)
Xd_tr, Xd_te, yd_tr, yd_te = train_test_split(Xd, yd, test_size=0.25, random_state=0)
for alpha in [0.001, 0.01, 0.1, 0.5, 1, 2, 5]:
las = Lasso(alpha=alpha, max_iter=100000).fit(Xd_tr, yd_tr)
print(f'alpha = {alpha:<5g}: {np.sum(las.coef_ != 0):2d} features kept, test R² {las.score(Xd_te, yd_te):.3f}')
ridge = Ridge(alpha=1).fit(Xd_tr, yd_tr)
print('ridge (alpha = 1) keeps', np.sum(ridge.coef_ != 0), 'of 10: it shrinks weights, never to exactly zero')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.
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.metrics import log_loss
Xb_tr, Xb_va, yb_tr, yb_va = train_test_split(X_train, y_train, test_size=0.3, random_state=1, stratify=y_train)
gb = GradientBoostingClassifier(n_estimators=500, learning_rate=0.1, max_depth=3, random_state=0).fit(Xb_tr, yb_tr)
train_loss = [log_loss(yb_tr, p) for p in gb.staged_predict_proba(Xb_tr)]
val_loss = [log_loss(yb_va, p) for p in gb.staged_predict_proba(Xb_va)]
best_n = int(np.argmin(val_loss)) + 1
print(f'validation loss is lowest after {best_n} trees ({min(val_loss):.3f}); after 500 trees it is {val_loss[-1]:.3f}')
print(f'training loss after 500 trees: {train_loss[-1]:.5f}')validation loss is lowest after 62 trees (0.151); after 500 trees it is 0.388
training loss after 500 trees: 0.00000
Source
plt.figure(figsize=(6.5, 3.3))
plt.plot(range(1, 501), train_loss, label='training'); plt.plot(range(1, 501), val_loss, label='validation')
plt.axvline(best_n, ls='--', color='gray'); plt.yscale('log'); plt.xlabel('number of trees'); plt.ylabel('log loss')
plt.title('gradient boosting: stop where validation is lowest'); plt.legend(); plt.tight_layout(); plt.show()
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.
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
rng = np.random.default_rng(0)
tree_acc, forest_acc = [], []
for s in range(30):
idx = rng.integers(0, len(y_train), len(y_train))
tree_acc.append(DecisionTreeClassifier(random_state=s).fit(X_train[idx], y_train[idx]).score(X_test, y_test))
forest_acc.append(RandomForestClassifier(n_estimators=100, random_state=s).fit(X_train[idx], y_train[idx]).score(X_test, y_test))
print(f'one tree: mean {np.mean(tree_acc):.3f}, standard deviation {np.std(tree_acc):.3f}')
print(f'random forest: mean {np.mean(forest_acc):.3f}, standard deviation {np.std(forest_acc):.3f}')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.
from sklearn.svm import SVC
digits = load_digits()
Xg, yg = digits.images, digits.target
Xg_tr, Xg_te, yg_tr, yg_te = train_test_split(Xg, yg, train_size=150, random_state=0, stratify=yg)
def shift(img, dy, dx):
out = np.zeros_like(img)
out[max(dy, 0):8 + min(dy, 0), max(dx, 0):8 + min(dx, 0)] = img[max(-dy, 0):8 + min(-dy, 0), max(-dx, 0):8 + min(-dx, 0)]
return out
moves = [(0, 1), (0, -1), (1, 0), (-1, 0)]
aug_X = np.concatenate([Xg_tr] + [np.array([shift(im, dy, dx) for im in Xg_tr]) for dy, dx in moves])
aug_y = np.tile(yg_tr, 5)
shifted_te = np.array([shift(im, *moves[i % 4]) for i, im in enumerate(Xg_te)])
flat = lambda a: a.reshape(len(a), -1)
for name, make in [('SVM (RBF)', lambda: SVC(gamma=0.001)), ('logistic regression', lambda: LogisticRegression(max_iter=5000))]:
plain, aug = make().fit(flat(Xg_tr), yg_tr), make().fit(flat(aug_X), aug_y)
print(f'{name:20s} test {plain.score(flat(Xg_te), yg_te):.3f} -> {aug.score(flat(Xg_te), yg_te):.3f} '
f'shifted test {plain.score(flat(shifted_te), yg_te):.3f} -> {aug.score(flat(shifted_te), yg_te):.3f}')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.
7. Grid Search Against Random Search¶
An SVM with an RBF kernel has two important hyperparameters, (the penalty for misclassified points) and (how local each training point’s influence is). Both act on a logarithmic scale.
from scipy.stats import loguniform
Xs_tr, Xs_te, ys_tr, ys_te = train_test_split(digits.data, digits.target, test_size=0.3, random_state=0, stratify=digits.target)
svm = make_pipeline(StandardScaler(), SVC())
grid = GridSearchCV(svm, {'svc__C': [0.1, 1, 10, 100], 'svc__gamma': [1e-4, 1e-3, 1e-2, 1e-1]}, cv=5).fit(Xs_tr, ys_tr)
rand = RandomizedSearchCV(svm, {'svc__C': loguniform(1e-1, 1e2), 'svc__gamma': loguniform(1e-4, 1e-1)}, n_iter=16, cv=5, random_state=0).fit(Xs_tr, ys_tr)
for name, s in [('grid, 16 settings', grid), ('random, 16 settings', rand)]:
p = {k.split('__')[1]: round(float(v), 4) for k, v in s.best_params_.items()}
print(f'{name}: best {p}, cross-validated {s.best_score_:.3f}, test {s.score(Xs_te, ys_te):.3f}')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
scores = grid.cv_results_['mean_test_score'].reshape(4, 4)
plt.figure(figsize=(4.6, 3.6))
plt.imshow(scores, cmap='viridis'); plt.colorbar(label='cross-validated accuracy')
plt.xticks(range(4), ['1e-4', '1e-3', '1e-2', '1e-1']); plt.yticks(range(4), ['0.1', '1', '10', '100'])
plt.xlabel('gamma'); plt.ylabel('C'); plt.title('the grid')
for i in range(4):
for j in range(4):
plt.text(j, i, f'{scores[i, j]:.2f}', ha='center', va='center', color='w', fontsize=8)
plt.tight_layout(); plt.show()
The grid’s heatmap shows a diagonal ridge of good settings: a larger can be compensated by a smaller . 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;clonecopies 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.