Hyperparameter Tuning and Model Selection

What hyperparameters are, how they differ from learned parameters, and practical approaches to tuning (grid search, random search, Bayesian optimization) without overfitting.


Training a model fits its parameters to the data. But somebody has to decide how the training itself is run: how big the adjustments are at each step, how long to keep going, how large the network is. Those decisions are called hyperparameters. They are chosen by people (or by a search program), they can change the result a good deal, and choosing them is a place where a project can talk itself into a result that isn't there.

You will probably never set a learning rate yourself. This article is so that you can follow the conversation when your engineers do, and so that you can ask a few useful questions about how the choices were made.

Parameters and hyperparameters

Parameters are the numbers inside the model that training adjusts. A network has millions of them, nobody sets them by hand, and nobody looks at them individually.

Hyperparameters are the settings that are fixed before training starts. A statistical analogy: in a penalized regression such as the lasso, the coefficients are parameters, and the strength of the penalty is a hyperparameter. The fitting procedure finds the coefficients. You have to choose the penalty, typically by cross-validation.

The ones you'll hear about

There are dozens. These are the ones that come up most.

The learning rate is the size of the step the model takes each time it adjusts its parameters. Too large and training lurches about and never settles. Too small and it crawls, or gets stuck somewhere mediocre. It is generally the single most influential setting, and it is usually varied over the course of training on a schedule, starting higher and ending lower.

The batch size is how many cases the model looks at before each adjustment. It is often limited by GPU memory, especially with 3D volumes, where a batch may be two scans.

The number of epochs is how many passes training makes through the whole training set. Too few and the model hasn't finished learning. Too many and it starts memorizing (see 3.5 Overfitting, Underfitting, and Regularization).

Regularization settings, such as weight decay and dropout rate, control how strongly the model is discouraged from memorizing.

Architecture choices are hyperparameters too: which network, how deep, how wide, what input resolution. So are the preprocessing and augmentation settings (see 2.5 Data Preprocessing and Augmentation), the choice of loss function, and, when fine-tuning, how much of a pretrained network to freeze (see 3.3 Transfer Learning).

The decision threshold that turns a score into "positive" or "negative" is in effect another one, and it gets chosen the same way as the rest: on the validation set, never the test set.

How they get chosen

Every method has the same skeleton. Pick a configuration, train a model with it, measure performance on the validation set, and repeat. The methods differ in how they pick the next configuration to try.

By hand

An engineer starts from settings that worked for a similar problem, trains, looks at the curves and adjusts. Less politely, this is known as "graduate student descent." It's how a lot of real work gets done, and it works well in experienced hands. Its weakness is that it is hard to document and hard for someone else to repeat.

Choose a few values for each hyperparameter and try every combination. Three learning rates, three weight decays and three dropout rates make 27 training runs. It is simple and thorough, and the number of runs explodes as you add hyperparameters.

Try configurations drawn at random from ranges you specify. This sounds like a lazier version of grid search, and it turns out to be better. In 2012 James Bergstra and Yoshua Bengio showed that random search finds good configurations in fewer runs than a grid. The reason is that usually only one or two hyperparameters have much effect on a given problem. A grid of 27 runs tests only three distinct values of the important one, while 27 random runs test 27.

Bayesian optimization and its relatives

These methods use the results so far to decide where to look next. They build a rough statistical model of how performance depends on the settings and choose the next configuration where that model predicts the most promise. Other methods save compute by starting many configurations and stopping the unpromising ones early. There are free tools that do all of this, and your engineers will probably use one for any search of more than a few dozen runs.

For most clinical research projects, the search doesn't need to be elaborate. Starting from a well-tested configuration and running a modest random search over the learning rate and one or two other settings gets most of the available benefit. Systems such as nnU-Net, mentioned in 2.1, go further and set nearly everything by rule from the properties of the dataset, with good results.

Tuning is fitting

This section is about the credibility of the result, so it is the one to read if you only read one.

Each time we choose a configuration because it scored best on the validation set, we are fitting to the validation set. One choice among three options is a small amount of fitting. The best of five hundred configurations is a lot. The winning validation score is then optimistic, for the reason described in 3.2 Training, Validation, and Test Sets: part of what made that configuration win was luck on those particular cases.

A made-up example shows the size of the effect. Say a validation set has 200 cases and the true accuracy of every reasonable configuration is 85%. With 200 cases, the measured accuracy of any one of them will wobble by two or three points either way from sampling alone. Try a hundred configurations and the best is likely to read 90% or so, purely by chance. Nothing about it is better than the others. If we then report that 90%, we have reported noise.

