Skip to content

Commit ba08eb5

Browse files
committed
Support sequential domain reduction with mixed parameters
1 parent ec45123 commit ba08eb5

3 files changed

Lines changed: 59 additions & 30 deletions

File tree

‎bayes_opt/bayesian_optimization.py‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -474,9 +474,13 @@ def _load_state_dict(self, state: dict[str, Any]) -> None:
474474
self._acquisition_function.set_acquisition_params(state["acquisition_params"])
475475

476476
if state.get("transformed_bounds") and self._bounds_transformer:
477+
bounds = np.asarray(state["transformed_bounds"])
478+
# Discrete parameters keep their typed domains; a categorical
479+
# parameter can occupy several rows of the encoded bounds.
477480
new_bounds = {
478-
key: bounds
479-
for key, bounds in zip(self._space.keys, np.array(state["transformed_bounds"]), strict=False)
481+
key: bounds[mask][0]
482+
for key, mask in self._space.masks.items()
483+
if not np.array_equal(bounds[mask], self._space.bounds[mask])
480484
}
481485
self._space.set_bounds(new_bounds)
482486
self._bounds_transformer.initialize(self._space)

‎bayes_opt/domain_reduction.py‎

Lines changed: 21 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -57,8 +57,9 @@ class SequentialDomainReductionTransformer(DomainTransformer):
5757
Zooming parameter used to shrink the region of interest.
5858
5959
minimum_window : float or np.ndarray or dict, default=0.0
60-
Minimum window size for each parameter. If a float is provided,
61-
the same value is used for all parameters.
60+
Minimum window size for each float parameter, in parameter order. If a
61+
scalar is provided, the same value is used for all float parameters.
62+
Integer and categorical parameters retain their original domains.
6263
"""
6364

6465
def __init__(
@@ -69,7 +70,6 @@ def __init__(
6970
eta: float = 0.9,
7071
minimum_window: NDArray[Float] | Sequence[float] | Mapping[str, float] | float = 0.0,
7172
) -> None:
72-
# TODO: Ensure that this is only applied to continuous parameters
7373
self.parameters = parameters
7474
self.gamma_osc = gamma_osc
7575
self.gamma_pan = gamma_pan
@@ -85,33 +85,31 @@ def initialize(self, target_space: TargetSpace) -> None:
8585
target_space : TargetSpace
8686
TargetSpace this DomainTransformer operates on.
8787
"""
88-
if isinstance(self.minimum_window_value, Mapping):
89-
self.minimum_window_value = [self.minimum_window_value[key] for key in target_space.keys]
90-
else:
91-
self.minimum_window_value = self.minimum_window_value
92-
93-
any_not_float = any(not isinstance(p, FloatParameter) for p in target_space._params_config.values())
94-
if any_not_float:
95-
msg = "Domain reduction is only supported for all-FloatParameter optimization."
88+
self._float_keys = [
89+
key for key, param in target_space.params_config.items() if isinstance(param, FloatParameter)
90+
]
91+
if not self._float_keys:
92+
msg = "Domain reduction requires at least one FloatParameter."
9693
raise ValueError(msg)
97-
# Set the original bounds
98-
self.original_bounds = np.copy(target_space.bounds)
94+
self.original_bounds = np.array([target_space.params_config[key].bounds for key in self._float_keys])
9995
self.bounds = [self.original_bounds]
10096

10197
self.minimum_window: NDArray[Float] | Sequence[float]
10298
# Set the minimum window to an array of length bounds
103-
if isinstance(self.minimum_window_value, (Sequence, np.ndarray)):
104-
if len(self.minimum_window_value) != len(target_space.bounds):
105-
error_msg = "Length of minimum_window must be the same as the number of parameters"
99+
if isinstance(self.minimum_window_value, Mapping):
100+
self.minimum_window = [self.minimum_window_value[key] for key in self._float_keys]
101+
elif isinstance(self.minimum_window_value, (Sequence, np.ndarray)):
102+
if len(self.minimum_window_value) != len(self._float_keys):
103+
error_msg = "Length of minimum_window must be the same as the number of float parameters"
106104
raise ValueError(error_msg)
107105
self.minimum_window = self.minimum_window_value
108106
else:
109-
self.minimum_window = [self.minimum_window_value] * len(target_space.bounds)
107+
self.minimum_window = [self.minimum_window_value] * len(self._float_keys)
110108

