Enable GPSampler to support constraint functions#5715
Merged
nabenabe0928 merged 58 commits intooptuna:masterfrom Nov 22, 2024
Merged
Enable GPSampler to support constraint functions#5715nabenabe0928 merged 58 commits intooptuna:masterfrom
GPSampler to support constraint functions#5715nabenabe0928 merged 58 commits intooptuna:masterfrom
Conversation
Contributor
Benchmark Codeimport matplotlib.pyplot as plt
import numpy as np
import optuna
plt.rcParams["font.family"] = "Times New Roman"
plt.rcParams["font.size"] = 24
plt.rcParams["mathtext.fontset"] = "stix" # The setting of math font
plt.rcParams["text.usetex"] = True
N_TRIALS = 100
def objective(trial: optuna.Trial) -> float:
x = trial.suggest_float("x", 0.0, 2 * np.pi)
y = trial.suggest_float("y", 0.0, 2 * np.pi)
return float(np.sin(x) + y)
def constraints(trial: optuna.trial.FrozenTrial) -> tuple[float]:
x = trial.params["x"]
y = trial.params["y"]
c = float(np.sin(x) * np.sin(y) + 0.95)
trial.set_user_attr("c", c)
return (c, )
def experiments(n_seeds: int) -> dict[str, np.ndarray]:
data = {"tpe-mv": [], "tpe-uv": [], "gp": []}
for seed in range(n_seeds):
sampler = optuna.samplers.TPESampler(multivariate=True, seed=seed, constraints_func=constraints)
study = optuna.create_study(sampler=sampler)
study.optimize(objective, n_trials=N_TRIALS)
data["tpe-mv"].append([t.value if t.user_attrs["c"] <= 0 else np.inf for t in study.trials])
sampler = optuna.samplers.TPESampler(seed=seed, constraints_func=constraints)
study = optuna.create_study(sampler=sampler)
study.optimize(objective, n_trials=N_TRIALS)
data["tpe-uv"].append([t.value if t.user_attrs["c"] <= 0 else np.inf for t in study.trials])
sampler = optuna.samplers.GPSampler(seed=seed, constraints_func=constraints)
study = optuna.create_study(sampler=sampler)
study.optimize(objective, n_trials=N_TRIALS)
data["gp"].append([t.value if t.user_attrs["c"] <= 0 else np.inf for t in study.trials])
return {k: np.asarray(v) for k, v in data.items()}
optuna.logging.set_verbosity(optuna.logging.CRITICAL)
data = experiments(n_seeds=3)
dx = np.arange(N_TRIALS) + 1
fig, ax = plt.subplots(figsize=(10, 5))
lines = []
labels = []
LABEL_DICT = {"tpe-mv": "Multivariate TPE", "tpe-uv": "TPE", "gp": "GP"}
COLOR_DICT = {"tpe-mv": "blue", "tpe-uv": "black", "gp": "darkred"}
for sampler_name, _values in data.items():
if len(_values) == 0:
continue
color = COLOR_DICT[sampler_name]
labels.append(LABEL_DICT[sampler_name])
values = np.minimum.accumulate(_values, axis=-1)
q75, meds, q25 = np.percentile(values, [75, 50, 25], axis=0)
line, = ax.plot(dx, meds, color=color)
lines.append(line)
ax.fill_between(dx, q25, q75, color=color, alpha=0.2)
ax.set_xlim(1, N_TRIALS)
ax.set_ylim(-1, 6.5)
ax.set_xlabel("Number of Trials")
ax.set_ylabel("Feasible Objective Value")
ax.grid(which="minor", color="gray", linestyle=":")
ax.grid(which="major", color="black")
fig.legend(
handles=lines,
loc="lower center",
labels=labels,
bbox_to_anchor=(0.5, -0.2),
fontsize=24,
fancybox=False,
ncol=len(lines),
)
plt.savefig("constraints.png", bbox_inches="tight") |
nabenabe0928
suggested changes
Oct 18, 2024
Contributor
nabenabe0928
left a comment
There was a problem hiding this comment.
Thank you for the PR!
I left two comments:)
Contributor
|
Co-authored-by: Shuhei Watanabe <47781922+nabenabe0928@users.noreply.github.com>
Member
HideakiImamura
left a comment
There was a problem hiding this comment.
Thanks for the update. I have several minor comments. PTAL.
HideakiImamura
approved these changes
Nov 21, 2024
Member
HideakiImamura
left a comment
There was a problem hiding this comment.
Thanks for the update. LGTM!
Contributor
|
Hey, I enhanced the separability of the constrained routine. |
nabenabe0928
approved these changes
Nov 22, 2024
This file contains hidden or 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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Motivation
Enable
GPSamplerto support constraint functions.Description of the changes
In this PR, the following main changes were made:
optuna/_gp/acqf.py, andoptuna/samplers/_gp/sampler.py.Note
Minimal changes (only adding comments) were made to
optuna/_gp/optim_mixed.py.