How to Use Optuna for Automated Hyperparameter Optimization

How to Use Optuna for Automated Hyperparameter Optimization

Building a machine learning model involves more than selecting an algorithm and training it on a dataset. The performance of a model often depends on how well its hyperparameters are configured.

For example, when training a Random Forest classifier, you need to decide how many decision trees to create, how deep each tree should grow, and how many features should be considered when splitting a node.

Similarly, training a Support Vector Machine (SVM) requires choosing parameters such as the regularisation strength and kernel coefficient.

These settings can significantly influence model performance. However, finding the right combination manually can be time-consuming, particularly when working with complex algorithms and large datasets.

This is where automated hyperparameter optimization becomes useful.

Instead of manually testing different configurations, you can use optimization frameworks to explore promising combinations and identify settings that improve model performance.

One popular Python framework for this task is Optuna.

Optuna automates hyperparameter search using optimization algorithms, supports efficient trial management, and integrates with popular machine learning libraries such as Scikit-learn, XGBoost, LightGBM, and PyTorch.

In this tutorial, you will learn how to use Optuna for automated hyperparameter optimization, build a practical machine learning example with Python, evaluate the results, and understand techniques for improving the optimization process.

1. What Is Hyperparameter Optimization?

Hyperparameters are configuration settings that control how a machine learning algorithm learns from data.

Unlike model parameters, which are learned during training, hyperparameters are usually specified before or during the training process.

Consider a Random Forest model.

Some of its important hyperparameters include:

  • n_estimators: The number of decision trees in the forest.
  • max_depth: The maximum depth of each decision tree.
  • min_samples_split: The minimum number of samples required to split an internal node.
  • min_samples_leaf: The minimum number of samples required at a leaf node.
  • max_features: The number or proportion of features considered when looking for the best split.

Different combinations of these settings can produce different model performances.

For example:

ConfigurationNumber of treesMaximum depthAccuracy
Model A50582%
Model B1001087%
Model C2001589%
Model D3002088%

These figures are illustrative rather than results from an actual experiment.

The objective of hyperparameter optimization is to identify a configuration that performs well according to a selected evaluation metric.

Common optimization objectives include:

  • Maximizing accuracy.
  • Maximizing precision, recall, or F1-score.
  • Minimizing mean squared error.
  • Minimizing log loss.
  • Minimizing model training time, where computational efficiency is important.

The appropriate metric depends on the problem being solved.

For instance, accuracy may be misleading when working with highly imbalanced classification datasets. In such situations, metrics such as F1-score, precision-recall AUC, or balanced accuracy may be more informative.

2. What Is Optuna?

Optuna is an open-source Python framework designed to automate hyperparameter optimization.

It helps machine learning practitioners search for effective hyperparameter combinations without manually testing every possible configuration.

Rather than relying exclusively on exhaustive grid searches, Optuna can use more efficient optimization strategies to determine which configurations should be evaluated next.

Its main components include:

Study: An optimization task that manages the search process.

Trial: One individual evaluation of a hyperparameter configuration.

Objective function: A Python function that defines what should be optimized.

Sampler: The algorithm responsible for suggesting hyperparameter values.

Pruner: A mechanism that stops unpromising trials before they consume unnecessary computational resources.

For example, suppose you want to optimize a Random Forest model.

Optuna can suggest:

  • 100 decision trees.
  • A maximum depth of 12.
  • A minimum of 3 samples per split.
  • A minimum of 2 samples per leaf.

The application trains and evaluates the model, records its performance, and uses the result to guide subsequent trials.

After completing the optimization process, you can retrieve the best-performing configuration.

Why use Optuna?

Optuna offers several advantages:

  1. Automated search: It reduces the need to manually experiment with hyperparameter combinations.
  2. Efficient optimization: Its samplers can explore promising configurations rather than evaluating every possible combination.
  3. Pruning: It can stop unpromising trials early.
  4. Integration: It works with popular machine learning and deep learning frameworks.
  5. Visualization: It provides tools for understanding optimization results.
  6. Reproducibility: Studies can be configured with reproducible sampling strategies and persistent storage.

3. Optuna vs Traditional Hyperparameter Optimization Methods

Before using Optuna, it is useful to understand how it compares with other optimization techniques.

