37 — Python Power Tools

Optuna#

PythonPractice 1 min read
◆ The PatternSmart hyperparameter tuning — TPE, pruning, study visualisation, any framework

Optuna is a hyperparameter optimisation framework that uses TPE (Tree-structured Parzen Estimator) to intelligently search the parameter space. It supports pruning (killing bad trials early) and integrates with scikit-learn, XGBoost, PyTorch, and more.

// Optuna search space exploration
FeatureWhat it does
TPE samplerBayesian sampling — learns from previous trials
PruningEarly stopping for bad trials (MedianPruner)
Study dashboardoptuna-dashboard for real-time monitoring
Multi-objectiveOptimise accuracy AND speed simultaneously
vs GridSearch: GridSearch tests every combination (exponential). Optuna uses Bayesian optimization — it learns which regions are promising and explores them more.
Pattern bridge: Hyperparameter search is the outer loop around gradient descent: optimising the settings rather than the weights. Tune too hard on one validation set and you fit its noise — the trap described in signal in the noise.
Worked example

Pure random search lands at least one trial in the best 5% of a search space with probability 64% after 20 trials, 95% after 60 and near certainty after 200 — whatever the number of dimensions, if only a few really matter (Bergstra & Bengio 2012). Smarter samplers such as TPE beat this baseline; it is the bar they have to clear.

Where it misleads
  • The best of many trials is optimistically biased; evaluate it on data the search never saw.
  • Pruning stops slow starters that might finish best; it is a heuristic, not a guarantee.
  • A wide, poorly scaled space (learning rate on a linear rather than log scale) wastes most trials.
In code
p_top5 = {n: round(1 - 0.95 ** n, 3) for n in (20, 60, 200)}   # random search: at least one trial in the top 5%
Python, in your browser — edit the code and run it again

Assumes import numpy as np and import pandas as pd (and SciPy where imported). Each snippet simulates or makes up its own data, as the comments say.

The same idea with a library
# Optuna — hyperparameter optimisation
import optuna
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score

def objective(trial):
    params = {
        'n_estimators': trial.suggest_int('n_estimators', 50, 500),
        'max_depth': trial.suggest_int('max_depth', 3, 20),
        'min_samples_split': trial.suggest_int('min_samples_split', 2, 20),
        'max_features': trial.suggest_categorical(
            'max_features', ['sqrt', 'log2', None]
        ),
    }
    model = RandomForestClassifier(**params)
    return cross_val_score(model, X, y, cv=5, scoring='f1').mean()

study = optuna.create_study(direction='maximize')
study.optimize(objective, n_trials=100)

print(study.best_params)
optuna.visualization.plot_optimization_history(study)
Sources
  • T. Akiba, S. Sano, T. Yanase, T. Ohta & M. Koyama, “Optuna: A Next-generation Hyperparameter Optimization Framework”, KDD, 2019
  • J. Bergstra & Y. Bengio, “Random Search for Hyper-Parameter Optimization”, Journal of Machine Learning Research 13, 2012
  • J. Bergstra, R. Bardenet, Y. Bengio & B. Kégl, “Algorithms for Hyper-Parameter Optimization”, NeurIPS, 2011

Last reviewed October 2026 · How this site checks its content · Report a mistake

Linked from 1
← Previous
SHAP Library
Open in the full reader, with the topic sidebar