diff --git a/bayes_opt/bayesian_optimization.py b/bayes_opt/bayesian_optimization.py index f3f151fd..1248e475 100644 --- a/bayes_opt/bayesian_optimization.py +++ b/bayes_opt/bayesian_optimization.py @@ -474,9 +474,13 @@ def _load_state_dict(self, state: dict[str, Any]) -> None: self._acquisition_function.set_acquisition_params(state["acquisition_params"]) if state.get("transformed_bounds") and self._bounds_transformer: + bounds = np.asarray(state["transformed_bounds"]) + # Discrete parameters keep their typed domains; a categorical + # parameter can occupy several rows of the encoded bounds. new_bounds = { - key: bounds - for key, bounds in zip(self._space.keys, np.array(state["transformed_bounds"]), strict=False) + key: bounds[mask][0] + for key, mask in self._space.masks.items() + if not np.array_equal(bounds[mask], self._space.bounds[mask]) } self._space.set_bounds(new_bounds) self._bounds_transformer.initialize(self._space) diff --git a/bayes_opt/domain_reduction.py b/bayes_opt/domain_reduction.py index 634fffdb..f191f20b 100644 --- a/bayes_opt/domain_reduction.py +++ b/bayes_opt/domain_reduction.py @@ -57,8 +57,9 @@ class SequentialDomainReductionTransformer(DomainTransformer): Zooming parameter used to shrink the region of interest. minimum_window : float or np.ndarray or dict, default=0.0 - Minimum window size for each parameter. If a float is provided, - the same value is used for all parameters. + Minimum window size for each float parameter, in parameter order. If a + scalar is provided, the same value is used for all float parameters. + Integer and categorical parameters retain their original domains. """ def __init__( @@ -69,7 +70,6 @@ def __init__( eta: float = 0.9, minimum_window: NDArray[Float] | Sequence[float] | Mapping[str, float] | float = 0.0, ) -> None: - # TODO: Ensure that this is only applied to continuous parameters self.parameters = parameters self.gamma_osc = gamma_osc self.gamma_pan = gamma_pan @@ -85,33 +85,31 @@ def initialize(self, target_space: TargetSpace) -> None: target_space : TargetSpace TargetSpace this DomainTransformer operates on. """ - if isinstance(self.minimum_window_value, Mapping): - self.minimum_window_value = [self.minimum_window_value[key] for key in target_space.keys] - else: - self.minimum_window_value = self.minimum_window_value - - any_not_float = any(not isinstance(p, FloatParameter) for p in target_space._params_config.values()) - if any_not_float: - msg = "Domain reduction is only supported for all-FloatParameter optimization." + self._float_keys = [ + key for key, param in target_space.params_config.items() if isinstance(param, FloatParameter) + ] + if not self._float_keys: + msg = "Domain reduction requires at least one FloatParameter." raise ValueError(msg) - # Set the original bounds - self.original_bounds = np.copy(target_space.bounds) + self.original_bounds = np.array([target_space.params_config[key].bounds for key in self._float_keys]) self.bounds = [self.original_bounds] self.minimum_window: NDArray[Float] | Sequence[float] # Set the minimum window to an array of length bounds - if isinstance(self.minimum_window_value, (Sequence, np.ndarray)): - if len(self.minimum_window_value) != len(target_space.bounds): - error_msg = "Length of minimum_window must be the same as the number of parameters" + if isinstance(self.minimum_window_value, Mapping): + self.minimum_window = [self.minimum_window_value[key] for key in self._float_keys] + elif isinstance(self.minimum_window_value, (Sequence, np.ndarray)): + if len(self.minimum_window_value) != len(self._float_keys): + error_msg = "Length of minimum_window must be the same as the number of float parameters" raise ValueError(error_msg) self.minimum_window = self.minimum_window_value else: - self.minimum_window = [self.minimum_window_value] * len(target_space.bounds) + self.minimum_window = [self.minimum_window_value] * len(self._float_keys) # Set initial values - self.previous_optimal = np.mean(target_space.bounds, axis=1) - self.current_optimal = np.mean(target_space.bounds, axis=1) - self.r = target_space.bounds[:, 1] - target_space.bounds[:, 0] + self.previous_optimal = np.mean(self.original_bounds, axis=1) + self.current_optimal = np.mean(self.original_bounds, axis=1) + self.r = self.original_bounds[:, 1] - self.original_bounds[:, 0] self.previous_d = 2.0 * (self.current_optimal - self.previous_optimal) / self.r @@ -141,7 +139,8 @@ def _update(self, target_space: TargetSpace) -> None: self.previous_optimal = self.current_optimal self.previous_d = self.current_d - self.current_optimal = target_space.params_to_array(target_space.max()["params"]) + best_params = target_space.max()["params"] + self.current_optimal = np.array([best_params[key] for key in self._float_keys]) self.current_d = 2.0 * (self.current_optimal - self.previous_optimal) / self.r @@ -289,4 +288,4 @@ def transform(self, target_space: TargetSpace) -> dict[str, NDArray[Float]]: new_bounds = self._trim(new_bounds, self.original_bounds) self.bounds.append(new_bounds) - return self._create_bounds(target_space.keys, new_bounds) + return self._create_bounds(self._float_keys, new_bounds) diff --git a/tests/test_seq_domain_red.py b/tests/test_seq_domain_red.py index 5865d877..e04650cc 100644 --- a/tests/test_seq_domain_red.py +++ b/tests/test_seq_domain_red.py @@ -179,9 +179,35 @@ def test_minimum_window_dict_ordering(): ) -def test_mixed_parameters(): - """Ensure that the transformer errors when providing non-float parameters""" - pbounds = {"x": (-10, 10), "y": (-10, 10), "z": (1, 10, int)} - target_space = TargetSpace(target_func=black_box_function, pbounds=pbounds) - with pytest.raises(ValueError): - _ = SequentialDomainReductionTransformer().initialize(target_space) +@pytest.mark.parametrize("window", [0.5, [0.5], {"rate": 0.5}]) +def test_mixed_parameters(window, tmp_path): + pbounds = {"model": ["small", "medium", "large"], "depth": (1, 5, int), "rate": (0.0, 2.0)} + + def make_optimizer(): + return BayesianOptimization( + f=lambda model, depth, rate: -((rate - 1) ** 2) + depth + (model == "small"), + pbounds=pbounds, + bounds_transformer=SequentialDomainReductionTransformer(minimum_window=window), + random_state=1, + verbose=0, + ) + + optimizer = make_optimizer() + original = optimizer.space.bounds.copy() + optimizer.maximize(init_points=2, n_iter=2) + bounds = optimizer.space.bounds + np.testing.assert_array_equal(bounds[:-1], original[:-1]) + assert 0.5 <= bounds[-1, 1] - bounds[-1, 0] < 2.0 + + path = tmp_path / "state.json" + optimizer.save_state(path) + restored = make_optimizer() + restored.load_state(path) + np.testing.assert_array_equal(restored.space.bounds, bounds) + assert restored.max == optimizer.max + + +def test_discrete_parameters_only(): + target_space = TargetSpace(target_func=None, pbounds={"depth": (1, 5, int)}) + with pytest.raises(ValueError, match="at least one FloatParameter"): + SequentialDomainReductionTransformer().initialize(target_space)