MethodHow it worksMain limitation
Manual searchUsers select configurations themselvesTime-consuming and difficult to scale
Grid SearchTests every specified combinationCan become computationally expensive
Random SearchRandomly samples configurationsMay spend evaluations on less promising areas
Bayesian optimizationUses previous evaluations to guide future searchesRequires a suitable probabilistic optimization strategy
OptunaProvides an optimization framework with configurable samplers and pruningResults depend on the search space, sampler, objective, and computational budget

An important distinction is that Optuna is not a single optimization algorithm. It is a framework that supports different optimization strategies.

Its default sampler, TPESampler, uses a Tree-structured Parzen Estimator approach to guide the search.

This allows the optimization process to learn from previous trials and suggest potentially better configurations.

4. Installing Optuna and Setting Up Python

To follow this tutorial, you need Python installed on your computer.

You should also have basic knowledge of Python, machine learning, and Scikit-learn.

Start by creating a project folder:

mkdir optuna-hyperparameter-optimization
cd optuna-hyperparameter-optimization

Create a virtual environment:

python -m venv venv

Activate it on Windows:

venv\Scripts\activate

On macOS or Linux:

source venv/bin/activate

Install Optuna and the other required libraries:

pip install optuna scikit-learn pandas numpy matplotlib

You can verify that Optuna is installed by running:

import optuna

print(optuna.__version__)

If the installation is successful, Python will display the installed Optuna version.

5. Prepare a Dataset for Hyperparameter Optimization

For this practical example, we will use the Breast Cancer Wisconsin dataset available through Scikit-learn.

It is a classification dataset containing measurements used to distinguish between malignant and benign breast cancer cases.

We will build a Random Forest classifier and use Optuna to optimize its hyperparameters.

First, import the required libraries:

import optuna
import pandas as pd
import numpy as np

from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score

Load the dataset:

data = load_breast_cancer()

X = pd.DataFrame(
    data.data,
    columns=data.feature_names
)

y = pd.Series(data.target)

Separate the data into training and testing sets:

X_train, X_test, y_train, y_test = train_test_split(
    X,
    y,
    test_size=0.2,
    random_state=42,
    stratify=y
)

The training dataset will be used during hyperparameter optimization, while the test dataset will be reserved for final evaluation.

The stratify=y argument helps preserve the class distribution across the training and testing sets.

Important: The test set should not be used to choose hyperparameters. Repeatedly evaluating configurations on the test set would introduce information leakage into the model selection process.

For a more robust experiment, we will use cross-validation within the training dataset.

6. Create Your First Optuna Objective Function

The objective function is the central part of an Optuna optimization task.

It defines:

  • Which hyperparameters should be optimized.
  • Their possible values or ranges.
  • How the model should be trained.
  • Which evaluation metric should be returned.

Create the following objective function:

from sklearn.model_selection import cross_val_score

def objective(trial):

    n_estimators = trial.suggest_int(
        "n_estimators",
        50,
        300
    )

    max_depth = trial.suggest_int(
        "max_depth",
        3,
        30
    )

    min_samples_split = trial.suggest_int(
        "min_samples_split",
        2,
        20
    )

    min_samples_leaf = trial.suggest_int(
        "min_samples_leaf",
        1,
        10
    )

    max_features = trial.suggest_categorical(
        "max_features",
        ["sqrt", "log2"]
    )

    model = RandomForestClassifier(
        n_estimators=n_estimators,
        max_depth=max_depth,
        min_samples_split=min_samples_split,
        min_samples_leaf=min_samples_leaf,
        max_features=max_features,
        random_state=42,
        n_jobs=-1
    )

    scores = cross_val_score(
        model,
        X_train,
        y_train,
        cv=5,
        scoring="accuracy",
        n_jobs=-1
    )

    return scores.mean()

Let’s understand what is happening.

Defining the search space

The function uses Optuna’s trial methods to define the values that can be tested.

trial.suggest_int()

This method selects integer values within a specified range.

n_estimators = trial.suggest_int(
    "n_estimators",
    50,
    300
)

Optuna can suggest any integer between 50 and 300.

trial.suggest_float()

This method selects floating-point values.

For example:

