Sub topic 1
What Hyperparameter Optimisation Is and Why Automate It
Prerequisites
Assume you know basic Python functions, model training, validation splits, and the difference between model parameters and hyperparameters. A hyperparameter is a setting chosen before training, such as a tree's maximum depth or a support vector machine's regularisation strength.
The Search Problem
Hyperparameter optimisation (HPO) is the automated search for hyperparameter values that produce the best validation result. Manual tuning is slow and can miss useful combinations. HPO evaluates many configurations according to a metric such as accuracy, loss, or mean squared error.
The search must use data that is separate from the final test set. Otherwise, repeated decisions based on the validation data can overfit that data.
Studies and Trials
A study is the complete optimisation run. It records the search direction, trials, configurations, results, and sampler state. A trial is one evaluation of the objective function with one set of hyperparameters.
Optuna can minimise a loss or maximise a score:
| Goal | Study direction | Objective returns |
|---|---|---|
| Reduce error | `minimize` | A loss value |
| Improve accuracy | `maximize` | A score |
Writing an Objective Function
The objective function receives a trial, chooses hyperparameters, trains or evaluates a model, and returns one numeric value. Optuna calls it once for each trial.
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)Here, the best value is near x = 2. In a machine-learning workflow, the function would usually return a cross-validation score or loss.
Defining the Search Space
Optuna's define-by-run API lets the objective describe its own search space:
suggest_float("learning_rate", 1e-4, 1e-1, log=True)searches continuous, log-scaled values.suggest_int("max_depth", 2, 16)searches integer values.suggest_categorical("model", ["svc", "rf"])chooses from named alternatives.
You can also define conditional spaces. For example, after choosing "svc", suggest C; after choosing "rf", suggest max_depth. This prevents irrelevant parameters from being evaluated for the wrong model.
Exercise
What does one Optuna trial represent?
Show answer
One objective evaluation using one suggested set of hyperparameter values.