Python para Data Science e Analytics
Python para Data Science e Analytics › Guides › How to Tune Hyperparameters with Optuna: A Step-by-Step Guid

How to Tune Hyperparameters with Optuna: A Step-by-Step Guide with Pruning and Logging

Optuna tuning runs in four steps: write an objective function that returns a metric, declare the search space with suggest_* calls, create a study with a sampler and a pruner, and log everything to storage so the history survives. Pruning stops trials that are clearly behind the best ones, and logging keeps the winning parameters for the final retrain. The walkthrough below covers each piece, what it does, and where it usually breaks.

Topics: optuna, hiperparâmetros, tuning

What does Optuna do that a grid search doesn't?

A grid search tests every combination you list. Optuna describes the space as functions — suggest_float, suggest_int, suggest_categorical — and the sampler picks the next combination from the history of previous trials, using TPE by default. You stop enumerating combinations and start declaring ranges.

The second gain is pruning. With trial.report and trial.should_prune, a trial that is clearly behind the current best is stopped before it finishes every epoch or fold. When a single fit takes minutes, that changes the total cost of a search round.

Grid search still wins in some cases. In small, discrete spaces it is simpler, needs no extra dependency and is fully deterministic, which matters when you have to reproduce a result exactly. Optuna earns its place when the space is large, continuous or expensive to evaluate.

How do you install Optuna and write the first objective function?

The objective receives a trial and returns a single number: the metric you want to optimize. Inside it you declare the hyperparameters and train the model. The study holds the trials and the full history.

Start with a few hyperparameters and one metric. Widening the search space before you understand how the model behaves usually adds noise, not signal.

How do you prune weak trials without throwing away good ones?

Without pruning, every trial runs to the end, including the ones that already showed they were going nowhere. With pruning, the trial reports an intermediate metric and the pruner decides whether it continues.

The trap is warm-up. Pruning too early discards trials that would have improved later. Set n_startup_trials and n_warmup_steps so the pruner only starts judging after it has a baseline to compare against.

How do you log results and compare the best trials?

Storage is what makes a search reusable. Point the study at a SQLite URL and it persists, so the next session resumes instead of repeating trials you already paid for.

At the end what you need is a decision: which parameters go into the final model. The trial history as a DataFrame shows whether the sampler is exploring well or the space is badly defined.

What usually breaks in an Optuna run?

Most failed runs come from a mismatch between what the objective returns and what you actually care about. If the objective returns training accuracy while your decision depends on validation performance, the search optimizes the wrong thing.

The other frequent problems are pruning too aggressively, declaring too many parameters at once, and forgetting to fix a seed when you need comparable runs.

How do you turn a tuning run into a portfolio project?

A notebook with the search, the pruning and the trial history is a solid portfolio piece because it shows the reasoning, not just the score. It also gives you something concrete to explain: why that space, why that pruner, why that metric.

The walkthrough above gets easier when the Python base, Pandas and cross-validation are already solid. The Python for Data Science and Analytics course at PAAnalytics goes from zero to advanced in three modules — Basic, Intermediate and Advanced — plus bonus modules, covering IDE and Jupyter Notebook setup, NumPy and Pandas, user-defined functions, loops and conditionals, data visualization, data cleaning and preparation, and outlier detection. On the machine learning side it covers linear and logistic regression, K-Means, SVM, Naive Bayes, decision trees, Random Forest, Gradient Boosting, XGBoost, LightGBM, feature selection and cross-validation, and closes with an end-to-end project: exploratory analysis and machine learning from start to finish.

Lessons are recorded in high quality and watched at your own pace, with guided exercises and real market projects for your portfolio. Access is unlimited with no expiry date, there is a completion certificate and an exclusive community for networking. Checkout runs through Hotmart with card or boleto, and you don't need to know how to program before starting. The course costs R$ 470, or 12 card payments of R$ 20.37. Details are at python.paanalytics.net.

PrunerBest whenWhat it costs you
MedianPrunerYou want a simple baseline that compares each trial against the median of previous onesNeeds enough completed trials before it has a reference
SuccessiveHalvingPrunerYou can report the metric at several steps and want to cut the weakest trials earlyAggressive settings can stop trials that would have recovered
HyperbandPrunerThe search budget is large and you want several brackets running at different intensitiesMore bookkeeping and a less obvious reading of the trial history

Pruner behavior as documented by Optuna; no benchmark numbers are claimed here.

Start with the Basic module and reach tuning with the foundation in place

Secure payment via Hotmart, up to 12 installments.

Enroll now Product site

Frequently asked questions

Do I need a GPU to run Optuna?

No. Optuna is a scheduling layer around your own training code, so it runs wherever that code runs. A GPU only helps if the model itself trains faster on one; the search loop adds negligible overhead.

How many trials should I run?

There is no universal number. Start small, watch study.best_value, and stop when the best value stops improving over a stretch of trials. Pruning makes longer runs cheaper, so you can usually afford more trials than with grid search.

What is the difference between the sampler and the pruner?

The sampler chooses the next set of hyperparameters. The pruner decides whether a running trial should be stopped early. They are independent settings on the same study, and you can change one without touching the other.

Can I close the notebook and resume the study later?

Yes, if you passed a storage URL and load_if_exists=True. The trials stay in the database and optimize() continues from the existing history instead of starting over.

Does the course teach Optuna?

The course outline covers the groundwork: Python from scratch, Pandas, data preparation, the main machine learning algorithms, feature selection and cross-validation. Optuna is a library you add on top of that base, and the course does not list it among its topics.

Ler em português →