learning_rate = trial.suggest_float(
    "learning_rate",
    0.001,
    0.1,
    log=True
)

Setting log=True makes the search logarithmic, which is useful when values span several orders of magnitude.

trial.suggest_categorical()

This method selects from a predefined list of options.

max_features = trial.suggest_categorical(
    "max_features",
    ["sqrt", "log2"]
)

In this example, Optuna chooses between two supported feature-selection strategies.

Training and evaluating the model

After selecting the hyperparameters, the objective function creates a Random Forest classifier.

The model is evaluated using five-fold cross-validation.

Cross-validation divides the training dataset into five sections. The model is trained on four sections and evaluated on the remaining section, repeating the process until every section has served as the validation set.

The function returns the average validation accuracy.

Optuna uses this value to determine how promising the selected configuration is.

7. Create an Optuna Study

Now that the objective function is ready, we can create an optimization study.

study = optuna.create_study(
    direction="maximize"
)

study.optimize(
    objective,
    n_trials=50
)

The direction parameter tells Optuna whether the objective should be maximized or minimized.

For this classification problem, we want to maximize accuracy.

Other examples include:

# Maximize F1-score
study = optuna.create_study(
    direction="maximize"
)

# Minimize mean squared error
study = optuna.create_study(
    direction="minimize"
)

The n_trials=50 argument instructs Optuna to evaluate 50 different hyperparameter configurations.

You can increase the number of trials, but more trials generally require additional computational resources.

What happens during optimization?

For each trial, Optuna:

  1. Suggests a hyperparameter configuration.
  2. Passes the configuration to the objective function.
  3. Trains and evaluates the model.
  4. Receives the validation score.
  5. Records the result.
  6. Uses previous trial information to guide subsequent suggestions.

Once the optimization process finishes, you can inspect the results.

8. Retrieve the Best Hyperparameters

After completing the optimization process, retrieve the best-performing configuration.

print("Best trial:")
print(study.best_trial)

print("Best accuracy:")
print(study.best_value)

print("Best hyperparameters:")
print(study.best_params)

The output will show the highest cross-validation accuracy and the associated hyperparameter values.

The actual results depend on the Optuna version, sampling process, computational environment, and trial budget.

You can also convert all trial results into a Pandas DataFrame:

results = study.trials_dataframe()

print(results.head())

This creates a structured table containing information about the optimization trials.

You can save the results for further analysis:

results.to_csv(
    "optuna_optimization_results.csv",
    index=False
)

This is useful when comparing different optimization experiments or documenting model development.

9. Evaluate the Optimized Model

Finding the best hyperparameters during cross-validation does not automatically mean that the model will perform equally well on unseen data.

The next step is to train a new model using the best configuration and evaluate it against the reserved test dataset.

best_model = RandomForestClassifier(
    **study.best_params,
    random_state=42,
    n_jobs=-1
)

best_model.fit(
    X_train,
    y_train
)

predictions = best_model.predict(X_test)

test_accuracy = accuracy_score(
    y_test,
    predictions
)

print("Test Accuracy:", test_accuracy)

The study.best_params dictionary contains the best configuration discovered by Optuna.

The model is trained using the entire training dataset and evaluated on the test dataset.

For a more detailed evaluation, use additional classification metrics:

from sklearn.metrics import (
    classification_report,
    confusion_matrix
)

print(
    classification_report(
        y_test,
        predictions,
        target_names=data.target_names
    )
)

print(
    confusion_matrix(
        y_test,
        predictions
    )
)

The classification report provides precision, recall, and F1-score for each class.

This is particularly useful when accuracy alone does not adequately describe model performance.

10. Visualize Optuna Optimization Results

One advantage of Optuna is its visualization functionality.

Visualizations help you understand how the optimization process behaves and which hyperparameters have the greatest influence on the objective value.

Install Plotly if it is not already available:

pip install plotly

Import Optuna’s visualization module:

import optuna.visualization as vis

A. Optimization history

fig = vis.plot_optimization_history(study)

fig.show()

The optimization history chart displays the objective value across trials.

It helps you understand whether the search is discovering increasingly promising configurations.

B. Hyperparameter importance

fig = vis.plot_param_importances(study)

fig.show()

This chart estimates the importance of the different hyperparameters in explaining variation in the objective values.

