
Imagine you're building a machine learning model to predict whether a customer will leave a subscription service. You've prepared the dataset, trained a Random Forest classifier, and achieved reasonable accuracy. But changing the number of trees, maximum depth, or minimum samples per leaf changes the results.
The problem is that these settings aren't learned from the training data. You have to choose them yourself.
This is where Hyperparameter Optimization using Optuna and Scikit-learn becomes useful. Instead of manually trying different combinations, we can define a search space and let Optuna run experiments, evaluate their results, and identify promising configurations.
In this tutorial, we'll use the real Breast Cancer Wisconsin Diagnostic dataset from Scikit-learn to build a classification model. We'll compare a baseline model with an optimized model, inspect the experiments, and save the best configuration for future use.
1. What Are Hyperparameters in Machine Learning?
When training a machine learning model, there are two types of values worth understanding.
Model parameters are learned automatically from the training data.
For example, in a linear regression model, the coefficients are learned during training.
Hyperparameters are configuration values that we choose before or during the training process.
For a Random Forest classifier, some common hyperparameters include:
Hyperparameter | Purpose |
|---|---|
n_estimators | Number of decision trees |
max_depth | Maximum depth of each tree |
min_samples_split | Minimum samples required to split a node |
min_samples_leaf | Minimum samples required in a leaf |
max_features | Number of features considered for each split |
class_weight | Controls how class imbalance affects training |
Consider these two configurations:
RandomForestClassifier(
n_estimators=100,
max_depth=10
)And:
RandomForestClassifier(
n_estimators=500,
max_depth=20
)Both use the same algorithm, but they can produce different results because their configurations are different.
A deeper tree may learn more complex patterns, but it can also overfit. Increasing the number of trees can improve stability, but it also increases training time.
The objective of hyperparameter optimization is to find a configuration that performs well on data the model hasn't seen during training.
2. What Is Optuna?
<Entity value="Optuna" category="software" disambig="Python hyperparameter optimization framework"/> is an open-source hyperparameter optimization framework designed to automate machine learning experiments.
Instead of manually defining every combination, we describe the search space and write an objective function that returns a score.
Optuna then proposes configurations, evaluates them, and uses previous trial results to guide future experiments.
Some useful features include:
Automatic hyperparameter suggestions.
TPE-based optimization.
Random and other sampling strategies.
Pruning of unpromising experiments.
Experiment history and visualization.
Support for Scikit-learn, PyTorch, TensorFlow, and other frameworks.
One of its useful features is the Tree-structured Parzen Estimator (TPE) sampler. It uses information from previous trials to propose potentially better hyperparameter combinations.
This is different from testing every possible combination.
3. Install the Required Libraries
Create a project directory:
mkdir optuna-ml-project
cd optuna-ml-projectCreate a virtual environment:
python -m venv venvActivate it on macOS or Linux:
source venv/bin/activateFor Windows:
venv\Scripts\activateInstall the dependencies:
pip install optuna scikit-learn pandas numpy matplotlib seaborn joblibWe'll use:
Optuna: Hyperparameter optimization.
Scikit-learn: Dataset loading, model training, cross-validation, and evaluation.
Pandas: Exploring the dataset.
NumPy: Numerical operations.
Matplotlib and Seaborn: Visualizing results.
Joblib: Saving the trained model.
Our project structure will be:
optuna-ml-project/
│
├── main.py
├── baseline_model.py
├── optimized_model.pkl
├── best_params.json
└── requirements.txt4. Choose a Real Dataset
For this example, we'll use the Breast Cancer Wisconsin Diagnostic dataset.
It is available directly through Scikit-learn and contains measurements calculated from digitized images of breast mass samples.
The dataset contains:
569 observations.
30 numerical features.
357 benign cases.
212 malignant cases.
Two classification labels.
Some of the features include:
Feature | Description |
|---|---|
radius_mean | Mean distance from center to perimeter |
texture_mean | Standard deviation of grayscale values |
perimeter_mean | Mean perimeter |
area_mean | Mean area |
smoothness_mean | Local variation in radius lengths |
compactness_mean | Compactness measurement |
concavity_mean | Severity of concave portions |
symmetry_mean | Symmetry measurement |
The target represents whether the sample is classified as benign or malignant.
This is a real, publicly available dataset. It is useful for learning binary classification, but a model trained on it is not a medical diagnostic system and should not be used for clinical decisions.
Load the dataset:
import pandas as pd
from sklearn.datasets import load_breast_cancer
dataset = load_breast_cancer()
X = pd.DataFrame(
dataset.data,
columns=dataset.feature_names
)
y = pd.Series(
dataset.target,
name="target"
)
print("Features:", X.shape)
print("Target:", y.shape)
print(y.value_counts())The target encoding in this dataset is:
0 = Malignant
1 = BenignUnderstanding the target encoding is important when interpreting predictions and classification reports.
5. Split the Dataset into Training and Testing Data
Before optimization, we need to separate the training data from the testing data.
We'll reserve 20% of the observations for final evaluation.
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
X,
y,
test_size=0.2,
random_state=42,
stratify=y
)
print("Training samples:", len(X_train))
print("Testing samples:", len(X_test))We use stratify=y to preserve the class distribution across both datasets.
One important rule: the test dataset must not be used during hyperparameter optimization.
If we repeatedly check test performance while changing hyperparameters, information from the test set influences our decisions. This creates evaluation leakage.
We'll use cross-validation on the training data to optimize the model and evaluate the selected configuration on the test set only after optimization is complete.
6. Train a Baseline Random Forest Model
Before using Optuna, we need a baseline.
A baseline gives us a reference point. Without one, we won't know whether optimization actually improves the model.
We'll start with a Random Forest classifier using its default configuration.
from sklearn.ensemble import RandomForestClassifier
baseline_model = RandomForestClassifier(
random_state=42,
n_jobs=-1
)
baseline_model.fit(
X_train,
y_train
)Generate predictions:
from sklearn.metrics import (
accuracy_score,
roc_auc_score
)
baseline_predictions = baseline_model.predict(
X_test
)
baseline_probabilities = baseline_model.predict_proba(
X_test
)[:, 1]
baseline_accuracy = accuracy_score(
y_test,
baseline_predictions
)
baseline_auc = roc_auc_score(
y_test,
baseline_probabilities
)
print("Baseline Accuracy:", baseline_accuracy)
print("Baseline ROC-AUC:", baseline_auc)Accuracy measures the percentage of correctly classified observations.
ROC-AUC measures how well the model distinguishes between the two classes across different classification thresholds.
For this example, we'll optimize ROC-AUC.
Why not use accuracy alone?
Imagine a dataset containing 95% observations from one class. A model that always predicts that majority class could achieve 95% accuracy while being completely useless for identifying the minority class.
ROC-AUC gives us a broader view of classification performance, although it should also be considered alongside class-specific metrics.
7. Define the Hyperparameter Search Space
Now we can start using Optuna.
First, import the library:
import optunaOptuna requires an objective function.
This function receives a trial object, suggests hyperparameter values, trains the model, evaluates it, and returns a numerical score.
Before writing the objective, let's understand how parameter suggestions work.
def example_objective(trial):
n_estimators = trial.suggest_int(
"n_estimators",
100,
500
)
max_depth = trial.suggest_int(
"max_depth",
3,
30
)
min_samples_split = trial.suggest_int(
"min_samples_split",
2,
20
)
print(n_estimators, max_depth, min_samples_split)
return 0.5Optuna provides several methods for defining search spaces.
Integer values:
trial.suggest_int(
"n_estimators",
100,
500
)Floating-point values:
trial.suggest_float(
"learning_rate",
0.001,
0.1,
log=True
)Categorical values:
trial.suggest_categorical(
"criterion",
["gini", "entropy", "log_loss"]
)The log=True option is useful when searching across values that differ by orders of magnitude, such as learning rates.
For our Random Forest model, we'll optimize:
Number of trees.
Maximum tree depth.
Minimum samples for splitting.
Minimum samples in a leaf.
Number of features considered at each split.
Split criterion.
Class weighting.
8. Create the Optuna Objective Function
Now let's create the actual objective function.
We'll use StratifiedKFold with five folds.
This divides the training data into five parts while preserving the class distribution as closely as possible.
Each fold gets a turn as the validation set, while the remaining folds are used for training.
from sklearn.model_selection import (
StratifiedKFold,
cross_val_score
)
def objective(trial):
params = {
"n_estimators": trial.suggest_int(
"n_estimators",
100,
500
),
"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", None]
),
"criterion": trial.suggest_categorical(
"criterion",
["gini", "entropy"]
),
"class_weight": trial.suggest_categorical(
"class_weight",
[None, "balanced"]
),
"random_state": 42,
"n_jobs": -1
}
model = RandomForestClassifier(**params)
cv = StratifiedKFold(
n_splits=5,
shuffle=True,
random_state=42
)
scores = cross_val_score(
model,
X_train,
y_train,
cv=cv,
scoring="roc_auc",
n_jobs=1
)
return scores.mean()Let's understand what happens here.
First, Optuna suggests a set of hyperparameters.
Next, we create a Random Forest classifier using those values.
Then, cross_val_score() trains and evaluates the model across five folds.
Finally, we calculate the average ROC-AUC score and return it to Optuna.
Optuna uses this result to guide future trials.
Notice that the objective function only receives X_train and y_train. Our test dataset remains untouched.
9. Create and Run the Optuna Study
An Optuna study manages the optimization process.
We'll create a study that maximizes ROC-AUC.
study = optuna.create_study(
direction="maximize",
study_name="random-forest-optimization",
sampler=optuna.samplers.TPESampler(seed=42)
)The direction parameter tells Optuna whether we want to maximize or minimize the objective.
For example:
direction="maximize"is appropriate when optimizing accuracy, ROC-AUC, or F1-score.
For loss functions such as mean squared error, we generally use:
direction="minimize"Now run the optimization:
study.optimize(
objective,
n_trials=50
)Each trial represents one experiment with a different hyperparameter configuration.
After 50 trials, print the best result:
print("Best ROC-AUC:", study.best_value)
print("Best Parameters:")
print(study.best_params)The exact result depends on the search process and environment. We should use the actual output from the experiment rather than assume that a particular combination will always be best.
For a larger search space, 50 trials may not be sufficient. The number of trials should depend on the available computing resources and how expensive each training run is.
10. Understand What Happens During Optimization
Let's say Optuna evaluates these configurations:
Trial | Trees | Maximum Depth | Minimum Leaf | ROC-AUC |
|---|---|---|---|---|
1 | 150 | 10 | 2 | Example result |
2 | 300 | 20 | 1 | Example result |
3 | 200 | 15 | 4 | Example result |
4 | 450 | 25 | 2 | Example result |
These values are illustrative, not measured experimental results.
Each trial is stored in the study.
Optuna can use previous trial outcomes to make more informed suggestions.
The TPE sampler estimates which parameter configurations are more likely to produce good results and uses that information to guide its search.
This is why Optuna can be more efficient than blindly testing every possible combination.
However, it doesn't guarantee finding the global optimum. It finds a promising configuration within the search space and trial budget we provide.
11. Train the Final Model Using the Best Parameters
Once optimization is complete, we can retrieve the best configuration.
best_params = study.best_params
print(best_params)Use these parameters to create a new model:
best_model = RandomForestClassifier(
**best_params,
random_state=42,
n_jobs=-1
)Now train it on the complete training dataset:
best_model.fit(
X_train,
y_train
)This step is important.
During cross-validation, each trial trained several temporary models on different training folds.
Now we train one final model using all the available training observations and the selected hyperparameters.
The test data is still reserved for final evaluation.
12. Compare Baseline and Optimized Models
Let's evaluate the optimized model.
optimized_predictions = best_model.predict(
X_test
)
optimized_probabilities = best_model.predict_proba(
X_test
)[:, 1]
optimized_accuracy = accuracy_score(
y_test,
optimized_predictions
)
optimized_auc = roc_auc_score(
y_test,
optimized_probabilities
)
print("Optimized Accuracy:", optimized_accuracy)
print("Optimized ROC-AUC:", optimized_auc)Now compare the results:
comparison = pd.DataFrame({
"Model": [
"Baseline Random Forest",
"Optimized Random Forest"
],
"Accuracy": [
baseline_accuracy,
optimized_accuracy
],
"ROC-AUC": [
baseline_auc,
optimized_auc
]
})
print(comparison)The comparison helps us understand whether the optimization process improved performance on unseen observations.
There is no guarantee that the optimized model will always outperform the baseline on the test set. A difference in cross-validation performance may not translate into an improvement on unseen data.
If the baseline performs better, investigate the search space, trial budget, and variability of the validation scores instead of assuming that more optimization trials automatically produce a better model.
13. Inspect the Best Optuna Trials
One useful feature of Optuna is that we can inspect the history of experiments.
Get all trial results:
trials_df = study.trials_dataframe()
print(
trials_df[
["number", "value", "state"]
].head()
)This gives us information about each optimization attempt.
We can also sort the completed trials:
completed_trials = trials_df[
trials_df["state"] == "COMPLETE"
]
print(
completed_trials.sort_values(
by="value",
ascending=False
).head(10)
)This is useful when you want to understand which configurations produced the strongest validation results.
14. Visualize the Optimization Process
Numbers alone don't always tell us how an optimization process behaves.
Optuna provides a visualization module for exploring trial results.
Install or use the visualization dependency:
pip install plotlyCreate an optimization history plot:
from optuna.visualization import (
plot_optimization_history
)
fig = plot_optimization_history(study)
fig.show()This graph shows the objective value of each trial and the best value found so far.
We can also inspect the importance of hyperparameters:
from optuna.visualization import (
plot_param_importances
)
fig = plot_param_importances(study)
fig.show()Parameter importance estimates which hyperparameters had the strongest influence on the observed optimization results.
These plots help answer practical questions:
Is the optimization improving over time?
Are some hyperparameters more influential than others?
Are later trials still discovering better configurations?
Is the search space unnecessarily large?
The importance plot should be interpreted carefully. It describes relationships within the completed experiment, not universal rules about which parameters matter most.
15. Use Optuna Pruning to Stop Unpromising Trials
Some machine learning models take a long time to train.
If a trial is performing poorly, continuing the experiment may waste computing resources.
Optuna supports pruning, which can stop unpromising trials before they complete.
For example, when training a model over multiple iterations, we can report intermediate performance:
trial.report(
current_score,
step=epoch
)
if trial.should_prune():
raise optuna.TrialPruned()Optuna uses the reported values and the selected pruning strategy to decide whether a trial should stop.
For a Random Forest trained through cross_val_score(), we don't automatically get intermediate reports from individual folds through this example.
To use pruning effectively, the objective function needs to report intermediate results. This is more natural with iterative algorithms such as neural networks, boosting models, and custom training loops.
16. Save the Optimized Model
Once the model has been evaluated, we can save it using Joblib.
import joblib
joblib.dump(
best_model,
"optimized_model.pkl"
)We should also save the selected hyperparameters:
import json
with open(
"best_params.json",
"w"
) as file:
json.dump(
best_params,
file,
indent=4
)Now our project contains:
optuna-ml-project/
│
├── main.py
├── optimized_model.pkl
└── best_params.jsonThe trained model can be loaded later without repeating the optimization process.
17. Make Predictions Using the Saved Model
Let's create a small prediction example.
Load the saved model:
import joblib
model = joblib.load(
"optimized_model.pkl"
)Prepare one observation using the same feature columns and order as the training dataset:
sample = X_test.iloc[[0]]Generate a prediction:
prediction = model.predict(sample)
probabilities = model.predict_proba(sample)
print("Predicted class:", prediction[0])
print("Class probabilities:", probabilities[0])Remember our dataset encoding:
0 = Malignant
1 = BenignWe can convert the prediction into a readable label:
labels = {
0: "Malignant",
1: "Benign"
}
print(
"Prediction:",
labels[prediction[0]]
)This demonstrates how the saved model can be used in another Python application.
In a real deployment, validate the input schema, monitor data quality, and use appropriate clinical oversight for any healthcare-related system. This educational model is not suitable for making medical decisions.
18. Other Machine Learning Problems Where Optuna Is Useful
The same optimization workflow can be applied to many practical machine learning tasks.
Customer Churn Prediction
A subscription business wants to identify customers who are likely to cancel their subscriptions.
Possible models include Random Forest, XGBoost, and Logistic Regression.
Useful hyperparameters include tree depth, learning rate, number of estimators, and regularization strength.
Depending on the business objective, you may optimize F1-score, ROC-AUC, or recall.
House Price Prediction
A real estate platform wants to estimate property prices using historical sales information.
For a regression model, we might optimize:
Number of estimators.
Maximum tree depth.
Minimum samples per leaf.
Learning rate.
Regularization parameters.
Metrics such as MAE, RMSE, and R² can be used to evaluate results.
Fraud Detection
A financial platform wants to identify potentially fraudulent transactions.
Fraud datasets are often highly imbalanced. Optimizing accuracy alone can produce misleading results.
Precision, recall, F1-score, and precision-recall AUC may be more useful, depending on the cost of false positives and false negatives.
Product Demand Forecasting
An e-commerce business wants to predict future product demand.
Different regression models and forecasting algorithms have different hyperparameters. Optuna can help search for configurations that minimize forecasting errors.
The important part is choosing an evaluation metric that reflects the actual business problem.
19. Best Practices for Hyperparameter Optimization
Hyperparameter optimization can improve a model, but poor experiment design can produce misleading results.
Here are some practices worth following.
Keep the test dataset separate.
Use cross-validation on training data for optimization. Evaluate the final selected model on the test dataset only after the search is complete.
Choose meaningful search ranges.
Searching between 1 and 10,000 trees without a reason can waste a lot of time. Start with reasonable ranges based on the algorithm and dataset.
Choose the right evaluation metric.
Accuracy isn't appropriate for every classification problem. Consider precision, recall, F1-score, ROC-AUC, or PR-AUC depending on the use case.
Use reproducible experiments.
Set random seeds where appropriate and record the dataset version, model configuration, and library versions.
Don't over-optimize a small validation set.
Running hundreds or thousands of trials against the same validation process can gradually overfit the model-selection process itself.
Track experiment history.
For larger projects, consider Optuna's persistent storage so studies can be resumed and reviewed.
Understand computational cost.
Every trial requires model training and evaluation. Start with a smaller number of trials, measure execution time, and increase the budget when necessary.
20. When Should You Use Optuna Instead of Grid Search?
Scikit-learn already provides GridSearchCV and RandomizedSearchCV.
So why use Optuna?
Grid Search evaluates every combination in a predefined parameter grid.
For example:
from sklearn.model_selection import GridSearchCV
param_grid = {
"n_estimators": [100, 200, 300],
"max_depth": [5, 10, 20],
"min_samples_split": [2, 5, 10]
}
grid_search = GridSearchCV(
RandomForestClassifier(random_state=42),
param_grid,
cv=5,
scoring="roc_auc",
n_jobs=-1
)
grid_search.fit(
X_train,
y_train
)This configuration requires:
[
3 \times 3 \times 3 = 27
]
parameter combinations.
With five-fold cross-validation, that's 135 model fits.
Grid Search works well when the search space is small and you want exhaustive evaluation of the specified combinations.
Randomized Search samples a fixed number of combinations from the search space.
Optuna provides a more adaptive search process. Its TPE sampler can use earlier results to guide later suggestions, and its pruning functionality can reduce wasted computation for compatible iterative objectives.
Feature | Grid Search | Random Search | Optuna |
|---|---|---|---|
Tests predefined combinations | Yes | No | No |
Random parameter sampling | No | Yes | Supported |
Adaptive optimization | No | No | Yes, with samplers such as TPE |
Pruning | No built-in trial pruning | No built-in trial pruning | Yes |
Visualization | Limited | Limited | Dedicated visualization tools |
Flexible custom objectives | Yes, through estimator scoring | Yes | Yes |
There isn't one method that is best for every project.
For a small search space, Grid Search is perfectly reasonable. For a larger or more complex search, Optuna can be a more flexible choice.
Conclusion
Hyperparameter optimization is an important part of building reliable machine learning models.
A model can use the right algorithm and still perform poorly because its configuration isn't suitable for the dataset. Manually testing every combination becomes time-consuming as the number of parameters increases.
With Optuna and Scikit-learn, we can automate much of this experimentation.
In this tutorial, we loaded a real classification dataset, trained a baseline Random Forest model, defined a hyperparameter search space, ran cross-validation through Optuna, selected the best configuration, and evaluated the final model on unseen data.
We also explored trial history, visualization, pruning, model saving, and practical use cases.
The main lesson is that optimization should be treated as a controlled experiment. A higher cross-validation score doesn't automatically guarantee better performance in production. Good data, meaningful evaluation metrics, proper validation, and careful testing are just as important as the optimization algorithm itself.
Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.


