optuna
101 строка · 3.3 Кб
1from __future__ import annotations
2
3from typing import cast
4
5import optuna
6from optuna.samplers import BaseSampler
7from optuna.samplers import CmaEsSampler
8from optuna.samplers import NSGAIISampler
9from optuna.samplers import RandomSampler
10from optuna.samplers import TPESampler
11from optuna.testing.storages import StorageSupplier
12
13
14def parse_args(args: str) -> list[int | str]:
15ret: list[int | str] = []
16for arg in map(lambda s: s.strip(), args.split(",")):
17try:
18ret.append(int(arg))
19except ValueError:
20ret.append(arg)
21return ret
22
23
24SAMPLER_MODES = [
25"random",
26"tpe",
27"cmaes",
28]
29
30
31def create_sampler(sampler_mode: str) -> BaseSampler:
32if sampler_mode == "random":
33return RandomSampler()
34elif sampler_mode == "tpe":
35return TPESampler()
36elif sampler_mode == "cmaes":
37return CmaEsSampler()
38elif sampler_mode == "nsgaii":
39return NSGAIISampler()
40else:
41assert False
42
43
44class OptimizeSuite:
45def objective(self, trial: optuna.Trial) -> float:
46x = trial.suggest_float("x", -100, 100)
47y = trial.suggest_int("y", -100, 100)
48return x**2 + y**2
49
50def multi_objective(self, trial: optuna.Trial) -> tuple[float, float]:
51x = trial.suggest_float("x", -100, 100)
52y = trial.suggest_int("y", -100, 100)
53return (x**2 + y**2, (x - 2) ** 2 + (y - 2) ** 2)
54
55def optimize(
56self, storage_mode: str, sampler_mode: str, n_trials: int, objective_type: str
57) -> None:
58with StorageSupplier(storage_mode) as storage:
59sampler = create_sampler(sampler_mode)
60if objective_type == "single":
61directions = ["minimize"]
62elif objective_type == "multi":
63directions = ["minimize", "minimize"]
64else:
65assert False
66study = optuna.create_study(storage=storage, sampler=sampler, directions=directions)
67if objective_type == "single":
68study.optimize(self.objective, n_trials=n_trials)
69elif objective_type == "multi":
70study.optimize(self.multi_objective, n_trials=n_trials)
71else:
72assert False
73
74def time_optimize(self, args: str) -> None:
75storage_mode, sampler_mode, n_trials, objective_type = parse_args(args)
76storage_mode = cast(str, storage_mode)
77sampler_mode = cast(str, sampler_mode)
78n_trials = cast(int, n_trials)
79objective_type = cast(str, objective_type)
80self.optimize(storage_mode, sampler_mode, n_trials, objective_type)
81
82params = (
83"inmemory, random, 1000, single",
84"inmemory, random, 10000, single",
85"inmemory, tpe, 1000, single",
86"inmemory, cmaes, 1000, single",
87"sqlite, random, 1000, single",
88"sqlite, tpe, 1000, single",
89"sqlite, cmaes, 1000, single",
90"journal, random, 1000, single",
91"journal, tpe, 1000, single",
92"journal, cmaes, 1000, single",
93"inmemory, tpe, 1000, multi",
94"inmemory, nsgaii, 1000, multi",
95"sqlite, tpe, 1000, multi",
96"sqlite, nsgaii, 1000, multi",
97"journal, tpe, 1000, multi",
98"journal, nsgaii, 1000, multi",
99)
100param_names = ["storage, sampler, n_trials, objective_type"]
101timeout = 600
102