-
Notifications
You must be signed in to change notification settings - Fork 54
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
Feature: Adds probability of improvement as an acquisition function #458
Merged
thomaspinder
merged 14 commits into
JaxGaussianProcesses:main
from
miguelgondu:feature-adds-probability-of-improvement
Jul 6, 2024
Merged
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
eadb7bb
Adds probability of improvement, refactors common tests for utility f…
miguelgondu 7ec1f89
Finishes a first draft of the tutorial
miguelgondu c67083f
Runs pre-commit hooks
miguelgondu e0fc9d2
Fixes a Ruff error on jaxtyping annotation
miguelgondu 623181a
Adds docstrings to probability of improvement
miguelgondu 5d0a84c
Adds a simple test for PI
miguelgondu 3924fa9
Changes the tutorial a bit before deleting it
miguelgondu ba5bbdc
Updates the tutorial on decision making by mentioning PI
miguelgondu b455c9a
Makes a better test for PI by manually computing the CDF
miguelgondu 1f67bfb
Lints according to Ruff
miguelgondu 64aeb2c
Removes the manual CDF and replaces it with tfp, improves error messa…
miguelgondu b651e90
Removes unused imports in utils
miguelgondu ceef630
Removes test of manual CDF
miguelgondu 58d7bd2
Updates the documentation to reflect changes, removes if main
miguelgondu 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
127 changes: 127 additions & 0 deletions
127
gpjax/decision_making/utility_functions/probability_of_improvement.py
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,127 @@ | ||
# Copyright 2024 The JaxGaussianProcesses Contributors. All Rights Reserved. | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
# ============================================================================== | ||
from dataclasses import dataclass | ||
|
||
from beartype.typing import Mapping | ||
from jaxtyping import Num | ||
import tensorflow_probability.substrates.jax as tfp | ||
|
||
from gpjax.dataset import Dataset | ||
from gpjax.decision_making.utility_functions.base import ( | ||
AbstractSinglePointUtilityFunctionBuilder, | ||
SinglePointUtilityFunction, | ||
) | ||
from gpjax.decision_making.utils import OBJECTIVE | ||
from gpjax.gps import ConjugatePosterior | ||
from gpjax.typing import ( | ||
Array, | ||
KeyArray, | ||
) | ||
|
||
|
||
@dataclass | ||
class ProbabilityOfImprovement(AbstractSinglePointUtilityFunctionBuilder): | ||
r""" | ||
An acquisition function which returns the probability of improvement | ||
of the objective function over the best observed value. | ||
|
||
More precisely, given a predictive posterior distribution of the objective | ||
function $`f`$, the probability of improvement at a test point $`x`$ is defined as: | ||
$$`\text{PI}(x) = \text{Prob}[f(x) < f(x_{\text{best}})]`$$ | ||
where $`x_{\text{best}}`$ is the minimiser of the posterior mean | ||
at previously observed values (to handle noisy observations). | ||
|
||
The probability of improvement can be easily computed using the | ||
cumulative distribution function of the standard normal distribution $`\Phi`$: | ||
$$`\text{PI}(x) = \Phi\left(\frac{f(x_{\text{best}}) - \mu}{\sigma}\right)`$$ | ||
where $`\mu`$ and $`\sigma`$ are the mean and standard deviation of the | ||
predictive distribution of the objective function at $`x`$. | ||
|
||
References | ||
---------- | ||
[1] Kushner, H. J. (1964). | ||
A new method of locating the maximum point of an arbitrary multipeak curve in the presence of noise. | ||
Journal of Basic Engineering, 86(1), 97-106. | ||
|
||
[2] Shahriari, B., Swersky, K., Wang, Z., Adams, R. P., & de Freitas, N. (2016). | ||
Taking the human out of the loop: A review of Bayesian optimization. | ||
Proceedings of the IEEE, 104(1), 148-175. doi: 10.1109/JPROC.2015.2494218 | ||
""" | ||
|
||
def build_utility_function( | ||
self, | ||
posteriors: Mapping[str, ConjugatePosterior], | ||
datasets: Mapping[str, Dataset], | ||
key: KeyArray, | ||
) -> SinglePointUtilityFunction: | ||
""" | ||
Constructs the probability of improvement utility function | ||
using the predictive posterior of the objective function. | ||
|
||
Args: | ||
posteriors (Mapping[str, AbstractPosterior]): Dictionary of posteriors to be | ||
used to form the utility function. One of the posteriors must correspond | ||
to the `OBJECTIVE` key, as we sample from the objective posterior to form | ||
the utility function. | ||
datasets (Mapping[str, Dataset]): Dictionary of datasets which may be used | ||
to form the utility function. Keys in `datasets` should correspond to | ||
keys in `posteriors`. One of the datasets must correspond | ||
to the `OBJECTIVE` key. | ||
key (KeyArray): JAX PRNG key used for random number generation. Since | ||
the probability of improvement is computed deterministically | ||
from the predictive posterior, the key is not used. | ||
|
||
Returns: | ||
SinglePointUtilityFunction: the probability of improvement utility function. | ||
""" | ||
self.check_objective_present(posteriors, datasets) | ||
|
||
objective_posterior = posteriors[OBJECTIVE] | ||
if not isinstance(objective_posterior, ConjugatePosterior): | ||
raise ValueError( | ||
"Objective posterior must be a ConjugatePosterior to compute the Probability of Improvement using a Gaussian CDF." | ||
) | ||
|
||
objective_dataset = datasets[OBJECTIVE] | ||
if ( | ||
objective_dataset.X is None | ||
or objective_dataset.n == 0 | ||
or objective_dataset.y is None | ||
): | ||
raise ValueError( | ||
"Objective dataset must be non-empty to compute the " | ||
"Probability of Improvement (since we need a " | ||
"`best_y` value)." | ||
) | ||
|
||
def probability_of_improvement(x_test: Num[Array, "N D"]): | ||
# Computing the posterior mean for the training dataset | ||
# for computing the best_y value (as the minimum | ||
# posterior mean of the objective function) | ||
predictive_dist_for_training = objective_posterior.predict( | ||
objective_dataset.X, objective_dataset | ||
) | ||
best_y = predictive_dist_for_training.mean().min() | ||
|
||
predictive_dist = objective_posterior.predict(x_test, objective_dataset) | ||
|
||
normal_dist = tfp.distributions.Normal( | ||
loc=predictive_dist.mean(), | ||
scale=predictive_dist.stddev(), | ||
) | ||
|
||
return normal_dist.cdf(best_y).reshape(-1, 1) | ||
|
||
return probability_of_improvement |
64 changes: 64 additions & 0 deletions
64
tests/test_decision_making/test_utility_functions/test_probability_of_improvement.py
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,64 @@ | ||
# Copyright 2023 The GPJax Contributors. All Rights Reserved. | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
# ============================================================================== | ||
from jax import config | ||
|
||
config.update("jax_enable_x64", True) | ||
|
||
import jax | ||
import jax.numpy as jnp | ||
import jax.random as jr | ||
|
||
from gpjax.decision_making.test_functions.continuous_functions import Forrester | ||
from gpjax.decision_making.utility_functions.probability_of_improvement import ( | ||
ProbabilityOfImprovement, | ||
) | ||
from gpjax.decision_making.utils import OBJECTIVE | ||
from tests.test_decision_making.utils import generate_dummy_conjugate_posterior | ||
|
||
|
||
def test_probability_of_improvement_gives_correct_value_for_a_seed(): | ||
key = jr.key(42) | ||
forrester = Forrester() | ||
dataset = forrester.generate_dataset(num_points=10, key=key) | ||
posterior = generate_dummy_conjugate_posterior(dataset) | ||
posteriors = {OBJECTIVE: posterior} | ||
datasets = {OBJECTIVE: dataset} | ||
|
||
pi_utility_builder = ProbabilityOfImprovement() | ||
pi_utility = pi_utility_builder.build_utility_function( | ||
posteriors=posteriors, datasets=datasets, key=key | ||
) | ||
|
||
test_X = forrester.generate_test_points(num_points=10, key=key) | ||
utility_values = pi_utility(test_X) | ||
|
||
# Computing the expected utility values | ||
predictive_dist = posterior.predict(test_X, train_data=dataset) | ||
predictive_mean = predictive_dist.mean() | ||
predictive_std = predictive_dist.stddev() | ||
|
||
# Computing best_y as the min. of the posterior predictive mean | ||
# over the training set. | ||
predictive_dist_for_training_data = posterior.predict(dataset.X, train_data=dataset) | ||
best_y = predictive_dist_for_training_data.mean().min() | ||
|
||
# Gaussian CDF computed "by hand" | ||
x_ = (best_y - predictive_mean) / predictive_std | ||
expected_utility_values = 0.5 * ( | ||
1 + jax.scipy.special.erf(x_ / jnp.sqrt(2)) | ||
).reshape(-1, 1) | ||
|
||
assert utility_values.shape == (10, 1) | ||
assert jnp.isclose(utility_values, expected_utility_values).all() |
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.
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.
Probably best to have something along the lines of
given that we use the objective dataset to find
best_y
.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.
Addressed!