Chapter 9: Parameters, Hyperparameters and Model Fit
With four parameters I can fit an elephant, and with five I can make him wiggle his trunk.
John von Neumann (attributed)
9.1 Two Kinds of Numbers¶
Every model of Chapter 8 contains two kinds of numbers, and confusing them is behind many mistakes.
Parameters are learned from the data by the training algorithm: the weights and bias of a linear model, the questions and thresholds of a decision tree, the class frequencies of Naive Bayes. Nobody types them in;
fitfinds them.Hyperparameters are chosen before training and control how the model learns or how complex it may become: the degree of a polynomial, the depth of a tree, the number of neighbours , the strength of a penalty , the learning rate of gradient descent.
| Model | Parameters (learned) | Hyperparameters (chosen) |
|---|---|---|
| Linear regression | weights , bias | polynomial degree, penalty (ridge, lasso) |
| Logistic regression | weights, bias | penalty , class weights |
| Decision tree | the questions and thresholds, the leaf predictions | maximum depth, minimum samples per leaf |
| Random forest | every tree’s parameters | number of trees, features tried per split, depth |
| k-nearest neighbours | none: it stores the training set | , the distance, the weighting |
| Naive Bayes | class priors, per-class feature probabilities | Laplace smoothing |
| Neural network (Chapter 15) | all weights and biases | layers, units, learning rate, batch size, epochs, dropout |
Scikit-learn makes the difference visible. Hyperparameters are the arguments of the constructor; parameters are attributes ending in an underscore, which exist only after fit:
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
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)
tree = DecisionTreeClassifier(max_depth=3, random_state=0) # hyperparameters: in the constructor
tree.fit(X_train, y_train)
print('learned: a tree with', tree.tree_.node_count, 'nodes; first question: feature', tree.tree_.feature[0],
'<=', round(tree.tree_.threshold[0], 2))
logreg = LogisticRegression(C=1.0, max_iter=5000).fit(X_train, y_train)
print('learned:', logreg.coef_.size, 'weights and', logreg.intercept_.size, 'bias')learned: a tree with 15 nodes; first question: feature 22 <= 106.1
learned: 30 weights and 1 bias
The distinction decides which data may set them:
Parameters are fitted on the training set.
Hyperparameters are chosen by comparing models on a validation set (or by cross-validation, Chapter 10).
The test set sets nothing at all. It is used once, at the end, to report performance.
Choosing a hyperparameter by its test score is a form of leakage (Chapter 7): the test set has then helped build the model, and its score is no longer an honest estimate.
9.2 Capacity: Underfitting and Overfitting¶
Most hyperparameters control a model’s capacity: how complicated a pattern it can represent. A straight line has little capacity; a degree-15 polynomial, a deep tree, or 1-nearest-neighbour has a lot.
To see what capacity does, we take 20 noisy points from a sine curve on (noise standard deviation 0.25, so the best possible mean squared error is ), fit polynomials of increasing degree, and measure the error on the 20 training points and on 500 fresh validation points.
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression, Ridge
from sklearn.pipeline import make_pipeline
from sklearn.metrics import mean_squared_error as mse
def sample(n, seed):
"""n points of y = sin(pi x) + noise, x uniform on [-1, 1]."""
rng = np.random.default_rng(seed)
x = rng.uniform(-1, 1, n)
return x.reshape(-1, 1), np.sin(np.pi * x) + rng.normal(0, 0.25, n)
def poly(degree, regressor=None):
return make_pipeline(PolynomialFeatures(degree, include_bias=False), regressor or LinearRegression())
X_tr, y_tr = sample(20, 0)
X_va, y_va = sample(500, 1)
for d in [1, 3, 6, 10, 15]:
m = poly(d).fit(X_tr, y_tr)
print(f'degree {d:2d}: training MSE {mse(y_tr, m.predict(X_tr)):.4f} validation MSE {mse(y_va, m.predict(X_va)):.3f}')degree 1: training MSE 0.1263 validation MSE 0.347
degree 3: training MSE 0.0161 validation MSE 0.094
degree 6: training MSE 0.0159 validation MSE 0.093
degree 10: training MSE 0.0130 validation MSE 0.154
degree 15: training MSE 0.0090 validation MSE 6.112
Source
import matplotlib.pyplot as plt
degrees = list(range(1, 16))
tr_err = [mse(y_tr, poly(d).fit(X_tr, y_tr).predict(X_tr)) for d in degrees]
va_err = [mse(y_va, poly(d).fit(X_tr, y_tr).predict(X_va)) for d in degrees]
grid = np.linspace(-1, 1, 400).reshape(-1, 1)
fig, axes = plt.subplots(1, 4, figsize=(15, 3.3))
for ax, d, name in zip(axes[:3], [1, 4, 15], ['degree 1: underfits', 'degree 4: about right', 'degree 15: overfits']):
ax.plot(grid, np.sin(np.pi * grid), '--', color='gray')
ax.plot(grid, np.clip(poly(d).fit(X_tr, y_tr).predict(grid), -2, 2), color='C1', lw=2)
ax.scatter(X_tr, y_tr, color='C0', zorder=3); ax.set_ylim(-2, 2); ax.set_title(name)
axes[3].plot(degrees, tr_err, 'o-', label='training'); axes[3].plot(degrees, va_err, 's-', label='validation')
axes[3].set_yscale('log'); axes[3].set_xlabel('degree'); axes[3].set_title('error against capacity'); axes[3].legend()
plt.tight_layout(); plt.show()
The two curves tell the whole story:
Training error always falls as capacity grows (0.126 at degree 1, 0.009 at degree 15): a more flexible model can always fit the training points at least as well. At degree 15 it is far below the noise level 0.0625, a sign that the model is fitting the noise itself.
Validation error falls, then rises: it is lowest around degrees 3 to 6 (0.093), and explodes at degree 15 (6.1), where the curve swings wildly between the training points.
| Situation | Training error | Validation error | Diagnosis |
|---|---|---|---|
| Degree 1 | high (0.126) | high (0.347) | underfitting: too little capacity |
| Degrees 3–6 | low | lowest (0.093) | about right |
| Degree 15 | very low (0.009) | very high (6.1) | overfitting: too much capacity for 20 points |
Two rules follow. High training error means underfitting; more data will not help, more capacity will. A large gap between low training error and high validation error means overfitting; more data or less capacity will help.
9.3 The Bias–Variance Trade-off¶
Why does too much capacity hurt? Imagine drawing many different training sets of 20 points from the same source, and fitting the same kind of model to each. At a fixed input , the predictions vary from one training set to the next. For squared error, the expected error at splits into three parts:
Bias: how far the average prediction is from the truth. It comes from wrong assumptions: a straight line cannot follow a sine.
Variance: how much the prediction changes from one training set to another. It comes from sensitivity to the particular sample.
Noise : what no model can remove.
We can measure the first two directly, by refitting on 300 training sets:
x0, truth = 0.5, np.sin(np.pi * 0.5)
for d in [1, 3, 6, 9]:
preds = np.array([poly(d).fit(*sample(20, 100 + s)).predict([[x0]])[0] for s in range(300)])
print(f'degree {d}: mean prediction {preds.mean():.3f} (truth {truth:.0f}) bias² {(preds.mean() - truth) ** 2:.4f} variance {preds.var():.4f}')degree 1: mean prediction 0.483 (truth 1) bias² 0.2675 variance 0.0250
degree 3: mean prediction 0.986 (truth 1) bias² 0.0002 variance 0.0116
degree 6: mean prediction 0.985 (truth 1) bias² 0.0002 variance 0.0303
degree 9: mean prediction 0.887 (truth 1) bias² 0.0128 variance 2.2089
The straight line is consistently wrong (bias² 0.27, small variance); degree 3 is right on average with the smallest variance; by degree 9 the predictions are right on average but scattered (variance 2.2). As capacity grows, bias falls and variance rises, and the best model balances the two.
9.4 Curing Overfitting¶
Overfitting means the model has more freedom than the data can pin down. There are two families of cures: more information, or less freedom.
More data¶
The most reliable cure. With more points, the wiggles of a flexible model have less room. The learning curve below shows the validation error of degree 15 as the training set grows:
for n in [40, 80, 160, 320, 640]:
X_n, y_n = sample(n, 2)
print(f'{n:3d} points: degree 15 validation MSE {mse(y_va, poly(15).fit(X_n, y_n).predict(X_va)):8.3f} '
f'degree 1: {mse(y_va, poly(1).fit(X_n, y_n).predict(X_va)):.3f}') 40 points: degree 15 validation MSE 352.580 degree 1: 0.263
80 points: degree 15 validation MSE 0.139 degree 1: 0.253
160 points: degree 15 validation MSE 0.097 degree 1: 0.257
320 points: degree 15 validation MSE 0.074 degree 1: 0.248
640 points: degree 15 validation MSE 0.070 degree 1: 0.250
The degree-15 model goes from useless (352 with 40 points) to excellent (0.070 with 640, close to the noise level 0.0625). The straight line stays at 0.25 however much data it gets: more data cures variance, not bias. Collecting data costs money, so the learning curve also tells you whether it is worth it (Chapter 10).
A simpler model¶
Fewer features, a lower degree, a shallower tree, a larger in k-NN: every one reduces capacity. Feature selection (keeping only informative features) is a form of this.
Regularisation¶
Instead of limiting the model’s form, penalise large parameters. Ridge regression adds to the squared error; lasso adds and can set weights exactly to zero. The penalty strength is a hyperparameter.
print(f'degree 15, no penalty: validation MSE {mse(y_va, poly(15).fit(X_tr, y_tr).predict(X_va)):.3f} '
f'sum |w| = {np.abs(poly(15).fit(X_tr, y_tr)[-1].coef_).sum():.0f}')
for lam in [1e-6, 1e-2, 1, 10]:
m = poly(15, Ridge(alpha=lam)).fit(X_tr, y_tr)
print(f'ridge lambda = {lam:<6g}: training {mse(y_tr, m.predict(X_tr)):.4f} validation {mse(y_va, m.predict(X_va)):.3f} '
f'sum |w| = {np.abs(m[-1].coef_).sum():.1f}')degree 15, no penalty: validation MSE 6.112 sum |w| = 14277
ridge lambda = 1e-06 : training 0.0119 validation 0.114 sum |w| = 231.4
ridge lambda = 0.01 : training 0.0152 validation 0.105 sum |w| = 7.1
ridge lambda = 1 : training 0.0689 validation 0.240 sum |w| = 1.9
ridge lambda = 10 : training 0.1838 validation 0.487 sum |w| = 0.4
Without a penalty, the degree-15 weights add up to over 14 000 in absolute value: huge positive and negative terms cancelling each other, which is exactly what makes the curve swing. A tiny penalty () shrinks them to 231 and cuts the validation error from 6.1 to 0.114; does slightly better (0.105). But too much penalty underfits: at the weights are almost zero and the validation error is back up to 0.49. Regularisation turns capacity into a dial.
Early stopping¶
Models trained iteratively (gradient descent, boosting, neural networks) start simple and become more complex as training goes on. Watching the validation error during training and stopping when it starts to rise is a form of regularisation (Chapter 10 shows how to watch it, Chapter 16 how to use it).
Ensembles¶
Averaging many models trained on different bootstrap samples (bagging, random forests, Chapter 8) cancels much of their variance without adding bias: each tree overfits in its own way, and the errors average out.
Data augmentation¶
When more real data cannot be collected, create plausible variations of the data you have: shifted, rotated or cropped images, sentences with synonyms, audio with added noise. The model sees more variety and cannot memorise single examples. It is central in deep learning (Chapter 16).
9.5 Curing Underfitting¶
Underfitting means the model cannot represent the pattern. The cures run the other way:
| Cure | Example |
|---|---|
| Richer features | add , interactions, the age of a building from its year (Chapter 7) |
| A more flexible model | a deeper tree, a forest or boosting instead of one stump, a neural network |
| Less regularisation | a smaller , a larger |
| Train longer | more iterations, a better optimiser, a better learning rate (Chapter 10) |
| Fix the data | wrong labels or a broken feature can make any model underfit |
The straight line of Section 9.2 underfits; giving it the features and (degree 3) drops its validation error from 0.347 to 0.094. More data, on the other hand, does not help an underfitting model, as the learning curve showed.
9.6 Tuning Hyperparameters¶
Choosing hyperparameters is itself a search problem: try settings, measure each on data the model did not train on, keep the best.
A validation set¶
The simplest protocol: split the data into training, validation and test sets; fit each candidate on the training set; keep the candidate with the best validation score; refit it (optionally on training + validation); report the test score once.
Grid search¶
Try every combination of a few values per hyperparameter. With cross-validation (Chapter 10), scikit-learn’s GridSearchCV does it in one call. Here, a decision tree on the breast-cancer data: 10 depths × 5 leaf sizes = 50 settings, each cross-validated 5 times.
from sklearn.model_selection import GridSearchCV, RandomizedSearchCV
from scipy.stats import randint
full = DecisionTreeClassifier(random_state=0).fit(X_train, y_train)
print(f'no limits: depth {full.get_depth()}, training accuracy {full.score(X_train, y_train):.3f}, test {full.score(X_test, y_test):.3f}')
search = GridSearchCV(DecisionTreeClassifier(random_state=0),
{'max_depth': list(range(1, 11)), 'min_samples_leaf': [1, 2, 5, 10, 20]}, cv=5)
search.fit(X_train, y_train)
print(f'grid search: {search.best_params_}, cross-validated {search.best_score_:.3f}, test {search.score(X_test, y_test):.3f} '
f'({len(search.cv_results_["params"]) * 5} fits)')no limits: depth 5, training accuracy 1.000, test 0.902
grid search: {'max_depth': 4, 'min_samples_leaf': 5}, cross-validated 0.941, test 0.923 (250 fits)
The unlimited tree memorises the training set (accuracy 1.000) and scores 0.902 on the test set; the tuned tree (depth 4, at least 5 examples per leaf) scores 0.923. Note the order of operations: the search sees only the training set, and the test set is used once, at the end.
Random search¶
A grid grows exponentially with the number of hyperparameters: 5 values for each of 6 hyperparameters is 15 625 combinations. Random search draws a fixed number of settings at random from given ranges. Bergstra and Bengio (2012) showed why it often wins: when only a few hyperparameters really matter, a grid wastes most of its trials repeating the same values of the important ones, while random trials try a new value of every hyperparameter each time.
rand = RandomizedSearchCV(DecisionTreeClassifier(random_state=0),
{'max_depth': randint(1, 11), 'min_samples_leaf': randint(1, 21)}, n_iter=10, cv=5, random_state=0)
rand.fit(X_train, y_train)
print(f'random search: {rand.best_params_}, cross-validated {rand.best_score_:.3f}, test {rand.score(X_test, y_test):.3f} (50 fits)')random search: {'max_depth': 5, 'min_samples_leaf': 7}, cross-validated 0.932, test 0.916 (50 fits)
Ten random settings (50 fits instead of 250) reach almost the same quality. Beyond random search, Bayesian optimisation (Optuna, scikit-optimize) chooses each new trial from the results of the previous ones, and is the usual choice when each training run is expensive.
9.7 Summary¶
Parameters are learned by
fitfrom the training set; hyperparameters are chosen before training, on validation data. The test set chooses nothing.Hyperparameters mostly control capacity. Training error always falls with capacity; validation error falls, then rises.
Underfitting: high training error (high bias). Overfitting: low training error, much higher validation error (high variance).
Bias² + variance + noise = expected squared error; capacity trades the first two.
Cures for overfitting: more data, a simpler model, regularisation, early stopping, ensembles, augmentation. Cures for underfitting: richer features, a more flexible model, less regularisation, longer training.
Tune with a validation set or cross-validation: grid search for a few hyperparameters, random search or Bayesian optimisation for many.
Exercises¶
For k-nearest neighbours, a decision tree and logistic regression, list the parameters and the hyperparameters. Why is it said that k-NN has no parameters?
A model has a training error of 2% and a validation error of 25%. Name the problem and three things you would try.
Another model has a training error of 24% and a validation error of 25%. Name the problem. Would collecting more data help? Why?
Explain, using the bias–variance decomposition, why averaging many deep trees (a random forest) generalises better than one deep tree.
In ridge regression, what happens to the weights and to the training error as ? And as ?
A colleague tries 200 hyperparameter settings and reports the best test-set accuracy. What is wrong, and how should it be done?
You have 4 hyperparameters but only budget for 30 training runs. Grid or random search? Justify.
Further Reading¶
T. Hastie, R. Tibshirani, J. Friedman, The Elements of Statistical Learning, 2nd ed., Springer, 2009, Chapter 7 (model assessment and selection).
J. Bergstra, Y. Bengio, “Random search for hyper-parameter optimization”, JMLR, 2012.
M. Belkin et al., “Reconciling modern machine-learning practice and the classical bias–variance trade-off”, PNAS, 2019 (double descent).
The scikit-learn user guide, “Tuning the hyper-parameters of an estimator”.