This is the machine learning version of what statisticians call the garden of forking paths, or researcher degrees of freedom. The remedies are the same as in any other analysis.

Keep the test set out of it entirely. However much tuning was done on the validation set, a test set that played no part gives an unbiased number.

Use a validation set large enough that small differences mean something, or cross-validation when the data is small. If tuning is done inside cross-validation and you also want a performance estimate from it, the tuning has to be nested inside each fold, as explained in 4.6 Cross-Validation Strategies for Medical Data.

Limit the search to what the data can support. A hundred validation cases can't meaningfully rank five hundred configurations.

Write down the search before running it: which hyperparameters, which ranges, how many runs. Then report it.

The run-to-run noise

There's a second source of noise that surprises people from outside the field. Train the same model twice on the same data with the same hyperparameters and you'll get two slightly different models, because training involves random choices: the starting weights, the order in which cases are shown, the random augmentations. The starting point for all that randomness is a number called the seed.

The difference between seeds can be a point or more of AUC on a small dataset. In 2021 Xavier Bouthillier and colleagues measured the sources of variance in machine learning benchmarks and found that variation from things like the data split and the random seed was of the same order as the improvements that papers were claiming for new methods.

So before concluding that configuration A beats configuration B, it's worth asking how much the result moves when the same configuration is simply run again. The usual practice is to train each serious candidate several times with different seeds and report the mean and the spread. If the gap between two models is smaller than the spread between seeds, we don't really know which is better.

Choosing the final model

When the search is done there is usually a cluster of configurations with nearly the same validation score. A few principles help in choosing among them.

If two models are within noise of each other, prefer the simpler one. It will be cheaper to run, easier to explain and probably less fragile. Statisticians will recognize this as the same reasoning as the one-standard-error rule used for choosing a lasso penalty.

Look past the headline metric. Two models with the same AUC can differ in calibration, in performance at the operating point you care about, and in how they do on subgroups (see 4.2 The ROC Curve and AUC). The choice of which metric to tune for is a clinical decision, and it's better made at the start than left to a default.

Sometimes the best answer is several models. Averaging the predictions of a handful of models trained with different seeds or settings, called an ensemble, is usually a bit more accurate and better calibrated than any one of them. It costs proportionally more to run.

And once the model is chosen, the choice is final. It goes to the test set once.

Comparing against a baseline fairly

Many papers claim that a new method beats an existing one. A common weakness in those claims is that the new method was tuned carefully and the old one was run with default settings. Some of the reported gain is then the tuning.

If you are making such a comparison, give the baseline the same tuning budget as your own method, on the same validation data. If you are reading one, check whether the paper says how the baseline was tuned. 4.7 Comparing Models covers the statistical tests for deciding whether a difference is real.

What belongs in the paper

A reader should be able to tell how much searching went into the result. That means reporting:

  • The hyperparameters that were tuned and the ranges searched.
  • The search method and the number of configurations tried.
  • The data used for selection (which validation set, or which cross-validation scheme).
  • The final values.
  • The number of seeds and the spread of results across them.

This usually goes in a supplementary table. It takes ten minutes to write if the experiments were tracked as they were run, and it is close to impossible to reconstruct afterwards if they weren't (see 3.7 Tools and Infrastructure and 9.2 Writing the Methods Section for an AI Study).

Questions worth asking your engineers

You don't need to judge the answers in detail. Clear answers are themselves a good sign.

  • Which settings did we tune, and how many configurations did we try?
  • What data was used to pick the winner?
  • How much does the result change if we just run the winner again with a different seed?
  • Was the baseline tuned as carefully as our model?
  • Has anything been chosen by looking at the test set?

Key takeaways

  • Hyperparameters are the settings chosen before training, such as learning rate, batch size, training length, regularization strength and architecture. Parameters are what training learns.
  • Search methods range from manual adjustment through grid and random search to Bayesian optimization. Random search beats grid search for the same number of runs.
  • Selecting the best of many configurations on a validation set is a form of fitting, and it makes the winning validation score optimistic.
  • The same configuration gives different results with different random seeds. Differences smaller than that spread aren't evidence of anything.
  • Among models within noise of each other, prefer the simpler, and check calibration and subgroup performance as well as the headline metric.
  • Tune baselines as carefully as the proposed method.
  • Report what was searched, how, on which data, and how many runs.

This article is part of the AI in Clinical Research Knowledge Base.