Skip to content

Commit 9543fb8

Browse files
committed
Update code
1 parent b97c11e commit 9543fb8

File tree

11 files changed

+150
-185
lines changed

11 files changed

+150
-185
lines changed

bayes_opt/parameter.py

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -195,11 +195,6 @@ def to_param(self, value: float | NDArray[Float]) -> float:
195195
Any
196196
The canonical representation of the parameter.
197197
"""
198-
if isinstance(value, np.ndarray) and value.size != 1:
199-
msg = "FloatParameter value should be scalar"
200-
raise ValueError(msg)
201-
if isinstance(value, (int, float)):
202-
return value
203198
return value.flatten()[0]
204199

205200
def to_string(self, value: float, str_len: int) -> str:

bayes_opt/target_space.py

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from __future__ import annotations
44

5+
from copy import deepcopy
56
from typing import TYPE_CHECKING, Any
67
from warnings import warn
78

@@ -125,9 +126,6 @@ def __len__(self) -> int:
125126
-------
126127
int
127128
"""
128-
if len(self._params) != len(self._target):
129-
error_msg = "The number of parameters and targets do not match."
130-
raise ValueError(error_msg)
131129
return len(self._target)
132130

133131
@property
@@ -404,10 +402,8 @@ def _as_array(self, x: Any) -> NDArray[Float]:
404402

405403
x = x.ravel()
406404
if x.size != self.dim:
407-
error_msg = (
408-
f"Size of array ({len(x)}) is different than the " f"expected number of ({len(self.dim)})."
409-
)
410-
raise ValueError(error_msg)
405+
msg = f"Size of array ({len(x)}) is different than the expected number of ({self.dim})."
406+
raise ValueError(msg)
411407
return x
412408

