Skip to content

Commit

Permalink
Merge pull request #13 from c-bata/optuna-pr-4793
Browse files Browse the repository at this point in the history
Add a constraint optimization study
  • Loading branch information
not522 authored Jul 25, 2024
2 parents 8e48562 + d931cff commit 6b98f40
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions studies.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

import os
import time
from typing import List
Expand Down Expand Up @@ -64,6 +66,29 @@ def objective_single_none_categorical(trial: optuna.Trial) -> float:
study.optimize(objective_single_none_categorical, n_trials=10)
studies.append((study.study_name, study))

# Single-objective study with constraints
# https://optuna.readthedocs.io/en/stable/faq.html#how-can-i-optimize-a-model-with-some-constraints
def objective_constraints(trial: optuna.Trial) -> float:
x = trial.suggest_float("x", -15, 30)
y = trial.suggest_float("y", -15, 30)
v0 = 4 * x**2 + 4 * y**2

c0 = (x - 5) ** 2 + y**2 - 25
c1 = -((x - 8) ** 2) - (y + 3) ** 2 + 7.7
trial.set_user_attr("constraint", (c0, c1))
return v0

def constraints(trial: optuna.Trial) -> list[float]:
return trial.user_attrs["constraint"]

study = optuna.create_study(
study_name="A single objective constraint optimization study",
storage=storage,
sampler=optuna.samplers.TPESampler(constraints_func=constraints),
)
study.optimize(objective_constraints, n_trials=100)
studies.append((study.study_name, study))

# No trials single-objective study
optuna.create_study(study_name="A single objective study that has no trials", storage=storage)
return studies
Expand Down

0 comments on commit 6b98f40

Please sign in to comment.