It can help identify which settings are most influential within the explored search space.

C. Parallel coordinate plot

fig = vis.plot_parallel_coordinate(study)

fig.show()

A parallel coordinate plot displays relationships between hyperparameter configurations and their corresponding objective values.

It can help identify combinations associated with stronger model performance.

D. Slice plot

fig = vis.plot_slice(study)

fig.show()

The slice plot shows how individual hyperparameter values relate to the objective results across trials.

These visualizations are useful when you want to understand more than just the best configuration.

Note: Some visualizations require sufficient completed trials and valid parameter distributions. Hyperparameter importance estimates can also be unreliable when there are too few trials or when parameters are strongly related.

11. Use Optuna Pruning to Save Computational Resources

When training machine learning models, some configurations perform poorly even during the early stages of training.

Continuing to train these models may waste computational resources.

Optuna provides pruning mechanisms that can terminate unpromising trials before they complete.

For example, consider a neural network trained over 100 epochs.

If a particular hyperparameter configuration consistently produces poor validation performance after the first 20 epochs, it may not be worth continuing the training process.

Optuna can use intermediate evaluation results to decide whether a trial should be stopped.

Example of pruning with an iterative model

The following example uses Scikit-learn’s SGDClassifier and Optuna’s pruning callback mechanism.

import optuna

from optuna.integration import (
    SklearnPruningCallback
)

from sklearn.linear_model import SGDClassifier
from sklearn.model_selection import (
    cross_val_score
)

def objective_with_pruning(trial):

    alpha = trial.suggest_float(
        "alpha",
        1e-5,
        1e-1,
        log=True
    )

    model = SGDClassifier(
        alpha=alpha,
        max_iter=1000,
        tol=1e-3,
        random_state=42
    )

    scores = cross_val_score(
        model,
        X_train,
        y_train,
        cv=5,
        scoring="accuracy"
    )

    return scores.mean()

This example demonstrates another model and a different search space, but it does not actually perform pruning.

For pruning to work, the objective function must report intermediate results and check whether the trial should be stopped.

Here is a simplified example using an iterative training process:

def objective_with_pruning(trial):

    alpha = trial.suggest_float(
        "alpha",
        1e-5,
        1e-1,
        log=True
    )

    model = SGDClassifier(
        alpha=alpha,
        random_state=42
    )

    classes = np.unique(y_train)

    for step in range(1, 11):

        model.partial_fit(
            X_train,
            y_train,
            classes=classes
        )

        score = model.score(
            X_train,
            y_train
        )

        trial.report(score, step)

        if trial.should_prune():
            raise optuna.TrialPruned()

    return model.score(X_train, y_train)

This illustrates the mechanics of reporting intermediate values and checking for pruning. However, it uses training accuracy as its reported metric, which is not a suitable measure for selecting a generalising model.

For a proper experiment, report validation performance at each step using a separate validation dataset. Also ensure that the model’s iterative training behaviour is appropriate for the chosen dataset.

Create a study with a pruner:

pruner = optuna.pruners.MedianPruner(
    n_startup_trials=5,
    n_warmup_steps=2
)

study = optuna.create_study(
    direction="maximize",
    pruner=pruner
)

study.optimize(
    objective_with_pruning,
    n_trials=30
)

The median pruner compares intermediate trial performance with previous trials and can stop configurations that appear unpromising.

Pruning is most useful when the objective function produces meaningful intermediate evaluation results. It does not automatically accelerate every machine learning algorithm.

12. Save and Resume Optuna Studies

Long optimization experiments may take considerable time to complete.

You may also want to continue an optimization process after restarting your computer or Python environment.

Optuna supports persistent storage through databases.

For example, you can use SQLite:

study = optuna.create_study(
    study_name="random_forest_optimization",
    direction="maximize",
    storage="sqlite:///optuna_study.db",
    load_if_exists=True
)

Run the optimization:

study.optimize(
    objective,
    n_trials=50
)

If you run the same study again using the same study name and database, Optuna can load the existing study and continue adding trials.

This is particularly useful for experiments that require larger computational budgets.

13. Best Practices for Using Optuna

Although Optuna automates hyperparameter search, the quality of your results still depends on how you design the experiment.

Consider the following recommendations.