413409
def register(
@@ -683,19 +679,23 @@ def set_bounds(self, new_bounds: BoundsMapping) -> None:
683679
"""
684680
new_params_config = self.make_params(new_bounds)
685681

682+
dims = 0
683+
params_config = deepcopy(self._params_config)
686684
for key in self.keys:
687685
if key in new_bounds:
688-
if isinstance(self._params_config[key], CategoricalParameter) and set(
689-
self._params_config[key].domain
690-
) == set(new_bounds[key]):
691-
msg = "Changing bounds of categorical parameters is not supported"
692-
raise NotImplementedError(msg)
693686
if not isinstance(new_params_config[key], type(self._params_config[key])):
694687
msg = (
695688
f"Parameter type {type(new_params_config[key])} of"
696689
" new bounds does not match parameter type"
697690
f" {type(self._params_config[key])} of old bounds"
698691
)
699692
raise ValueError(msg)
700-
self._params_config[key] = new_params_config[key]
693+
params_config[key] = new_params_config[key]
694+
dims = dims + params_config[key].dim
695+
if dims != self.dim:
696+
msg = (
697+
f"Dimensions of new bounds ({dims}) does not match" f" dimensions of old bounds ({self.dim})."
698+
)
699+
raise ValueError(msg)
700+
self._params_config = params_config
701701
self._bounds = self.calculate_bounds()

examples/parameter_types.ipynb

Lines changed: 57 additions & 57 deletions
Large diffs are not rendered by default.

ruff.toml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,3 +126,6 @@ split-on-trailing-comma = false
126126

127127
[lint.pydocstyle]
128128
convention = "numpy"
129+
130+
[lint.flake8-pytest-style]
131+
fixture-parentheses = false

tests/test_acceptance.py

Lines changed: 0 additions & 69 deletions
This file was deleted.

tests/test_bayesian_optimization.py

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -333,11 +333,3 @@ def test_duplicate_points():
333333
optimizer.register(params=next_point_to_probe, target=target)
334334
# and again (should throw warning)
335335
optimizer.register(params=next_point_to_probe, target=target)
336-
337-
338-
if __name__ == "__main__":
339-
r"""
340-
CommandLine:
341-
python tests/test_bayesian_optimization.py
342-
"""
343-
pytest.main([__file__])

tests/test_observer.py

Lines changed: 0 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -114,13 +114,3 @@ def max(self):
114114
assert start_time == tracker._start_time
115115
if "win" not in sys.platform:
116116
assert previous_time < tracker._previous_time
117-
118-
119-
if __name__ == "__main__":
120-
r"""
121-
CommandLine:
122-
python tests/test_observer.py
123-
"""
124-
import pytest
125-
126-
pytest.main([__file__])

tests/test_parameter.py

Lines changed: 62 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,11 @@
22

33
import numpy as np
44
import pytest
5+
from scipy.optimize import NonlinearConstraint
6+
from sklearn.gaussian_process import GaussianProcessRegressor, kernels
57

68
from bayes_opt import BayesianOptimization
7-
from bayes_opt.parameter import CategoricalParameter, FloatParameter, IntParameter
9+
from bayes_opt.parameter import CategoricalParameter, FloatParameter, IntParameter, wrap_kernel
810
from bayes_opt.target_space import TargetSpace
911

1012

@@ -168,6 +170,22 @@ def test_to_string():
168170
assert space._params_config["fruit"].to_string("strawberry", 10) == "strawberry"
169171

170172

173+
def test_preconstructed_parameter():
174+
pbounds = {"p1": (0, 1), "p2": (1, 2), "p3": IntParameter("p3", (-1, 3))}
175+
176+
def target_func(p1, p2, p3):
177+
return p1 + p2 + p3
178+
179+
optimizer1 = BayesianOptimization(target_func, pbounds)
180+
181+
pbounds = {"p1": (0, 1), "p2": (1, 2), "p3": (-1, 3, int)}
182+
optimizer2 = BayesianOptimization(target_func, pbounds)
183+
184+
assert optimizer1.space.keys == optimizer2.space.keys
185+
assert (optimizer1.space.bounds == optimizer2.space.bounds).all()
186+
assert optimizer1.space._params_config["p3"].to_float(2) == 2.0
187+
188+
171189
def test_integration_mixed_optimization():
172190
fruit_ratings = {"apple": 1.0, "banana": 2.0, "mango": 5.0, "honeydew melon": -10.0, "strawberry": np.pi}
173191

@@ -183,3 +201,46 @@ def target_func(p1, p2, p3, fruit):
183201

184202
optimizer = BayesianOptimization(target_func, pbounds)
185203
optimizer.maximize(init_points=2, n_iter=10)
204+
205+
206+
def test_integration_mixed_optimization_with_constraints():
207+
fruit_ratings = {"apple": 1.0, "banana": 2.0, "mango": 5.0, "honeydew melon": -10.0, "strawberry": np.pi}
208+
209+
pbounds = {
210+
"p1": (0, 1),
211+
"p2": (1, 2),
212+
"p3": (-1, 3, int),
213+
"fruit": ("apple", "banana", "mango", "honeydew melon", "strawberry"),
214+
}
215+
216+
def target_func(p1, p2, p3, fruit):
217+
return p1 + p2 + p3 + fruit_ratings[fruit]
218+
219+
def constraint_func(p1, p2, p3, fruit):
220+
return (p1 + p2 + p3 - fruit_ratings[fruit]) ** 2
221+
222+
constraint = NonlinearConstraint(constraint_func, 0, 4.0)
223+
224+
optimizer = BayesianOptimization(target_func, pbounds, constraint=constraint)
225+
init_points = [
226+
{"p1": 0.5, "p2": 1.5, "p3": 1, "fruit": "banana"},
227+
{"p1": 0.5, "p2": 1.5, "p3": 2, "fruit": "mango"},
228+
]
229+
for p in init_points:
230+
optimizer.register(p, target=target_func(**p), constraint_value=constraint_func(**p))
231+
optimizer.maximize(init_points=0, n_iter=2)
232+
233+
234+
def test_wrapped_kernel_fit():
235+
pbounds = {"p1": (0, 1), "p2": (1, 10, int)}
236+
space = TargetSpace(None, pbounds)
237+
238+
space.register(space.random_sample(0), 1.0)
239+
space.register(space.random_sample(1), 5.0)
240+
241+
kernel = wrap_kernel(kernels.Matern(nu=2.5, length_scale=1e5), space.kernel_transform)
242+
gp = GaussianProcessRegressor(kernel=kernel, alpha=1e-6, n_restarts_optimizer=5)
243+
244+
gp.fit(space.params, space.target)
245+
246+
assert gp.kernel_.length_scale != 1e5

tests/test_seq_domain_red.py

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -185,11 +185,3 @@ def test_mixed_parameters():
185185
target_space = TargetSpace(target_func=black_box_function, pbounds=pbounds)
186186
with pytest.raises(ValueError):
187187
_ = SequentialDomainReductionTransformer().initialize(target_space)
188-
189-
190-
if __name__ == "__main__":
191-
r"""
192-
CommandLine:
193-
python tests/test_seq_domain_red.py
194-
"""
195-
pytest.main([__file__])

tests/test_target_space.py

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -294,9 +294,18 @@ def test_no_target_func():
294294
target_space.probe({"p1": 1, "p2": 2})
295295

296296

297-
if __name__ == "__main__":
298-
r"""
299-
CommandLine:
300-
python tests/test_target_space.py
301-
"""
302-
pytest.main([__file__])
297+
def test_change_typed_bounds():
298+
pbounds = {
299+
"p1": (0, 1),
300+
"p2": (1, 2),
301+
"p3": (-1, 3, int),
302+
"fruit": ("apple", "banana", "mango", "honeydew melon", "strawberry"),
303+
}
304+
305+
space = TargetSpace(None, pbounds)
306+
307+
with pytest.raises(ValueError):
308+
space.set_bounds({"fruit": ("apple", "banana", "mango", "honeydew melon")})
309+
310+
with pytest.raises(ValueError):
311+
space.set_bounds({"p3": (-1, 2, float)})

0 commit comments

Comments
 (0)