-
Notifications
You must be signed in to change notification settings - Fork 127
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
BQ stopping criteria that depend on model statistics #463
Draft
mmahsereci
wants to merge
6
commits into
EmuKit:main
Choose a base branch
from
mmahsereci:mm-bq-stopping-conditions
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
0f44c1d
add BQLoopState BQOuterLoop and COV stopping condition
mmahsereci 695fa22
some simplifications
mmahsereci e24fb06
adding changes to docs
mmahsereci 10c130d
Merge branch 'main' into mm-bq-stopping-conditions
mmahsereci be501a2
Merge branch 'main' into mm-bq-stopping-conditions
mmahsereci addb62d
docstring updates
mmahsereci File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
# Copyright 2020-2024 The Emukit Authors. All Rights Reserved. | ||
# SPDX-License-Identifier: Apache-2.0 | ||
|
||
|
||
from typing import List, Optional | ||
|
||
import numpy as np | ||
|
||
from ...core.loop.loop_state import LoopState, create_loop_state | ||
from ...core.loop.user_function_result import UserFunctionResult | ||
|
||
|
||
class QuadratureLoopState(LoopState): | ||
"""Contains the state of the BQ loop, which includes a history of all integrand evaluations and integral mean and | ||
variance estimates. | ||
|
||
:param initial_results: The results from previous integrand evaluations. | ||
|
||
""" | ||
|
||
def __init__(self, initial_results: List[UserFunctionResult]) -> None: | ||
|
||
super().__init__(initial_results) | ||
|
||
self.integral_means = [] | ||
self.integral_vars = [] | ||
|
||
def update_integral_stats(self, integral_mean: float, integral_var: float) -> None: | ||
"""Adds the latest integral mean and variance to the loop state. | ||
|
||
:param integral_mean: The latest integral mean estimate. | ||
:param integral_var: The latest integral variance. | ||
""" | ||
self.integral_means.append(integral_mean) | ||
self.integral_vars.append(integral_var) | ||
|
||
|
||
def create_bq_loop_state(x_init: np.ndarray, y_init: np.ndarray, **kwargs) -> QuadratureLoopState: | ||
"""Creates a BQ loop state object using the provided data. | ||
|
||
:param x_init: x values for initial function evaluations. Shape: (n_initial_points x n_input_dims) | ||
:param y_init: y values for initial function evaluations. Shape: (n_initial_points x n_output_dims) | ||
:param kwargs: extra outputs observed from a function evaluation. Shape: (n_initial_points x n_dims) | ||
:return: The BQ loop state. | ||
""" | ||
|
||
loop_state = create_loop_state(x_init, y_init, **kwargs) | ||
return QuadratureLoopState(loop_state.results) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
# Copyright 2020-2024 The Emukit Authors. All Rights Reserved. | ||
# SPDX-License-Identifier: Apache-2.0 | ||
|
||
|
||
from typing import List, Union | ||
|
||
from ...core.loop import OuterLoop | ||
from ...core.loop.candidate_point_calculators import CandidatePointCalculator | ||
from ...core.loop.model_updaters import ModelUpdater | ||
from .bq_loop_state import QuadratureLoopState | ||
|
||
|
||
class QuadratureOuterLoop(OuterLoop): | ||
"""Base class for a Bayesian quadrature loop. | ||
|
||
:param candidate_point_calculator: Finds next point(s) to evaluate. | ||
:param model_updaters: Updates the model with the new data and fits the model hyper-parameters. | ||
:param loop_state: Object that keeps track of the history of the BQ loop. Default is None, resulting in empty | ||
initial state. | ||
|
||
:raises ValueError: If more than one model updater is provided. | ||
|
||
""" | ||
|
||
def __init__( | ||
self, | ||
candidate_point_calculator: CandidatePointCalculator, | ||
model_updaters: Union[ModelUpdater, List[ModelUpdater]], | ||
loop_state: QuadratureLoopState = None, | ||
): | ||
if isinstance(model_updaters, list): | ||
raise ValueError("The BQ loop only supports a single model.") | ||
|
||
super().__init__(candidate_point_calculator, model_updaters, loop_state) | ||
|
||
def _update_loop_state(self) -> None: | ||
model = self.model_updaters[0].model # only works if there is one model, but for BQ nothing else makes sense | ||
integral_mean, integral_var = model.integrate() | ||
self.loop_state.update_integral_stats(integral_mean, integral_var) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,63 @@ | ||
# Copyright 2020-2024 The Emukit Authors. All Rights Reserved. | ||
# SPDX-License-Identifier: Apache-2.0 | ||
|
||
|
||
import logging | ||
|
||
import numpy as np | ||
|
||
from ...core.loop.stopping_conditions import StoppingCondition | ||
from .bq_loop_state import QuadratureLoopState | ||
|
||
_log = logging.getLogger(__name__) | ||
|
||
|
||
class CoefficientOfVariationStoppingCondition(StoppingCondition): | ||
r"""Stops once the coefficient of variation (COV) falls below a threshold. | ||
|
||
The COV is given by | ||
|
||
.. math:: | ||
COV = \frac{\sigma}{\mu} | ||
|
||
where :math:`\mu` and :math:`\sigma^2` are the current mean and variance respectively of the integral according to | ||
the BQ posterior model. | ||
|
||
:param eps: Threshold under which the COV must fall. | ||
:param delay: Number of times the stopping condition needs to be true in a row in order to stop. Defaults to 1. | ||
|
||
:raises ValueError: If `delay` is smaller than 1. | ||
:raises ValueError: If `eps` is non-negative. | ||
|
||
""" | ||
|
||
def __init__(self, eps: float, delay: int = 1) -> None: | ||
|
||
if delay < 1: | ||
raise ValueError(f"delay ({delay}) must be and integer greater than zero.") | ||
|
||
if eps <= 0.0: | ||
raise ValueError(f"eps ({eps}) must be positive.") | ||
|
||
self.eps = eps | ||
self.delay = delay | ||
self.times_true = 0 # counts how many times stopping has been triggered in a row | ||
|
||
def should_stop(self, loop_state: QuadratureLoopState) -> bool: | ||
if len(loop_state.integral_means) < 1: | ||
return False | ||
|
||
m = loop_state.integral_means[-1] | ||
v = loop_state.integral_vars[-1] | ||
should_stop = (np.sqrt(v) / m) < self.eps | ||
|
||
if should_stop: | ||
self.times_true += 1 | ||
else: | ||
self.times_true = 0 | ||
|
||
should_stop = should_stop and (self.times_true >= self.delay) | ||
|
||
if should_stop: | ||
_log.info(f"Stopped as coefficient of variation is below threshold of {self.eps}.") | ||
return should_stop |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
because if you pass float('inf'), then you will have an infinite loop right?