Skip to content

Allow saving and loading optimizer state without probes/registrations #582

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 2 additions & 13 deletions bayes_opt/bayesian_optimization.py
Original file line number Diff line number Diff line change
Expand Up @@ -352,19 +352,7 @@ def save_state(self, path: str | PathLike[str]) -> None:
----------
path : str or PathLike
Path to save the optimization state

Raises
------
ValueError
If attempting to save state before collecting any samples.
"""
if len(self._space) == 0:
msg = (
"Cannot save optimizer state before collecting any samples. "
"Please probe or register at least one point before saving."
)
raise ValueError(msg)

random_state = None
if self._random_state is not None:
state_tuple = self._random_state.get_state()
Expand Down Expand Up @@ -443,7 +431,8 @@ def load_state(self, path: str | PathLike[str]) -> None:
# Set the GP parameters
self.set_gp_params(**gp_params)

self._gp.fit(self._space.params, self._space.target)
if len(self._space):
self._gp.fit(self._space.params, self._space.target)

if state["random_state"] is not None:
random_state_tuple = (
Expand Down
14 changes: 8 additions & 6 deletions tests/test_bayesian_optimization.py
Original file line number Diff line number Diff line change
Expand Up @@ -372,14 +372,16 @@ def test_save_load_unused_optimizer(tmp_path):
"""Test saving and loading optimizer state with unused optimizer."""
optimizer = BayesianOptimization(f=target_func, pbounds=PBOUNDS, random_state=1, verbose=0)

# Test that saving without samples raises an error
with pytest.raises(ValueError, match="Cannot save optimizer state before collecting any samples"):
optimizer.save_state(tmp_path / "optimizer_state.json")
# Test that saving without samples does not raise an error
optimizer.save_state(tmp_path / "unprobed_optimizer_state.json")

# Add a sample point
optimizer.probe(params={"p1": 1, "p2": 2}, lazy=False)
# Check that we load the original state
first_suggestion = optimizer.suggest()
optimizer.load_state(tmp_path / "unprobed_optimizer_state.json")
assert optimizer.suggest() == first_suggestion

# Now saving should work
# Save an optimizer state with a probed point
optimizer.probe(params={"p1": 1, "p2": 2}, lazy=False)
optimizer.save_state(tmp_path / "optimizer_state.json")

new_optimizer = BayesianOptimization(f=target_func, pbounds=PBOUNDS, random_state=1, verbose=0)
Expand Down