Bayesian Optimization with Optuna
Use Optuna trials and pruning to efficiently explore expensive hyperparameter spaces.
In plain words
Optuna tries settings for your model, learns which kinds of settings work best and picks the next ones more cleverly, stopping bad attempts early to save time.
Think of it like…
Searching for a good restaurant in a new city: instead of sampling randomly, you notice which neighbourhoods had the best meals so far and try nearby, but you also leave a trial of unfamiliar districts, and you walk out of a place after the first bad course rather than finishing the meal.
Where you’ve seen it
A boosting model takes 12 minutes per trial with 5-fold CV. A random search of 100 trials would take 100 × 12 = 1,200 minutes (20 hours). With Optuna the team defines learning_rate (log-uniform 0.001 to 0.3), max_depth (3 to 10), subsample (0.5 to 1.0), colsample_bytree and min_child_weight, reports the validation score after each CV fold and uses a MedianPruner, which stops a trial when its running score is below the median of earlier trials at the same step. If 60 of 100 trials are pruned after 10% of their budget, the cost is 40 × 1 + 60 × 0.1 = 46 trial-equivalents, 552 minutes (9.2 hours), a 54% saving. TPE splits observed trials into a good group and a bad group, models parameter densities l(x) for good and g(x) for bad and proposes the candidate maximising l(x)/g(x): a learning rate of 0.05 with l = 0.30 and g = 0.05 scores 6.0, while 0.01 with l = 0.04 and g = 0.12 scores 0.33. The best CV AUC is 0.874 against 0.862 for defaults; the parameter-importance plot shows learning_rate and max_depth dominate, and a best max_depth of 10 at the edge of the range prompts widening the space.
Words you’ll hear
- Study / trial
- A study is the optimisation session; a trial is one evaluation of a parameter set.
- TPE sampler
- Models good and bad parameter regions and proposes points with a high ratio l(x)/g(x).
- Pruner
- A rule that stops unpromising trials early using intermediate results.
- Define-by-run search space
- Parameters are suggested inside the objective, allowing conditional spaces.
Visual diagram
Theory & deep dive
How TPE and Optuna work
Classic Bayesian optimisation fits a surrogate model (often a Gaussian process) to observed (parameters, score) pairs and chooses the next point by an acquisition function such as expected improvement. TPE reverses the modelling: it splits the completed trials by score into a good set (the top fraction, for example the best 10 to 25%) and a bad set, estimates a density l(x) over parameters for good trials and g(x) for bad ones using Parzen (kernel) estimators, and picks the candidate that maximises l(x)/g(x), which is proportional to expected improvement. It handles categorical and conditional parameters naturally, scales to many dimensions better than Gaussian processes and starts with a number of random startup trials to seed the densities. Optuna also offers CMA-ES for continuous spaces, Gaussian-process and random samplers, and multi-objective optimisation (for example accuracy versus latency).
In code: study = optuna.create_study(direction="maximize", sampler=optuna.samplers.TPESampler(seed=0), pruner=optuna.pruners.MedianPruner(n_startup_trials=5, n_warmup_steps=1)), then study.optimize(objective, n_trials=100, n_jobs=4). Inside the objective, trial.suggest_float("learning_rate", 1e-3, 0.3, log=True), trial.suggest_int("max_depth", 3, 10) and trial.suggest_categorical(...) define the space (define-by-run, so a parameter can exist only when another takes a certain value). trial.report(value, step) followed by if trial.should_prune(): raise optuna.TrialPruned() enables pruning, and integrations (LightGBM, XGBoost, Keras, PyTorch Lightning callbacks) report automatically. Persist studies with storage="sqlite:///study.db" so runs can resume and parallel workers share results.
Among completed trials, learning rates near 0.05 are common in the good group (density l = 0.30) and rare in the bad group (g = 0.05): ratio 6.0. Rates near 0.01 are rare among good trials (0.04) and common among bad (0.12): ratio 0.33. TPE samples more near 0.05 next.
Pruning, budgeting and pitfalls
Pruning compares a trial's intermediate results with those of earlier trials and stops it if it is unlikely to finish among the best: MedianPruner stops a trial whose running score is below the median at the same step; SuccessiveHalving and Hyperband allocate more resources to survivors. It needs a meaningful intermediate signal (a validation metric per CV fold, per boosting round or per epoch). In the example, pruning 60 of 100 trials after 10% of their budget cuts cost to 40 × 1 + 60 × 0.1 = 46 trial-equivalents (552 minutes instead of 1,200). Set n_startup_trials and n_warmup_steps so early noisy scores don't prune good trials, and be cautious when learning curves cross (slow starters that finish best get pruned).
Practical pitfalls: a noisy objective (small validation folds, stochastic training) makes TPE chase noise, so average over folds or seeds and keep the CV scheme fixed; overfitting the validation signal after hundreds of trials (use nested CV or a test set for the final estimate); search-space bounds: if the best value sits at an edge (max_depth = 10 at the limit), widen the range; log scales for rates and penalties; parallelism reduces TPE's sample efficiency because workers propose points without each other's results; and reproducibility (fixed seeds, versioned data and code, stored studies). Analyse the study with plot_optimization_history, plot_param_importances and plot_parallel_coordinate to learn which parameters matter, fix the unimportant ones and re-run a narrower search. Record the winning configuration, seed and score, and re-tune only when data or objectives change.
100 trials at 12 min = 1,200 min. 60 pruned at 10% of the budget (1.2 min) and 40 completed (12 min): 60 × 1.2 + 40 × 12 = 72 + 480 = 552 min (9.2 h), a 54% saving, with the same best-found configuration in this study.
How it works, step by step
Step 1 of 41. Write the objective
Build the pipeline from suggested parameters, evaluate with fixed CV folds and report intermediate scores.
- Seeds
- fixed
When to use it & trade-offs
What it is
Bayesian (sequential model-based) optimisation tunes hyperparameters by using the results of earlier trials to decide which configuration to try next, instead of sampling blindly. Optuna is a popular Python framework for it: you write an objective function that builds and scores a model from parameters suggested by a trial (trial.suggest_float("lr", 1e-3, 0.3, log=True)), create a study that maximises or minimises the objective, and Optuna's default TPE sampler (Tree-structured Parzen Estimator) proposes configurations likely to beat the best so far. Pruners (median, successive halving, Hyperband) stop unpromising trials early based on intermediate scores, saving most of the compute. Optuna supports conditional search spaces, parallel and distributed trials, persistent storage and visualisations.
Why it matters: When each trial is expensive (a 12-minute cross-validated boosting fit, a neural network run), blind grids and random draws waste budget on poor regions. Sequential optimisation concentrates trials where the model's data suggests improvements, and pruning avoids paying full price for trials that are clearly bad. The risk is the same as with any search: overfitting the validation signal, noisy objectives and misleading boundaries, so good practice still matters.
When to reach for it
- Tuning boosting and neural network models with costly trials
- Conditional spaces (kernel-specific or optimiser-specific parameters)
- Multi-objective trade-offs such as accuracy versus latency
When to avoid or be careful
- Reporting the best study score as the expected performance
- Pruning with unreliable early signals
- Ignoring that the best value sits at a search-range edge
Search strategies
Strengths: Sample-efficient; prunes bad trials; flexible spaces.
Watch out: Needs a good intermediate signal; noisy objectives mislead.
Strengths: Easy and parallel; no assumptions.
Watch out: Doesn't learn from earlier trials.
Strengths: Exhaustive and transparent.
Watch out: Exponential cost.
Interview signals & numbers to know
When this topic comes up
- “Each trial takes ten minutes”
- TPE sampler
- MedianPruner and Hyperband
- Define-by-run search spaces
- Optuna study storage
Benchmarks & rules of thumb
- 40×1 + 60×0.1 = 46
- trial-equivalents with 60 of 100 trials pruned at 10%
- 1,200 → 552 minutes
- total time without and with pruning
- l(x)/g(x)
- TPE acquisition ratio (6.0 vs 0.33 in the example)
Common mistakes & follow-ups
Common interview mistakes
- Using a different CV split for each trial.
- Starting TPE with too few random trials and locking in early noise.
- Running many parallel workers and expecting the same sample efficiency.
Likely interviewer follow-ups
- How does TPE choose the next trial?
- How does pruning save compute?
- How would you avoid overfitting the validation set when using Optuna?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Bayesian Optimization with Optuna with data science interview Q&A and hands-on practice.