-
Notifications
You must be signed in to change notification settings - Fork 178
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #218 from nabenabe0928/code-fix/refactor-simple-ex…
…amples Modify simple examples based on the Optuna code conventions
- Loading branch information
Showing
2 changed files
with
48 additions
and
30 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,30 +1,34 @@ | ||
""" | ||
Optuna example that optimizes simple quadratic functions. | ||
In this example, we optimize simple quadratic functions. | ||
In this example, we optimize two objective values. | ||
Unlike single-objective optimization, an optimization gives a trade-off between two objectives. | ||
As a result, we get the best trade-offs between two objectives, a.k.a Pareto solutions. | ||
""" | ||
|
||
import optuna | ||
|
||
|
||
# Define simple 2-dimensional objective functions. | ||
# Define two objective functions. | ||
# We would like to minimize f1 and maximize f2. | ||
def objective(trial): | ||
x = trial.suggest_float("x", -100, 100) | ||
y = trial.suggest_categorical("y", [-1, 0, 1]) | ||
obj1 = x**2 + y | ||
obj2 = -((x - 2) ** 2 + y) | ||
return [obj1, obj2] | ||
f1 = x**2 + y | ||
f2 = -((x - 2) ** 2 + y) | ||
return f1, f2 | ||
|
||
|
||
if __name__ == "__main__": | ||
# We minimize obj1 and maximize obj2. | ||
# We minimize the first objective value and maximize the second objective value. | ||
study = optuna.create_study(directions=["minimize", "maximize"]) | ||
study.optimize(objective, n_trials=500, timeout=1) | ||
|
||
pareto_front = [t.values for t in study.best_trials] | ||
pareto_sols = [t.params for t in study.best_trials] | ||
print("Number of finished trials: ", len(study.trials)) | ||
|
||
for i, (params, values) in enumerate(zip(pareto_sols, pareto_front)): | ||
print(f"The {i}-th Pareto solution and its objective values") | ||
print("\t", params, values) | ||
for i, best_trial in enumerate(study.best_trials): | ||
print(f"The {i}-th Pareto solution was found at Trial#{best_trial.number}.") | ||
print(f" Params: {best_trial.params}") | ||
f1, f2 = best_trial.values | ||
print(f" Values: {f1=}, {f2=}") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters