Skip to main content

Optuna: Hyperparameter Tuning with MLflow Tracking

Updated 2 min readMarkdown
Part of seriesMLOPS
Optuna: Hyperparameter Tuning with MLflow Tracking

Cross-validation evaluates a model configuration. Hyperparameter tuning searches for a better configuration.

For a Random Forest, examples of hyperparameters include the number of trees (n_estimators) and maximum tree depth (max_depth).

Define the search space

Optuna lets us define ranges for parameters:

n_estimators = trial.suggest_int(
    "n_estimators", 50, 500
)
max_depth = trial.suggest_int(
    "max_depth", 3, 20
)

Optuna proposes values for each trial. The objective function builds a model, evaluates it, and returns a score.

Evaluate each candidate

A candidate can be evaluated with stratified cross-validation:

cv = StratifiedKFold(
    n_splits=3,
    shuffle=True,
    random_state=42,
)

scores = cross_val_score(
    model,
    X,
    y,
    cv=cv,
    scoring="f1",
)

score = float(np.mean(scores))

The three fold scores are averaged to produce one F1 score for the candidate.

Because a higher F1 score is better, create the study with:

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

Using minimize would tell Optuna to seek the lowest score --- the opposite of the goal.

Track every trial in MLflow

Each trial should have its own independent MLflow run:

with mlflow.start_run(run_name=f"trial-{trial.number}"):
    mlflow.log_params({
        "n_estimators": n_estimators,
        "max_depth": max_depth,
    })
    mlflow.log_metric("f1_score", score)

This allows the trials to be compared in the MLflow UI.

Save the winning configuration

After optimization:

study.best_params
study.best_value

These provide the best parameter combination and its objective score. The configuration can be written to YAML for a later training or release step.

Takeaway: Optuna chooses what to try, cross-validation evaluates each candidate, and MLflow records the search.

No comments yet. Be the first to comment.