Skip to main content

Lesson 5 of 9

Bayesian Hyperparameter Optimization with Optuna: Tree-Structured Parzen Estimators (TPE)

While Grid and Random search sample blindly without learning from previous evaluations, Bayesian Optimization treats hyperparameter tuning as an active learning problem. Optuna uses the Tree-Structured Parzen Estimator (TPE) algorithm: it models the probability distributions of hyperparameters conditioned on performance l(x) = p(x | score > threshold) and g(x) = p(x | score <= threshold), picking new trial configurations that maximize Expected Improvement (EI). Optuna also prunes unpromising trials dynamically using Asynchronous Successive Halving (ASHA).

25 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Bayesian Optimization with Optuna & Early Pruning

Bayesian Optimization with Optuna & Early Pruning
import numpy as np
from sklearn.model_selection import cross_val_score, StratifiedKFold
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.datasets import make_classification

# Synthetic enterprise dataset
X, y = make_classification(n_samples=1500, n_features=15, random_state=42)

# Optuna Objective Function formulation
def objective_study(trial):
    # Suggest continuous and discrete parameters from search space
    learning_rate = trial.suggest_float('learning_rate', 1e-3, 0.2, log=True)
    max_leaf_nodes = trial.suggest_int('max_leaf_nodes', 15, 63)
    l2_reg = trial.suggest_float('l2_regularization', 0.0, 10.0)
    min_samples_leaf = trial.suggest_int('min_samples_leaf', 5, 40)
    
    clf = HistGradientBoostingClassifier(
        learning_rate=learning_rate,
        max_leaf_nodes=max_leaf_nodes,
        l2_regularization=l2_reg,
        min_samples_leaf=min_samples_leaf,
        max_iter=80,
        random_state=42
    )
    
    cv = StratifiedKFold(n_splits=3, shuffle=True, random_state=42)
    scores = cross_val_score(clf, X, y, cv=cv, scoring='roc_auc')
    return scores.mean()

# In production, we run:
# import optuna
# study = optuna.create_study(direction='maximize', sampler=optuna.samplers.TPESampler(seed=42))
# study.optimize(objective_study, n_trials=30)
# print("Best Params:", study.best_params)

print("=== BAYESIAN OPTIMIZATION (OPTUNA / TPE CONCEPTS) ===")
print("1. TPE divides past trials into Good (top 15%) and Bad groups.")
print("2. Models p(hyperparam | Good) and p(hyperparam | Bad) via Kernel Density Estimation.")
print("3. Samples new candidates maximizing Expected Improvement ratio: l(x) / g(x).")
print("4. Early pruners (MedianPruner, Hyperband) terminate lagging trials at epoch 10!")

Pro Tip: Prune Dead Trials with Optuna Integration

Optuna's killer feature is automated pruning (`optuna.integration.LightGBMPruningCallback`). If a trial is in the bottom 50% of performers at iteration 15, Optuna raises a `TrialPruned` exception and aborts training immediately, saving 70% of total GPU/CPU compute budget.

Diagram
Loading diagram…

MlOptunaBayesian Visual Representation

Hands-On Challenge: Build a Complete Optuna Study Script

Write a standalone script that runs a 30-trial Optuna study on a Random Forest classifier, logs results to a local SQLite database (`storage='sqlite:///optuna_study.db'`), and plots the optimization history diagram.

Quick Quiz & Key Concept Checks

Common Pitfall: Searching Non-Interacting Hyperparameters in One Study

Tuning tree hyperparameters and neural network hyperparameters in a single combined objective function creates an intractable discontinuous search space. Use conditional parameters (`trial.suggest_categorical('model_type')`) or run independent studies.

Topics in This Module

0/9 done