111109
# Set initial values
112-
self.previous_optimal = np.mean(target_space.bounds, axis=1)
113-
self.current_optimal = np.mean(target_space.bounds, axis=1)
114-
self.r = target_space.bounds[:, 1] - target_space.bounds[:, 0]
110+
self.previous_optimal = np.mean(self.original_bounds, axis=1)
111+
self.current_optimal = np.mean(self.original_bounds, axis=1)
112+
self.r = self.original_bounds[:, 1] - self.original_bounds[:, 0]
115113

116114
self.previous_d = 2.0 * (self.current_optimal - self.previous_optimal) / self.r
117115

@@ -141,7 +139,8 @@ def _update(self, target_space: TargetSpace) -> None:
141139
self.previous_optimal = self.current_optimal
142140
self.previous_d = self.current_d
143141

144-
self.current_optimal = target_space.params_to_array(target_space.max()["params"])
142+
best_params = target_space.max()["params"]
143+
self.current_optimal = np.array([best_params[key] for key in self._float_keys])
145144

146145
self.current_d = 2.0 * (self.current_optimal - self.previous_optimal) / self.r
147146

@@ -289,4 +288,4 @@ def transform(self, target_space: TargetSpace) -> dict[str, NDArray[Float]]:
289288

290289
new_bounds = self._trim(new_bounds, self.original_bounds)
291290
self.bounds.append(new_bounds)
292-
return self._create_bounds(target_space.keys, new_bounds)
291+
return self._create_bounds(self._float_keys, new_bounds)

‎tests/test_seq_domain_red.py‎

Lines changed: 32 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -179,9 +179,35 @@ def test_minimum_window_dict_ordering():
179179
)
180180

181181

182-
def test_mixed_parameters():
183-
"""Ensure that the transformer errors when providing non-float parameters"""
184-
pbounds = {"x": (-10, 10), "y": (-10, 10), "z": (1, 10, int)}
185-
target_space = TargetSpace(target_func=black_box_function, pbounds=pbounds)
186-
with pytest.raises(ValueError):
187-
_ = SequentialDomainReductionTransformer().initialize(target_space)
182+
@pytest.mark.parametrize("window", [0.5, [0.5], {"rate": 0.5}])
183+
def test_mixed_parameters(window, tmp_path):
184+
pbounds = {"model": ["small", "medium", "large"], "depth": (1, 5, int), "rate": (0.0, 2.0)}
185+
186+
def make_optimizer():
187+
return BayesianOptimization(
188+
f=lambda model, depth, rate: -((rate - 1) ** 2) + depth + (model == "small"),
189+
pbounds=pbounds,
190+
bounds_transformer=SequentialDomainReductionTransformer(minimum_window=window),
191+
random_state=1,
192+
verbose=0,
193+
)
194+
195+
optimizer = make_optimizer()
196+
original = optimizer.space.bounds.copy()
197+
optimizer.maximize(init_points=2, n_iter=2)
198+
bounds = optimizer.space.bounds
199+
np.testing.assert_array_equal(bounds[:-1], original[:-1])
200+
assert 0.5 <= bounds[-1, 1] - bounds[-1, 0] < 2.0
201+
202+
path = tmp_path / "state.json"
203+
optimizer.save_state(path)
204+
restored = make_optimizer()
205+
restored.load_state(path)
206+
np.testing.assert_array_equal(restored.space.bounds, bounds)
207+
assert restored.max == optimizer.max
208+
209+
210+
def test_discrete_parameters_only():
211+
target_space = TargetSpace(target_func=None, pbounds={"depth": (1, 5, int)})
212+
with pytest.raises(ValueError, match="at least one FloatParameter"):
213+
SequentialDomainReductionTransformer().initialize(target_space)

0 commit comments

Comments
 (0)