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

Open in Colab

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 ww and bias bb of a linear model, the questions and thresholds of a decision tree, the class frequencies of Naive Bayes. Nobody types them in; fit finds 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 kk, the strength of a penalty λ\lambda, the learning rate η\eta of gradient descent.

ModelParameters (learned)Hyperparameters (chosen)
Linear regressionweights wjw_j, bias bbpolynomial degree, penalty λ\lambda (ridge, lasso)
Logistic regressionweights, biaspenalty C=1/λC = 1/\lambda, class weights
Decision treethe questions and thresholds, the leaf predictionsmaximum depth, minimum samples per leaf
Random forestevery tree’s parametersnumber of trees, features tried per split, depth
k-nearest neighboursnone: it stores the training setkk, the distance, the weighting
Naive Bayesclass priors, per-class feature probabilitiesLaplace smoothing α\alpha
Neural network (Chapter 15)all weights and biaseslayers, 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:

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 [−1,1][-1, 1] (noise standard deviation 0.25, so the best possible mean squared error is 0.252=0.06250.25^2 = 0.0625), fit polynomials of increasing degree, and measure the error on the 20 training points and on 500 fresh validation points.

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
<Figure size 1500x330 with 4 Axes>

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.

SituationTraining errorValidation errorDiagnosis
Degree 1high (0.126)high (0.347)underfitting: too little capacity
Degrees 3–6lowlowest (0.093)about right
Degree 15very 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 x0x_0, the predictions vary from one training set to the next. For squared error, the expected error at x0x_0 splits into three parts:

E[(f^(x0)−y)2]=(E[f^(x0)]−f(x0))2⏟bias2+Var⁡[f^(x0)]⏟variance+σ2⏟noise\mathbb{E}\big[(\hat f(x_0) - y)^2\big] = \underbrace{\big(\mathbb{E}[\hat f(x_0)] - f(x_0)\big)^2}_{\text{bias}^2} + \underbrace{\operatorname{Var}\big[\hat f(x_0)\big]}_{\text{variance}} + \underbrace{\sigma^2}_{\text{noise}}
  • 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 σ2\sigma^2: what no model can remove.

We can measure the first two directly, by refitting on 300 training sets:

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:

 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 kk 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 λ∑jwj2\lambda \sum_j w_j^2 to the squared error; lasso adds λ∑j∣wj∣\lambda \sum_j |w_j| and can set weights exactly to zero. The penalty strength λ\lambda is a hyperparameter.

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 (λ=10−6\lambda = 10^{-6}) shrinks them to 231 and cuts the validation error from 6.1 to 0.114; λ=0.01\lambda = 0.01 does slightly better (0.105). But too much penalty underfits: at λ=10\lambda = 10 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:

CureExample
Richer featuresadd x2,x3x^2, x^3, interactions, the age of a building from its year (Chapter 7)
A more flexible modela deeper tree, a forest or boosting instead of one stump, a neural network
Less regularisationa smaller λ\lambda, a larger CC
Train longermore iterations, a better optimiser, a better learning rate (Chapter 10)
Fix the datawrong labels or a broken feature can make any model underfit

The straight line of Section 9.2 underfits; giving it the features x2x^2 and x3x^3 (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.

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.

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.

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.

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 fit from 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

  1. 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?

  2. A model has a training error of 2% and a validation error of 25%. Name the problem and three things you would try.

  3. Another model has a training error of 24% and a validation error of 25%. Name the problem. Would collecting more data help? Why?

  4. Explain, using the bias–variance decomposition, why averaging many deep trees (a random forest) generalises better than one deep tree.

  5. In ridge regression, what happens to the weights and to the training error as λ→∞\lambda \to \infty? And as λ→0\lambda \to 0?

  6. A colleague tries 200 hyperparameter settings and reports the best test-set accuracy. What is wrong, and how should it be done?

  7. 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”.