Repository navigation
Remove prior_mu from compute_sigmas - #6574
Conversation
|
Just to note from my past experiments: If this PR retains moderate performance on such scenario, the change itself would be more consistent (and preferable). |
|
This pull request has not seen any recent activity. |
|
I tried the current latest and v4.8.0 to benchmark the performance impact. Results
Significant differences were observed at at I used the following script: Experiment Scriptfrom __future__ import annotations
import optuna
from optuna.samplers._tpe.parzen_estimator import _ParzenEstimator
import optunahub
HPOLib = optunahub.load_module("benchmarks/hpolib").Problem
HPOBench = optunahub.load_module("benchmarks/hpobench_nn").Problem
class CustomParzenEstimator(_ParzenEstimator):
# This class invalidates the weak bandwidth heuristic.
def __init__(self, observations, search_space, parameters, predetermined_weights=None):
parameters = parameters._replace(multivariate=False)
super().__init__(observations, search_space, parameters, predetermined_weights)
def experiment(trial: optuna.Trial) -> float:
seed = trial.suggest_int("seed", 0, 9)
multivariate = trial.suggest_categorical("multivariate", [True, False])
bench_name = trial.suggest_categorical("bench_name", ["hpolib", "hpobench"])
if bench_name == "hpolib":
dataset_id = trial.suggest_int("dataset_id", 0, 3)
problem = HPOLib(dataset_id=dataset_id, seed=seed)
elif bench_name == "hpobench":
dataset_id = trial.suggest_int("dataset_id", 0, 7)
problem = HPOBench(dataset_id=dataset_id, seed=seed)
else:
assert False, f"Unknown {bench_name=}"
sampler = optuna.samplers.TPESampler(multivariate=multivariate, seed=seed)
sampler._parzen_estimator_cls = CustomParzenEstimator
study = optuna.create_study(sampler=sampler)
study.optimize(problem, n_trials=200)
trial.set_user_attr("results", [float(t.value) for t in study.trials])
return 0.0
if __name__ == "__main__":
optuna_version = optuna.__version__
sampler = optuna.samplers.BruteForceSampler()
storage = optuna.storages.JournalStorage(optuna.storages.journal.JournalFileBackend("result.log"))
study = optuna.create_study(
sampler=sampler, storage=storage, study_name=f"bench-{optuna_version}", load_if_exists=True
)
study.optimize(experiment)Visualization Scriptimport os
import matplotlib.pyplot as plt
import numpy as np
import optuna
import pandas as pd
plt.rcParams["font.family"] = "Times New Roman"
plt.rcParams["font.size"] = 18
def extract() -> pd.DataFrame:
file_path = "./extract.json"
if os.path.exists(file_path):
return pd.read_json(file_path)
storage = optuna.storages.JournalStorage(optuna.storages.journal.JournalFileBackend("result.log"))
results = []
for v in ["4.8.0", "4.9.0.dev"]:
for t in optuna.load_study(storage=storage, study_name=f"bench-{v}").trials:
row = t.params.copy()
bench_name = row.pop("bench_name")
dataset_id = row.pop("dataset_id")
row.update(version=v, dataset_name=f"{bench_name}{dataset_id}", values=t.user_attrs["results"])
results.append(row)
res = pd.DataFrame(results)
res.to_json(file_path)
return res
def plot_results(
ax: plt.Axes,
df: pd.DataFrame,
multivariate: bool,
version: str,
dataset_name: str,
) -> None:
target = (
(df["version"] == version)
& (df["dataset_name"] == dataset_name)
& (df["multivariate"] if multivariate else ~df["multivariate"])
)
# Remove initial samples.
n_init = 10
values = np.minimum.accumulate(df[target]["values"].to_list(), axis=-1)[:, n_init:]
m = np.mean(values, axis=0)
s = np.std(values, axis=0) / np.sqrt(len(values))
steps = np.arange(len(m)) + n_init + 1
color = "darkred" if version == "4.9.0.dev" else "black"
ls = "dashed" if multivariate else "dotted"
marker = "*" if multivariate else "s"
label = f"{multivariate=} ({version[:5]})"
ax.plot(steps, m, color=color, ls=ls, marker=marker, markevery=20, ms=10, label=label)
ax.fill_between(steps, m - s, m + s, alpha=0.2, color=color)
ax.set_xlim(steps[0], steps[-1])
def plot(dataset_name: str) -> None:
df = extract()
_, ax = plt.subplots()
for version in ["4.8.0", "4.9.0.dev"]:
for multivariate in [True, False]:
plot_results(ax, df, multivariate, version, dataset_name)
ax.set_title(dataset_name[:4].upper() + dataset_name[4:-1].lower() + f" (dataset ID: {dataset_name[-1]})")
ax.set_xlabel("# of Trials")
ax.set_ylabel("Objective")
ax.grid(which="minor", color="gray", linestyle=":")
ax.grid(which="major", color="black")
ax.legend()
if dataset_name.startswith("hpolib"):
ax.set_yscale("log")
os.makedirs("figs/", exist_ok=True)
plt.savefig(f"figs/{dataset_name}.png",)
if __name__ == "__main__":
for i in range(4):
plot(f"hpolib{i}")
for i in range(8):
plot(f"hpobench{i}")Statistical Testimport os
import numpy as np
import pandas as pd
from scipy.stats import wilcoxon
def extract() -> pd.DataFrame:
file_path = "./extract.json"
if os.path.exists(file_path):
return pd.read_json(file_path)
raise FileNotFoundError(f"{file_path} not found. Run visualize.py first.")
def get_cummin(df: pd.DataFrame, version: str, dataset_name: str, multivariate: bool) -> np.ndarray:
mask = (
(df["version"] == version)
& (df["dataset_name"] == dataset_name)
& (df["multivariate"] if multivariate else ~df["multivariate"])
)
return np.minimum.accumulate(df[mask]["values"].to_list(), axis=-1)
def wilcoxon_test_per_step(
df: pd.DataFrame,
dataset_name: str,
multivariate: bool,
) -> list[dict]:
v48 = get_cummin(df, "4.8.0", dataset_name, multivariate)
v49 = get_cummin(df, "4.9.0.dev", dataset_name, multivariate)
rows = []
for t in [24, 49, 99, 149, 199]:
_, p_value = wilcoxon(v48[:, t], v49[:, t])
rows.append(dict(dataset_name=dataset_name, n_trials=t + 1, multivariate=multivariate, p_value=p_value))
return rows
if __name__ == "__main__":
df = extract()
dataset_names = sorted(df["dataset_name"].unique())
rows = []
for dataset_name in dataset_names:
for multivariate in [True, False]:
rows.extend(wilcoxon_test_per_step(df, dataset_name, multivariate))
results = pd.DataFrame(rows)
results["significant"] = results["p_value"] < 0.05
print(results.sort_values(by="p_value").head(15))Post EditI also tried some BBOB functions, but I observed almost no significance. BBOB ExperimentBBOB = optunahub.load_module("benchmarks/bbob").Problem
INSTANCE_IDS = [1, 2, 3, 4, 5, 71, 72, 73, 74, 75]
def experiment_bbob(trial: optuna.Trial) -> float:
seed = trial.suggest_int("seed", 0, 9)
multivariate = trial.suggest_categorical("multivariate", [True, False])
function_id = trial.suggest_categorical("function_id", [2, 8, 11, 15, 20])
dim = trial.suggest_categorical("dim", [5, 10])
problem = BBOB(function_id=function_id, dimension=dim, instance_id=INSTANCE_IDS[seed])
sampler = optuna.samplers.TPESampler(multivariate=multivariate, seed=seed)
sampler._parzen_estimator_cls = CustomParzenEstimator
study = optuna.create_study(sampler=sampler)
study.optimize(problem, n_trials=200)
trial.set_user_attr("results", [float(t.value) for t in study.trials])
return 0.0 |
|
@nabenabe0928 Thank you for reporting this! I will discuss with the core devs whether we should revert this PR to fix the performance regression. |
|
@c-bata |
|
Thank you for sharing your valuable benchmark results. Based on the following points, we do not intend to revert:
Thank you for your understanding. |


This PR is the same as #6261. The previous PR was closed due to performance concerns. But, after our subsequent discussion, we concluded that the performance changes were small enough to be acceptable.
The followings are copied from #6261.
Motivation
The calculation of sigmas in
ParzenEstimatoris influenced by the prior's mu, but this is inappropriate for the window computation. This behavior stems from referencing the implementation of hyperopt (hyperopt/hyperopt@5d8b88e).Description of the changes
This PR removes
prior_mufromcompute_sigmas.Benchmark results vary depending on the objective function, and when the optimal values are in the middle of the suggestion ranges, performance slightly deteriorated.
Σx^2 / Σ(x-5)^2
The internal state of the
ParzenEstimatorwas verified using the following code:master / PR