Sub topic 15
Tuning with Optuna
This chapter assumes you know the following:
- Basic scikit-learn, including
cross_val_score. - Why a test set stays untouched during tuning.
- How grid search and random search work.
Install the library with pip install optuna.
What Optuna adds
Grid and random search choose every setting in advance. Optuna is a tuning library that runs a loop of trials instead. Each trial is one attempt: Optuna proposes a setting, your code scores it, and Optuna records the result. The default sampler, called TPE, uses the recorded results to propose more promising settings next. A sampler is the component that picks the next setting to try.
You supply an objective function, which takes a trial and returns a score. A study is the object that holds all trials and runs the loop.
A complete example
This code tunes a random forest. The objective asks the trial for each setting with a suggest_ method, which declares both the range and the type. It returns the mean cross-validated accuracy on the training data.
import optuna
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score, train_test_split
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.2, random_state=0, stratify=y
)
def objective(trial):
params = {
"n_estimators": trial.suggest_int("n_estimators", 50, 300),
"max_depth": trial.suggest_int("max_depth", 2, 16),
"min_samples_leaf": trial.suggest_int("min_samples_leaf", 1, 10),
}
model = RandomForestClassifier(random_state=0, **params)
return cross_val_score(model, X_train, y_train, cv=5).mean()
study = optuna.create_study(
direction="maximize",
sampler=optuna.samplers.TPESampler(seed=0),
)
study.optimize(objective, n_trials=30)
print(study.best_params, study.best_value)
final = RandomForestClassifier(random_state=0, **study.best_params)
final.fit(X_train, y_train)
print("Test accuracy:", final.score(X_test, y_test))The last three lines refit the best settings on all training data and score the test set once. The search never sees the test set.
Choices that matter
- Direction.
create_studyminimizes by default. Passdirection="maximize"for accuracy or AUC. Leaving it out is a common mistake, and it makes Optuna search for the worst model. - Scale. For learning rates and regularization strengths, use
trial.suggest_float("lr", 1e-4, 1e-1, log=True). Withoutlog=True, most samples land in the top decade of the range. - Seed.
TPESampler(seed=0)makes the proposals repeatable. The model's ownrandom_statemust also be fixed. Parallel runs withn_jobscan still vary in order. - Budget.
n_trialscaps the number of trials.timeout=600caps the run at 600 seconds. Use whichever matches the limit you actually have.
Pruning poor trials
A pruner stops trials that look weak before they finish. It needs intermediate scores, so the objective calls trial.report(score, step) after each epoch or boosting round. It then checks trial.should_prune() and raises optuna.TrialPruned() if that returns true. MedianPruner and HyperbandPruner are the usual choices. A cross-validation loop that returns only one number gives the pruner nothing to act on.
Save results with study.trials_dataframe() and store the seed, n_trials, and library versions next to them.
Exercise
Your objective returns validation loss, and Optuna keeps reporting settings with the highest loss as best. What is the likely cause, and what is the fix?
Show answer
The study used the default direction, "minimize" was expected but you may have set "maximize" (or the reverse). Check create_study(direction=...). For loss, use direction="minimize". For accuracy, use direction="maximize".