1. Define a realistic search space

Avoid testing values that are unlikely to make sense for your model.

For example, searching for a Random Forest with millions of trees is unlikely to be practical for most ordinary datasets.

Start with reasonable ranges and expand them when necessary.

2. Select the right evaluation metric

Choose a metric that reflects the actual problem.

For imbalanced classification, consider F1-score, recall, precision, or average precision instead of relying exclusively on accuracy.

For regression, consider metrics such as mean absolute error, root mean squared error, and R-squared.

3. Use cross-validation

A single train-validation split can produce results that depend heavily on how the data was divided.

Cross-validation provides a more reliable estimate of performance across different data partitions.

4. Avoid test-set leakage

Do not use your test dataset repeatedly to select hyperparameters.

Keep it separate until the optimization process is complete.

5. Set random seeds where appropriate

Reproducibility is important when comparing optimization experiments.

Set random states in your machine learning models and use a seeded Optuna sampler when reproducible suggestions are required.

6. Monitor computational resources

Increasing the number of trials does not always produce meaningful improvements.

Monitor training time, memory consumption, and the improvement in validation performance.

7. Document your experiments

Record the search space, evaluation metric, number of trials, best configuration, and final test performance.

This makes it easier to reproduce and compare experiments.

8. Consider parallel optimization carefully

Optuna supports parallel and distributed optimization.

However, parallel trials may consume more memory and processing resources. The order in which trials finish can also affect subsequent suggestions, so parallel runs may not be identical to sequential runs even when a seed is specified.

14. Common Mistakes to Avoid

Optimizing the wrong metric: A model with high accuracy may still perform poorly on the class that matters most.

Using an excessively broad search space: An unrealistic search space can waste computational resources.

Ignoring data leakage: Preprocessing operations should be fitted only on the relevant training folds. Use Scikit-learn pipelines when scaling, imputing, selecting features, or encoding data.

Running too few trials: A small number of trials may not explore a complex search space sufficiently.

Assuming the best trial is always the best possible model: Optuna identifies the best configuration found within the search space and computational budget, not necessarily the global optimum.

Ignoring model complexity: A configuration that performs slightly better may require significantly more memory or training time.

Evaluating only on training data: Training performance does not establish how well a model will generalise to unseen data.

Conclusion

Hyperparameter optimization is an important part of building effective machine learning models. However, manually testing different configurations can become inefficient as models and search spaces become more complex.

Optuna provides a practical solution by automating the search process, suggesting promising hyperparameter combinations, recording trial results, and supporting techniques such as pruning.

In this tutorial, we explored how to install Optuna, prepare a dataset, define an objective function, create an optimization study, retrieve the best hyperparameters, evaluate the resulting model, and visualize optimization results.

We also discussed persistent storage, pruning, and best practices for designing reliable experiments.

Whether you are developing classification models, regression systems, or deep learning applications, Optuna can help make your model development workflow more systematic and efficient.

The important thing to remember is that automated optimization does not replace sound machine learning practices. Good data preparation, appropriate evaluation metrics, careful validation, and independent testing remain essential.

Frequently Asked Questions

1. What is Optuna used for in machine learning?

Optuna is used to automate hyperparameter optimization. It helps machine learning practitioners identify effective model configurations by testing different hyperparameter combinations using optimization algorithms.

2. Is Optuna better than GridSearchCV?

Optuna can be more efficient than GridSearchCV when searching large or complex hyperparameter spaces because it can use previous trial results to guide subsequent suggestions. However, GridSearchCV remains useful when the search space is small and exhaustive evaluation is desirable.

3. Does Optuna work with Scikit-learn?

Yes. Optuna works with Scikit-learn and other machine learning frameworks. You can define an objective function that trains a Scikit-learn model, evaluates its performance, and returns a metric for optimization.

4. What is a trial in Optuna?

A trial represents one evaluation of a particular hyperparameter configuration. During a trial, Optuna suggests parameter values, executes the objective function, and records the resulting performance.

5. Can Optuna optimize deep learning models?

Yes. Optuna can optimize hyperparameters for deep learning models built with frameworks such as PyTorch and TensorFlow. It can search learning rates, batch sizes, network architectures, dropout rates, and other model settings.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top