Sub topic 1
What Hyperparameter Optimisation Is and Why Automate It
Every machine learning model has settings you choose before training starts. Hyperparameter optimisation (HPO) is the search for the settings that give the best validation score. This chapter defines the problem, shows why manual tuning breaks down, and introduces the loop that Optuna automates. Later chapters cover each part of that loop in detail.
Prerequisites
This chapter assumes you already have the following:
- Basic Python, including functions and exceptions.
- Experience training and validating a model with scikit-learn.
- A clear sense of the difference between parameters and hyperparameters.
- Knowledge of train/validation splits and cross-validation.
You also need optuna and scikit-learn installed, for example with pip install optuna scikit-learn.
Parameters and hyperparameters
Parameters are values the model learns from data. Examples are the weights of a linear model or the split thresholds in a decision tree. Training sets them for you.
Hyperparameters are values you fix before training, and training does not change them. Examples are the regularisation strength C of an SVM, the max_depth of a random forest, and the learning rate of a neural network. They control how the model learns or how flexible it can be, so they often decide whether the model underfits or overfits.
Choosing hyperparameters is an optimisation problem with three parts:
- A search space: which hyperparameters exist and which values each may take.
- An objective: a number computed from a trained model, usually a cross-validated score or a validation loss.
- A budget: how many evaluations, or how much time, you can spend.
The goal is to find the point in the search space with the best objective value within that budget.
Why the objective is hard to optimise
The objective behaves differently from the functions you meet in calculus.
- It is a black box. You can evaluate it at a point, but you cannot differentiate it with respect to
max_depthor to the choice of kernel. - It is expensive. Each evaluation trains a model, sometimes for hours.
- It is noisy. Different random seeds or data splits give slightly different scores for the same hyperparameters.
- It mixes types. Some hyperparameters are real numbers, some are integers, and some are categories such as the choice of classifier.
- Some hyperparameters only matter in certain cases.
gammais meaningless if you pick a linear kernel.
Because of this, gradient descent does not apply. Search methods that only need objective values are used instead.
Why manual tuning does not scale
Most people start by hand: change a value, rerun, compare, repeat. This works for one or two hyperparameters. It fails for these reasons:
- You forget which combinations you tried, and results end up in notebook cells or filenames.
- Your choices follow habit. You tend to test round numbers like
0.1and0.01and never look at the region between them. - Interactions are hard to see. The best learning rate often depends on the batch size or the depth.
- Your time is the bottleneck. A machine can evaluate candidates while you sleep.
The usual next step is grid search. It tries every combination of a fixed list of values per hyperparameter. The number of runs grows multiplicatively:
| Hyperparameters | Values each | Total runs |
|---|---|---|
| 1 | 5 | 5 |
| 2 | 5 | 25 |
| 3 | 5 | 125 |
| 4 | 5 | 625 |
| 5 | 5 | 3125 |
Grid search also wastes effort. If only one of five hyperparameters really matters, most grid points repeat the same value of that one, so you learn little from them. Random search samples each hyperparameter independently and tests many more distinct values of the important ones. It is a strong baseline, but it ignores what earlier trials taught it.
The automated loop
Automated HPO replaces the human in the loop with a program. The loop is the same in every library:
A smart sampler uses the recorded results to choose the next proposal. A pruner can stop step B early when a trial looks poor. Both ideas get their own chapters later.
The same search by hand
Here is a random search written without any library. It tunes the SVM regularisation strength C on the iris data set.
import random
from sklearn.datasets import load_iris
from sklearn.model_selection import cross_val_score
from sklearn.svm import SVC
X, y = load_iris(return_X_y=True)
random.seed(0)
best_score, best_c = -1.0, None
for _ in range(20):
c = 10 ** random.uniform(-3, 3)
score = cross_val_score(SVC(C=c, gamma="scale"), X, y, cv=3).mean()
if score > best_score:
best_score, best_c = score, c
print(best_c, best_score)Two details matter here. The value of C is drawn on a log scale, because the useful range spans several orders of magnitude. You also had to write the bookkeeping yourself. As soon as you want to resume after a crash, run in parallel, or log every trial, this script grows quickly.
The same search with Optuna
Optuna keeps the loop, the bookkeeping and the sampling strategy in one library. Its smallest example minimises a one-variable function, so you can see the moving parts without a model in the way.
import optuna
def objective(trial):
x = trial.suggest_float("x", -10, 10)
return (x - 2) ** 2
study = optuna.create_study(direction="minimize")
study.optimize(objective, n_trials=50)
print(study.best_params)
print(study.best_value)The pieces map onto the loop above:
objectiveis steps B and C. It receives atrial, asks it for hyperparameter values, and returns a score.trial.suggest_float("x", -10, 10)is step A. The search space is declared inside the function as the code runs.create_studymakes the object that records results (step D).directionsays whether lower or higher is better.study.optimize(..., n_trials=50)runs the loop until the budget is spent (step E).study.best_paramsandstudy.best_valueare step F.
The best x should land close to 2, the true minimum. Because the sampler is random, the exact digits change from run to run unless you seed it. Seeding is covered in a later chapter.
What automation gives you
- Coverage: the search spends its budget systematically instead of on your habits.
- Efficiency: samplers learn from past trials, and pruners cut bad trials short.
- Records: every trial's parameters, value and state are stored and can be queried or plotted.
- Scale: the same study can be stored in a database and run by several workers.
What automation does not fix
- Overfitting the validation data. The more trials you run, the more likely the best score is partly luck. Keep a final test set that the search never sees.
- A bad search space. If the best value lies outside your ranges, no sampler can find it. Check whether the best trial sits at an edge of a range.
- A noisy or flawed objective. If the score is computed on a leaky split, the search will exploit the leak.
- Missing fundamentals. Features, data quality and model choice usually matter more than the last decimal of a learning rate.
Where this chapter fits
The next chapters name the core objects in detail: the study, the trial and the objective function. After that come search spaces, samplers, pruning, storage and diagnostics. All of them are parts of the loop shown in the diagram.
Exercise
You tune 6 hyperparameters with grid search, using 4 values for each. How many models must you train, and why does random search often find a good configuration with far fewer runs?
Show answer
Grid search needs 4^6 = 4096 runs. Random search samples every hyperparameter independently, so each run tests a new value of each one. If only one or two hyperparameters matter, 50 random runs test 50 distinct values of them, while a grid tests only 4.
Exercise
In the Optuna example, you change direction="minimize" to direction="maximize" but leave the objective (x - 2) ** 2 unchanged. What will study.best_params approximately contain, and why?
Show answer
It will contain an x near -10 or 10, whichever edge of the range gives the larger squared distance from 2 (here, -10). The study now searches for the largest value of the objective, so it moves away from the true minimum at x = 2.