diff --git a/.github/workflows/build_docs.yml b/.github/workflows/build_docs.yml index 07282413b..d461c2dab 100644 --- a/.github/workflows/build_docs.yml +++ b/.github/workflows/build_docs.yml @@ -29,6 +29,7 @@ jobs: pip install nbsphinx pip install sphinx_rtd_theme pip install jupyter + pip install myst-parser - name: Install package run: | pip install -e . diff --git a/.github/workflows/check_docstrings.yml b/.github/workflows/check_docstrings.yml new file mode 100644 index 000000000..83b5d4ac8 --- /dev/null +++ b/.github/workflows/check_docstrings.yml @@ -0,0 +1,30 @@ +# This workflow will install Python dependencies and check docstrings with a single version of Python +# For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions + +name: Check docstrings + +on: + push: + branches: [ "master" ] + pull_request: + +permissions: + contents: read + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - name: Set up Python 3.10 + uses: actions/setup-python@v3 + with: + python-version: "3.10" + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install pydocstyle + - name: Check docstyle + run : pydocstyle --convention=numpy --add-select D417 bayes_opt/* + #- name: Run linting + # run : pylint bayes_opt/* --disable=C0103 # ignore no snake_case conformity of arguments diff --git a/.github/workflows/run_tests.yml b/.github/workflows/run_tests.yml index 3a809789e..0551a364e 100644 --- a/.github/workflows/run_tests.yml +++ b/.github/workflows/run_tests.yml @@ -7,7 +7,6 @@ on: push: branches: [ "master" ] pull_request: - branches: [ "master" ] permissions: contents: read diff --git a/.gitignore b/.gitignore index 3f4f6d54e..6556c710e 100644 --- a/.gitignore +++ b/.gitignore @@ -32,4 +32,6 @@ venv.bak/ docs/* docsrc/.ipynb_checkpoints/* -docsrc/*.ipynb \ No newline at end of file +docsrc/*.ipynb +docsrc/static/* +docsrc/README.md diff --git a/README.md b/README.md index ac94cc649..229fa2ef2 100644 --- a/README.md +++ b/README.md @@ -1,16 +1,18 @@
-

+

# Bayesian Optimization -![tests](https://github.com/fmfn/BayesianOptimization/actions/workflows/run_tests.yml/badge.svg) -[![Codecov](https://codecov.io/github/fmfn/BayesianOptimization/badge.svg?branch=master&service=github)](https://codecov.io/github/fmfn/BayesianOptimization?branch=master) +![tests](https://github.com/bayesian-optimization/BayesianOptimization/actions/workflows/run_tests.yml/badge.svg) +[![Codecov](https://codecov.io/github/bayesian-optimization/BayesianOptimization/badge.svg?branch=master&service=github)](https://codecov.io/github/bayesian-optimization/BayesianOptimization?branch=master) [![Pypi](https://img.shields.io/pypi/v/bayesian-optimization.svg)](https://pypi.python.org/pypi/bayesian-optimization) Pure Python implementation of bayesian global optimization with gaussian processes. +## Installation + * PyPI (pip): ```console @@ -30,25 +32,18 @@ suited for optimization of high cost functions, situations where the balance between exploration and exploitation is important. ## Quick Start -See below for a quick tour over the basics of the Bayesian Optimization package. More detailed information, other advanced features, and tips on usage/implementation can be found in the [examples](https://github.com/fmfn/BayesianOptimization/tree/master/examples) folder. I suggest that you: -- Follow the -[basic tour notebook](https://github.com/fmfn/BayesianOptimization/blob/master/examples/basic-tour.ipynb) -to learn how to use the package's most important features. -- Take a look at the -[advanced tour notebook](https://github.com/fmfn/BayesianOptimization/blob/master/examples/advanced-tour.ipynb) -to learn how to make the package more flexible, how to deal with categorical parameters, how to use observers, and more. -- Check out this -[notebook](https://github.com/fmfn/BayesianOptimization/blob/master/examples/visualization.ipynb) -with a step by step visualization of how this method works. -- To understand how to use bayesian optimization when additional constraints are present, see the -[constrained optimization notebook](https://github.com/fmfn/BayesianOptimization/blob/master/examples/constraints.ipynb). -- Explore this [notebook](https://github.com/fmfn/BayesianOptimization/blob/master/examples/exploitation_vs_exploration.ipynb) +See below for a quick tour over the basics of the Bayesian Optimization package. More detailed information, other advanced features, and tips on usage/implementation can be found in the [examples](http://bayesian-optimization.github.io/BayesianOptimization/examples.html) folder. I suggest that you: +- Follow the [basic tour notebook](http://bayesian-optimization.github.io/BayesianOptimization/basic-tour.html) to learn how to use the package's most important features. +- Take a look at the [advanced tour notebook](http://bayesian-optimization.github.io/BayesianOptimization/advanced-tour.html) to learn how to make the package more flexible, how to deal with categorical parameters, how to use observers, and more. +- Check out this [notebook](http://bayesian-optimization.github.io/BayesianOptimization/visualization.html) with a step by step visualization of how this method works. +- To understand how to use bayesian optimization when additional constraints are present, see the [constrained optimization notebook](http://bayesian-optimization.github.io/BayesianOptimization/constraints.html). +- Explore this [notebook](http://bayesian-optimization.github.io/BayesianOptimization/exploitation_vs_exploration.html) exemplifying the balance between exploration and exploitation and how to control it. -- Go over this [script](https://github.com/fmfn/BayesianOptimization/blob/master/examples/sklearn_example.py) +- Go over this [script](https://github.com/bayesian-optimization/BayesianOptimization/blob/master/examples/sklearn_example.py) for examples of how to tune parameters of Machine Learning models using cross validation and bayesian optimization. -- Explore the [domain reduction notebook](https://github.com/fmfn/BayesianOptimization/blob/master/examples/domain_reduction.ipynb) to learn more about how search can be sped up by dynamically changing parameters' bounds. -- Finally, take a look at this [script](https://github.com/fmfn/BayesianOptimization/blob/master/examples/async_optimization.py) +- Explore the [domain reduction notebook](http://bayesian-optimization.github.io/BayesianOptimization/domain_reduction.html) to learn more about how search can be sped up by dynamically changing parameters' bounds. +- Finally, take a look at this [script](https://github.com/bayesian-optimization/BayesianOptimization/blob/master/examples/async_optimization.py) for ideas on how to implement bayesian optimization in a distributed fashion using this package. @@ -56,11 +51,11 @@ for ideas on how to implement bayesian optimization in a distributed fashion usi Bayesian optimization works by constructing a posterior distribution of functions (gaussian process) that best describes the function you want to optimize. As the number of observations grows, the posterior distribution improves, and the algorithm becomes more certain of which regions in parameter space are worth exploring and which are not, as seen in the picture below. -![BayesianOptimization in action](./examples/bo_example.png) +![BayesianOptimization in action](./static/bo_example.png) As you iterate over and over, the algorithm balances its needs of exploration and exploitation taking into account what it knows about the target function. At each step a Gaussian Process is fitted to the known samples (points previously explored), and the posterior distribution, combined with a exploration strategy (such as UCB (Upper Confidence Bound), or EI (Expected Improvement)), are used to determine the next point that should be explored (see the gif below). -![BayesianOptimization in action](./examples/bayesian_optimization.gif) +![BayesianOptimization in action](./static/bayesian_optimization.gif) This process is designed to minimize the number of steps required to find a combination of parameters that are close to the optimal combination. To do so, this method uses a proxy optimization problem (finding the maximum of the acquisition function) that, albeit still a hard problem, is cheaper (in the computational sense) and common tools can be employed. Therefore Bayesian Optimization is most adequate for situations where sampling the function to be optimized is a very expensive endeavor. See the references for a proper discussion of this method. @@ -68,10 +63,9 @@ This project is under active development, if you find a bug, or anything that needs correction, please let me know. -Basic tour of the Bayesian Optimization package -=============================================== +## Basic tour of the Bayesian Optimization package -## 1. Specifying the function to be optimized +### 1. Specifying the function to be optimized This is a function optimization package, therefore the first and most important ingredient is, of course, the function to be optimized. @@ -89,7 +83,7 @@ def black_box_function(x, y): return -x ** 2 - (y - 1) ** 2 + 1 ``` -## 2. Getting Started +### 2. Getting Started All we need to get started is to instantiate a `BayesianOptimization` object specifying a function to be optimized `f`, and its parameters with their corresponding bounds, `pbounds`. This is a constrained optimization technique, so you must specify the minimum and maximum values that can be probed for each parameter in order for it to work @@ -160,7 +154,7 @@ for i, res in enumerate(optimizer.res): ``` -### 2.1 Changing bounds +#### 2.1 Changing bounds During the optimization process you may realize the bounds chosen for some parameters are not adequate. For these situations you can invoke the method `set_bounds` to alter them. You can pass any combination of **existing** parameters and their associated new bounds. @@ -183,17 +177,17 @@ optimizer.maximize( | 10 | -1.762 | 1.442 | 0.1735 | ================================================= -### 2.2 Sequential Domain Reduction +#### 2.2 Sequential Domain Reduction Sometimes the initial boundaries specified for a problem are too wide, and adding points to improve the response surface in regions of the solution domain is extraneous. Other times the cost function is very expensive to compute, and minimizing the number of calls is extremely beneficial. When it's worthwhile to converge on an optimal point quickly rather than try to find the optimal point, contracting the domain around the current optimal value as the search progresses can speed up the search progress considerably. Using the `SequentialDomainReductionTransformer` the bounds of the problem can be panned and zoomed dynamically in an attempt to improve convergence. -![sequential domain reduction](./examples/sdr.png) +![sequential domain reduction](./static/sdr.png) -An example of using the `SequentialDomainReductionTransformer` is shown in the [domain reduction notebook](https://github.com/fmfn/BayesianOptimization/blob/master/examples/domain_reduction.ipynb). More information about this method can be found in the paper ["On the robustness of a simple domain reduction scheme for simulation‐based optimization"](http://www.truegrid.com/srsm_revised.pdf). +An example of using the `SequentialDomainReductionTransformer` is shown in the [domain reduction notebook](http://bayesian-optimization.github.io/BayesianOptimization/domain_reduction.html). More information about this method can be found in the paper ["On the robustness of a simple domain reduction scheme for simulation‐based optimization"](http://www.truegrid.com/srsm_revised.pdf). -## 3. Guiding the optimization +### 3. Guiding the optimization It is often the case that we have an idea of regions of the parameter space where the maximum of our function might lie. For these situations the `BayesianOptimization` object allows the user to specify points to be probed. By default these will be explored lazily (`lazy=True`), meaning these points will be evaluated only the next time you call `maximize`. This probing process happens before the gaussian process takes over. @@ -221,11 +215,11 @@ optimizer.maximize(init_points=0, n_iter=0) ================================================= -## 4. Saving, loading and restarting +### 4. Saving, loading and restarting By default you can follow the progress of your optimization by setting `verbose>0` when instantiating the `BayesianOptimization` object. If you need more control over logging/alerting you will need to use an observer. For more information about observers checkout the advanced tour notebook. Here we will only see how to use the native `JSONLogger` object to save to and load progress from files. -### 4.1 Saving progress +#### 4.1 Saving progress ```python @@ -255,7 +249,7 @@ optimizer.maximize( By default the previous data in the json file is removed. If you want to keep working with the same logger, the `reset` parameter in `JSONLogger` should be set to False. -### 4.2 Loading progress +#### 4.2 Loading progress Naturally, if you stored progress you will be able to load that onto a new instance of `BayesianOptimization`. The easiest way to do it is by invoking the `load_logs` function, from the `util` submodule. @@ -277,54 +271,51 @@ load_logs(new_optimizer, logs=["./logs.log"]); ## Next Steps -This introduction covered the most basic functionality of the package. Checkout the [basic-tour](https://github.com/fmfn/BayesianOptimization/blob/master/examples/basic-tour.ipynb) and [advanced-tour](https://github.com/fmfn/BayesianOptimization/blob/master/examples/advanced-tour.ipynb) notebooks in the example folder, where you will find detailed explanations and other more advanced functionality. Also, browse the examples folder for implementation tips and ideas. - -Installation -============ - -### Installation - -The latest release can be obtained by two ways: - -* With PyPI (pip): - - pip install bayesian-optimization - -* With conda (from conda-forge channel): - - conda install -c conda-forge bayesian-optimization - -The bleeding edge version can be installed with: - - pip install git+https://github.com/fmfn/BayesianOptimization.git +This introduction covered the most basic functionality of the package. Checkout the [basic-tour](http://bayesian-optimization.github.io/BayesianOptimization/basic-tour.html) and [advanced-tour](http://bayesian-optimization.github.io/BayesianOptimization/advanced-tour.html), where you will find detailed explanations and other more advanced functionality. Also, browse the [examples](http://bayesian-optimization.github.io/BayesianOptimization/examples.html) for implementation tips and ideas. -If you prefer, you can clone it and run the setup.py file. Use the following -commands to get a copy from Github and install all dependencies: +## Minutiae - git clone https://github.com/fmfn/BayesianOptimization.git - cd BayesianOptimization - python setup.py install +### Citation -Citation -============ - -If you used this package in your research and is interested in citing it here's how you do it: +If you used this package in your research, please cite it: ``` @Misc{, author = {Fernando Nogueira}, title = {{Bayesian Optimization}: Open source constrained global optimization tool for {Python}}, year = {2014--}, - url = " https://github.com/fmfn/BayesianOptimization" + url = " https://github.com/bayesian-optimization/BayesianOptimization" +} +``` +If you used any of the advanced functionalities, please additionally cite the corresponding publication: + +For the `SequentialDomainTransformer`: +``` +@article{ + author = {Stander, Nielen and Craig, Kenneth}, + year = {2002}, + month = {06}, + pages = {}, + title = {On the robustness of a simple domain reduction scheme for simulation-based optimization}, + volume = {19}, + journal = {International Journal for Computer-Aided Engineering and Software (Eng. Comput.)}, + doi = {10.1108/02644400210430190} +} +``` + +For constrained optimization: +``` +@inproceedings{gardner2014bayesian, + title={Bayesian optimization with inequality constraints.}, + author={Gardner, Jacob R and Kusner, Matt J and Xu, Zhixiang Eddie and Weinberger, Kilian Q and Cunningham, John P}, + booktitle={ICML}, + volume={2014}, + pages={937--945}, + year={2014} } ``` -# Dependencies -* Numpy -* Scipy -* Scikit-learn - -# References: +### References: * http://papers.nips.cc/paper/4522-practical-bayesian-optimization-of-machine-learning-algorithms.pdf * http://arxiv.org/pdf/1012.2599v1.pdf * http://www.gaussianprocess.org/gpml/ diff --git a/bayes_opt/__init__.py b/bayes_opt/__init__.py index 3c9d4791c..9e08d8a6a 100644 --- a/bayes_opt/__init__.py +++ b/bayes_opt/__init__.py @@ -1,8 +1,10 @@ +"""Pure Python implementation of bayesian global optimization with gaussian processes.""" from .bayesian_optimization import BayesianOptimization, Events from .domain_reduction import SequentialDomainReductionTransformer from .util import UtilityFunction from .logger import ScreenLogger, JSONLogger from .constraint import ConstraintModel +from .util import UtilityFunction __all__ = [ "BayesianOptimization", diff --git a/bayes_opt/bayesian_optimization.py b/bayes_opt/bayesian_optimization.py index df2000291..fe09f65a5 100644 --- a/bayes_opt/bayesian_optimization.py +++ b/bayes_opt/bayesian_optimization.py @@ -1,3 +1,8 @@ +"""Main module. + +Holds the `BayesianOptimization` class, which handles the maximization of a +function over a specific target space. +""" import warnings from bayes_opt.constraint import ConstraintModel @@ -12,17 +17,25 @@ class Queue: + """Queue datastructure. + + Append items in the end, remove items from the front. + """ + def __init__(self): self._queue = [] @property def empty(self): + """Check whether the queue holds any items.""" return len(self) == 0 def __len__(self): + """Return number of items in the Queue.""" return len(self._queue) def __next__(self): + """Remove and return first item in the Queue.""" if self.empty: raise StopIteration("Queue is empty, no more objects to retrieve.") obj = self._queue[0] @@ -35,11 +48,7 @@ def add(self, obj): class Observable(object): - """ - - Inspired/Taken from - https://www.protechtraining.com/blog/post/879#simple-observer - """ + """Inspired by https://www.protechtraining.com/blog/post/879#simple-observer.""" def __init__(self, events): # maps event names to subscribers @@ -47,23 +56,28 @@ def __init__(self, events): self._events = {event: dict() for event in events} def get_subscribers(self, event): + """Return the subscribers of an event.""" return self._events[event] def subscribe(self, event, subscriber, callback=None): + """Add subscriber to an event.""" if callback is None: callback = getattr(subscriber, 'update') self.get_subscribers(event)[subscriber] = callback def unsubscribe(self, event, subscriber): + """Remove a subscriber for a particular event.""" del self.get_subscribers(event)[subscriber] def dispatch(self, event): + """Trigger callbacks for subscribers of an event.""" for _, callback in self.get_subscribers(event).items(): callback(event, self) class BayesianOptimization(Observable): - """ + """Handle optimization of a target function over a specific target space. + This class takes the function to optimize as well as the parameters bounds in order to find which values for the parameters yield the maximum value using bayesian optimization. @@ -168,30 +182,53 @@ def __init__(self, @property def space(self): + """Return the target space associated with the optimizer.""" return self._space @property def constraint(self): + """Return the constraint associated with the optimizer, if any.""" if self.is_constrained: return self._space.constraint return None @property def max(self): + """Get maximum target value found and corresponding parameters. + + See `TargetSpace.max` for more information. + """ return self._space.max() @property def res(self): + """Get all target values and constraint fulfillment for all parameters. + + See `TargetSpace.res` for more information. + """ return self._space.res() def register(self, params, target, constraint_value=None): - """Expect observation with known target""" + """Register an observation with known target. + + Parameters + ---------- + params: dict or list + The parameters associated with the observation. + + target: float + Value of the target function at the observation. + + constraint_value: float or None + Value of the constraint function at the observation, if any. + """ self._space.register(params, target, constraint_value) self.dispatch(Events.OPTIMIZATION_STEP) def probe(self, params, lazy=True): - """ - Evaluates the function on the given points. Useful to guide the optimizer. + """Evaluate the function at the given points. + + Useful to guide the optimizer. Parameters ---------- @@ -202,7 +239,6 @@ def probe(self, params, lazy=True): If True, the optimizer will evaluate the points when calling maximize(). Otherwise it will evaluate it at the moment. """ - if lazy: self._queue.add(params) else: @@ -210,7 +246,14 @@ def probe(self, params, lazy=True): self.dispatch(Events.OPTIMIZATION_STEP) def suggest(self, utility_function): - """Most promising point to probe next""" + """Suggest a promising point to probe next. + + Parameters + ---------- + utility_function: + Surrogate function which suggests parameters to probe the target + function at. + """ if len(self._space) == 0: return self._space.array_to_params(self._space.random_sample()) @@ -230,12 +273,18 @@ def suggest(self, utility_function): y_max=self._space._target_max(), bounds=self._space.bounds, random_state=self._random_state, - y_max_params=self._space.params[self._space.target.argmax()]) + y_max_params=self._space.params_to_array(self._space.max()['params'])) return self._space.array_to_params(suggestion) def _prime_queue(self, init_points): - """Make sure there's something in the queue at the very beginning.""" + """Ensure the queue is not empty. + + Parameters + ---------- + init_points: int + Number of parameters to prime the queue with. + """ if self._queue.empty and self._space.empty: init_points = max(init_points, 1) @@ -259,10 +308,8 @@ def maximize(self, kappa_decay_delay=None, xi=None, **gp_params): - - """ - Probes the target space to find the parameters that yield the maximum - value for the given function. + r""" + Maximize the given function over the target space. Parameters ---------- @@ -278,8 +325,23 @@ def maximize(self, An instance of bayes_opt.util.UtilityFunction. If nothing is passed, a default using ucb is used - All other parameters are unused, and are only available to ensure backwards compatibility - these - will be removed in a future release + acq: + Deprecated, unused and slated for deletion. + + kappa: + Deprecated, unused and slated for deletion. + + kappa_decay: + Deprecated, unused and slated for deletion. + + kappa_decay_delay: + Deprecated, unused and slated for deletion. + + xi: + Deprecated, unused and slated for deletion. + + \*\*gp_params: + Deprecated, unused and slated for deletion. """ self._prime_subscriptions() self.dispatch(Events.OPTIMIZATION_START) @@ -320,8 +382,7 @@ def maximize(self, self.dispatch(Events.OPTIMIZATION_END) def set_bounds(self, new_bounds): - """ - A method that allows changing the lower and upper searching bounds + """Modify the bounds of the search space. Parameters ---------- @@ -331,5 +392,5 @@ def set_bounds(self, new_bounds): self._space.set_bounds(new_bounds) def set_gp_params(self, **params): - """Set parameters to the internal Gaussian Process Regressor""" + """Set parameters of the internal Gaussian Process Regressor.""" self._gp.set_params(**params) diff --git a/bayes_opt/constraint.py b/bayes_opt/constraint.py index a31142310..ec15d998c 100644 --- a/bayes_opt/constraint.py +++ b/bayes_opt/constraint.py @@ -1,3 +1,4 @@ +"""Constraint handling.""" import numpy as np from sklearn.gaussian_process.kernels import Matern from sklearn.gaussian_process import GaussianProcessRegressor @@ -5,32 +6,32 @@ class ConstraintModel(): - """ + """Model constraints using GP regressors. + This class takes the function to optimize as well as the parameters bounds in order to find which values for the parameters yield the maximum value using bayesian optimization. Parameters ---------- - fun: function - Constraint function. If multiple constraints are handled, this should - return a numpy.ndarray of appropriate size. + fun : None or Callable -> float or np.ndarray + The constraint function. Should be float-valued or array-valued (if + multiple constraints are present). Needs to take the same parameters + as the optimization target with the same argument names. - lb: numeric or numpy.ndarray - Upper limit(s) for the constraints. The return value of `fun` should - have exactly this shape. + lb : float or np.ndarray + The lower bound on the constraints. Should have the same + dimensionality as the return value of the constraint function. - ub: numeric or numpy.ndarray - Upper limit(s) for the constraints. The return value of `fun` should - have exactly this shape. + ub : float or np.ndarray + The upper bound on the constraints. Should have the same + dimensionality as the return value of the constraint function. - random_state: int or numpy.random.RandomState, optional(default=None) - If the value is an integer, it is used as the seed for creating a - numpy.random.RandomState. Otherwise the random state provided is used. - When set to None, an unseeded random state is generated. + random_state : np.random.RandomState or int or None, default=None + Random state to use. - Note - ---- + Notes + ----- In case of multiple constraints, this model assumes conditional independence. This means that for each constraint, the probability of fulfillment is the cdf of a univariate Gaussian. The overall probability @@ -40,7 +41,7 @@ class ConstraintModel(): def __init__(self, fun, lb, ub, random_state=None): self.fun = fun - self._lb = np.atleast_1d(lb) + self._lb = np.atleast_1d(lb) self._ub = np.atleast_1d(ub) if np.any(self._lb >= self._ub): @@ -58,19 +59,36 @@ def __init__(self, fun, lb, ub, random_state=None): @property def lb(self): + """Return lower bounds.""" return self._lb @property def ub(self): + """Return upper bounds.""" return self._ub - + @property def model(self): + """Return GP regressors of the constraint function.""" return self._model - def eval(self, **kwargs): - """ - Evaluates the constraint function. + def eval(self, **kwargs: dict): + r"""Evaluate the constraint function. + + Parameters + ---------- + \*\*kwargs : + Function arguments to evaluate the constraint function on. + + + Returns + ------- + Value of the constraint function. + + Raises + ------ + TypeError + If the kwargs' keys don't match the function argument names. """ try: return self.fun(**kwargs) @@ -85,8 +103,19 @@ def eval(self, **kwargs): raise def fit(self, X, Y): - """ - Fits internal GaussianProcessRegressor's to the data. + """Fit internal GPRs to the data. + + Parameters + ---------- + X : + Parameters of the constraint function. + Y : + Values of the constraint function. + + + Returns + ------- + None """ if len(self._model) == 1: self._model[0].fit(X, Y) @@ -95,13 +124,39 @@ def fit(self, X, Y): gp.fit(X, Y[:, i]) def predict(self, X): - """ - Returns the probability that the constraint is fulfilled at `X` based - on the internal Gaussian Process Regressors. + r"""Calculate the probability that the constraint is fulfilled at `X`. + + Note that this does not try to approximate the values of the + constraint function (for this, see `ConstraintModel.approx()`.), but + probability that the constraint function is fulfilled. That is, this + function calculates + + .. math:: + p = \text{Pr}\left\{c^{\text{low}} \leq \tilde{c}(x) \leq + c^{\text{up}} \right\} = \int_{c^{\text{low}}}^{c^{\text{up}}} + \mathcal{N}(c, \mu(x), \sigma^2(x)) \, dc. + + with :math:`\mu(x)`, :math:`\sigma^2(x)` the mean and variance at + :math:`x` as given by the GP and :math:`c^{\text{low}}`, + :math:`c^{\text{up}}` the lower and upper bounds of the constraint + respectively. + + In case of multiple constraints, we assume conditional independence. + This means we calculate the probability of constraint fulfilment + individually, with the joint probability given as their product. + + Parameters + ---------- + X : np.ndarray of shape (n_samples, n_features) + Parameters for which to predict the probability of constraint + fulfilment. + + + Returns + ------- + np.ndarray of shape (n_samples,) + Probability of constraint fulfilment. - Note that this does not try to approximate the values of the constraint - function, but probability that the constraint function is fulfilled. - For the former, see `ConstraintModel.approx()`. """ X_shape = X.shape X = X.reshape((-1, self._model[0].n_features_in_)) @@ -114,33 +169,53 @@ def predict(self, X): if self._lb[0] != np.inf else np.array([1])) result = p_upper - p_lower return result.reshape(X_shape[:-1]) - else: - result = np.ones(X.shape[0]) - for j, gp in enumerate(self._model): - y_mean, y_std = gp.predict(X, return_std=True) - p_lower = (norm(loc=y_mean, scale=y_std).cdf(self._lb[j]) - if self._lb[j] != -np.inf else np.array([0])) - p_upper = (norm(loc=y_mean, scale=y_std).cdf(self._ub[j]) - if self._lb[j] != np.inf else np.array([1])) - result = result * (p_upper - p_lower) - return result.reshape(X_shape[:-1]) + + result = np.ones(X.shape[0]) + for j, gp in enumerate(self._model): + y_mean, y_std = gp.predict(X, return_std=True) + p_lower = (norm(loc=y_mean, scale=y_std).cdf(self._lb[j]) + if self._lb[j] != -np.inf else np.array([0])) + p_upper = (norm(loc=y_mean, scale=y_std).cdf(self._ub[j]) + if self._lb[j] != np.inf else np.array([1])) + result = result * (p_upper - p_lower) + return result.reshape(X_shape[:-1]) def approx(self, X): """ - Returns the approximation of the constraint function using the internal - Gaussian Process Regressors. + Approximate the constraint function using the internal GPR model. + + Parameters + ---------- + X : np.ndarray of shape (n_samples, n_features) + Parameters for which to estimate the constraint function value. + + Returns + ------- + np.ndarray of shape (n_samples, n_constraints) + Constraint function value estimates. """ X_shape = X.shape X = X.reshape((-1, self._model[0].n_features_in_)) if len(self._model) == 1: return self._model[0].predict(X).reshape(X_shape[:-1]) - else: - result = np.column_stack([gp.predict(X) for gp in self._model]) - return result.reshape(X_shape[:-1] + (len(self._lb), )) + + result = np.column_stack([gp.predict(X) for gp in self._model]) + return result.reshape(X_shape[:-1] + (len(self._lb), )) def allowed(self, constraint_values): - """ - Checks whether `constraint_values` are below the specified limits. + """Check whether `constraint_values` fulfills the specified limits. + + Parameters + ---------- + constraint_values : np.ndarray of shape (n_samples, n_constraints) + The values of the constraint function. + + + Returns + ------- + np.ndarrray of shape (n_samples,) + Specifying wheter the constraints are fulfilled. + """ if self._lb.size == 1: return (np.less_equal(self._lb, constraint_values) diff --git a/bayes_opt/domain_reduction.py b/bayes_opt/domain_reduction.py index 5134f5465..d48a70d7a 100644 --- a/bayes_opt/domain_reduction.py +++ b/bayes_opt/domain_reduction.py @@ -1,3 +1,9 @@ +"""Implement domain transformation. + +In particular, this provides a base transformer class and a sequential domain +reduction transformer as based on Stander and Craig's "On the robustness of a +simple domain reduction scheme for simulation-based optimization" +""" from typing import Optional, Union, List, Dict import numpy as np @@ -6,22 +12,40 @@ class DomainTransformer(): - '''The base transformer class''' + """Base class.""" - def __init__(self, **kwargs): + def __init__(self, **kwargs) -> None: + """To override with specific implementation.""" pass - def initialize(self, target_space: TargetSpace): + def initialize(self, target_space: TargetSpace) -> None: + """To override with specific implementation.""" raise NotImplementedError - def transform(self, target_space: TargetSpace): + def transform(self, target_space: TargetSpace) -> dict: + """To override with specific implementation.""" raise NotImplementedError class SequentialDomainReductionTransformer(DomainTransformer): - """ + """Reduce the searchable space. + A sequential domain reduction transformer based on the work by Stander, N. and Craig, K: - "On the robustness of a simple domain reduction scheme for simulation‐based optimization" + "On the robustness of a simple domain reduction scheme for simulation-based optimization" + + Parameters + ---------- + gamma_osc : float, default=0.7 + Parameter used to scale (typically dampen) oscillations. + + gamma_pan : float, default=1.0 + Parameter used to scale (typically unitary) panning. + + eta : float, default=0.9 + 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. """ def __init__( @@ -42,8 +66,12 @@ def __init__( def initialize(self, target_space: TargetSpace) -> None: """Initialize all of the parameters. + + Parameters + ---------- + target_space : TargetSpace + TargetSpace this DomainTransformer operates on. """ - # Set the original bounds self.original_bounds = np.copy(target_space.bounds) self.bounds = [self.original_bounds] @@ -81,7 +109,12 @@ def initialize(self, target_space: TargetSpace) -> None: self._window_bounds_compatibility(self.original_bounds) def _update(self, target_space: TargetSpace) -> None: - """ Updates contraction rate, window size, and window center. + """Update contraction rate, window size, and window center. + + Parameters + ---------- + target_space : TargetSpace + TargetSpace this DomainTransformer operates on. """ # setting the previous self.previous_optimal = self.current_optimal @@ -104,24 +137,23 @@ def _update(self, target_space: TargetSpace) -> None: self.r = self.contraction_rate * self.r - def _trim(self, new_bounds: np.array, global_bounds: np.array) -> np.array: + def _trim(self, new_bounds: np.ndarray, global_bounds: np.ndarray) -> np.ndarray: """ Adjust the new_bounds and verify that they adhere to global_bounds and minimum_window. - Parameters: - ----------- - new_bounds : np.array + Parameters + ---------- + new_bounds : np.ndarray The proposed new_bounds that (may) need adjustment. - global_bounds : np.array + global_bounds : np.ndarray The maximum allowable bounds for each parameter. - Returns: - -------- - new_bounds : np.array + Returns + ------- + new_bounds : np.ndarray The adjusted bounds after enforcing constraints. """ - #sort bounds new_bounds = np.sort(new_bounds) @@ -180,8 +212,18 @@ def _trim(self, new_bounds: np.array, global_bounds: np.array) -> np.array: return new_bounds - def _window_bounds_compatibility(self, global_bounds: np.array) -> bool: - """Checks if global bounds are compatible with the minimum window sizes. + def _window_bounds_compatibility(self, global_bounds: np.ndarray): + """Check if global bounds are compatible with the minimum window sizes. + + Parameters + ---------- + global_bounds : np.ndarray + The maximum allowable bounds for each parameter. + + Raises + ------ + ValueError + If global bounds are not compatible with the minimum window size. """ for i, entry in enumerate(global_bounds): global_window_width = abs(entry[1] - entry[0]) @@ -189,11 +231,31 @@ def _window_bounds_compatibility(self, global_bounds: np.array) -> bool: raise ValueError( "Global bounds are not compatible with the minimum window size.") - def _create_bounds(self, parameters: dict, bounds: np.array) -> dict: + def _create_bounds(self, parameters: dict, bounds: np.ndarray) -> dict: + """Create a dictionary of bounds for each parameter. + + Parameters + ---------- + parameters : dict + The parameters for which to create the bounds. + + bounds : np.ndarray + The bounds for each parameter. + """ return {param: bounds[i, :] for i, param in enumerate(parameters)} def transform(self, target_space: TargetSpace) -> dict: - """Reduces the bounds of the target space. + """Transform the bounds of the target space. + + Parameters + ---------- + target_space : TargetSpace + TargetSpace this DomainTransformer operates on. + + Returns + ------- + dict + The new bounds of each parameter. """ self._update(target_space) diff --git a/bayes_opt/event.py b/bayes_opt/event.py index d5dfdd10e..374534343 100644 --- a/bayes_opt/event.py +++ b/bayes_opt/event.py @@ -1,4 +1,11 @@ +"""Register optimization events variables.""" + class Events: + """Define optimization events. + + Behaves similar to enums. + """ + OPTIMIZATION_START = 'optimization:start' OPTIMIZATION_STEP = 'optimization:step' OPTIMIZATION_END = 'optimization:end' diff --git a/bayes_opt/logger.py b/bayes_opt/logger.py index edcfa836c..84182c184 100644 --- a/bayes_opt/logger.py +++ b/bayes_opt/logger.py @@ -1,17 +1,48 @@ +"""Contains classes and functions for logging.""" from __future__ import print_function import os import json -import warnings -from pathlib import Path from .observer import _Tracker from .event import Events -from .util import Colours +from colorama import Fore, just_fix_windows_console + +just_fix_windows_console() def _get_default_logger(verbose, is_constrained): + """ + Return the default logger. + + Parameters + ---------- + verbose : int + Verbosity level of the logger. + + is_constrained : bool + Whether the underlying optimizer uses constraints (this requires + an additional column in the output). + + Returns + ------- + ScreenLogger + The default logger. + + """ return ScreenLogger(verbose=verbose, is_constrained=is_constrained) class ScreenLogger(_Tracker): + """Logger that outputs text, e.g. to log to a terminal. + + Parameters + ---------- + verbose : int + Verbosity level of the logger. + + is_constrained : bool + Whether the logger is associated with a constrained optimization + instance. + """ + _default_cell_size = 9 _default_precision = 4 @@ -19,64 +50,106 @@ def __init__(self, verbose=2, is_constrained=False): self._verbose = verbose self._is_constrained = is_constrained self._header_length = None - super(ScreenLogger, self).__init__() + super().__init__() @property def verbose(self): + """Return the verbosity level.""" return self._verbose @verbose.setter def verbose(self, v): + """Set the verbosity level. + + Parameters + ---------- + v : int + New verbosity level of the logger. + """ self._verbose = v @property def is_constrained(self): + """Return whether the logger is constrained.""" return self._is_constrained def _format_number(self, x): + """Format a number. + + Parameters + ---------- + x : number + Value to format. + + Returns + ------- + A stringified, formatted version of `x`. + """ if isinstance(x, int): - s = "{x:<{s}}".format( - x=x, - s=self._default_cell_size, - ) + s = f"{x:<{self._default_cell_size}}" else: - s = "{x:<{s}.{p}}".format( - x=x, - s=self._default_cell_size, - p=self._default_precision, - ) + s = f"{x:<{self._default_cell_size}.{self._default_precision}}" if len(s) > self._default_cell_size: if "." in s: return s[:self._default_cell_size] - else: - return s[:self._default_cell_size - 3] + "..." + return s[:self._default_cell_size - 3] + "..." return s def _format_bool(self, x): + """Format a boolean. + + Parameters + ---------- + x : boolean + Value to format. + + Returns + ------- + A stringified, formatted version of `x`. + """ if 5 > self._default_cell_size: - if x == True: + if x: x_ = 'T' - elif x == False: + else: x_ = 'F' else: x_ = str(x) - s = "{x:<{s}}".format( - x=x_, - s=self._default_cell_size, - ) + s = f"{x_:<{self._default_cell_size}}" return s def _format_key(self, key): - s = "{key:^{s}}".format( - key=key, - s=self._default_cell_size - ) + """Format a key. + + Parameters + ---------- + key : string + Value to format. + + Returns + ------- + A stringified, formatted version of `x`. + """ + s = f"{key:^{self._default_cell_size}}" if len(s) > self._default_cell_size: return s[:self._default_cell_size - 3] + "..." return s - def _step(self, instance, colour=Colours.black): + def _step(self, instance, colour=Fore.BLACK): + """Log a step. + + Parameters + ---------- + instance : bayesian_optimization.BayesianOptimization + The instance associated with the event. + + colour : + (Default value = Fore.BLACK) + + Returns + ------- + A stringified, formatted version of the most recent optimization step. + """ res = instance.res[-1] cells = [] @@ -89,9 +162,20 @@ def _step(self, instance, colour=Colours.black): for key in instance.space.keys: cells.append(self._format_number(res["params"][key])) - return "| " + " | ".join(map(colour, cells)) + " |" + return "| " + " | ".join([colour + cells[i] for i in range(len(cells))]) + " |" def _header(self, instance): + """Print the header of the log. + + Parameters + ---------- + instance : bayesian_optimization.BayesianOptimization + The instance associated with the header. + + Returns + ------- + A stringified, formatted version of the most header. + """ cells = [] cells.append(self._format_key("iter")) cells.append(self._format_key("target")) @@ -107,6 +191,17 @@ def _header(self, instance): return line + "\n" + ("-" * self._header_length) def _is_new_max(self, instance): + """Check if the step to log produced a new maximum. + + Parameters + ---------- + instance : bayesian_optimization.BayesianOptimization + The instance associated with the step. + + Returns + ------- + boolean + """ if instance.max is None: # During constrained optimization, there might not be a maximum # value since the optimizer might've not encountered any points @@ -117,6 +212,17 @@ def _is_new_max(self, instance): return instance.max["target"] > self._previous_max def update(self, event, instance): + """Handle incoming events. + + Parameters + ---------- + event : str + One of the values associated with `Events.OPTIMIZATION_START`, + `Events.OPTIMIZATION_STEP` or `Events.OPTIMIZATION_END`. + + instance : bayesian_optimization.BayesianOptimization + The instance associated with the step. + """ if event == Events.OPTIMIZATION_START: line = self._header(instance) + "\n" elif event == Events.OPTIMIZATION_STEP: @@ -124,7 +230,7 @@ def update(self, event, instance): if self._verbose == 1 and not is_new_max: line = "" else: - colour = Colours.purple if is_new_max else Colours.black + colour = Fore.MAGENTA if is_new_max else Fore.BLACK line = self._step(instance, colour=colour) + "\n" elif event == Events.OPTIMIZATION_END: line = "=" * self._header_length + "\n" @@ -135,18 +241,44 @@ def update(self, event, instance): class JSONLogger(_Tracker): - def __init__(self, path, reset=True): + """ + Logger that outputs steps in JSON format. + + The resulting file can be used to restart the optimization from an earlier state. + + Parameters + ---------- + path : str or bytes or os.PathLike + Path to the file to write to. + reset : bool + Whether to overwrite the file if it already exists. + """ + + def __init__(self, path, reset=True): self._path = path if reset: try: os.remove(self._path) except OSError: pass - super(JSONLogger, self).__init__() + super().__init__() def update(self, event, instance): + """ + Handle incoming events. + + Parameters + ---------- + event : str + One of the values associated with `Events.OPTIMIZATION_START`, + `Events.OPTIMIZATION_STEP` or `Events.OPTIMIZATION_END`. + + instance : bayesian_optimization.BayesianOptimization + The instance associated with the step. + + """ if event == Events.OPTIMIZATION_STEP: data = dict(instance.res[-1]) diff --git a/bayes_opt/observer.py b/bayes_opt/observer.py index 5a6ac16b2..910b8c370 100644 --- a/bayes_opt/observer.py +++ b/bayes_opt/observer.py @@ -1,16 +1,11 @@ -""" -observers... -""" +"""Holds the parent class for loggers.""" from datetime import datetime from .event import Events -class Observer: - def update(self, event, instance): - raise NotImplementedError - - class _Tracker(object): + """Parent class for ScreenLogger and JSONLogger.""" + def __init__(self): self._iterations = 0 @@ -21,6 +16,17 @@ def __init__(self): self._previous_time = None def _update_tracker(self, event, instance): + """Update the tracker. + + Parameters + ---------- + event : str + One of the values associated with `Events.OPTIMIZATION_START`, + `Events.OPTIMIZATION_STEP` or `Events.OPTIMIZATION_END`. + + instance : bayesian_optimization.BayesianOptimization + The instance associated with the step. + """ if event == Events.OPTIMIZATION_STEP: self._iterations += 1 @@ -35,6 +41,7 @@ def _update_tracker(self, event, instance): self._previous_max_params = current_max["params"] def _time_metrics(self): + """Return time passed since last call.""" now = datetime.now() if self._start_time is None: self._start_time = now diff --git a/bayes_opt/target_space.py b/bayes_opt/target_space.py index 534932f2e..89f523dfc 100644 --- a/bayes_opt/target_space.py +++ b/bayes_opt/target_space.py @@ -1,21 +1,40 @@ +"""Manages the optimization domain and holds points.""" import numpy as np +from colorama import Fore from warnings import warn from .util import ensure_rng, NotUniqueError -from .util import Colours def _hashable(x): - """ ensure that an point is hashable by a python dict """ + """Ensure that a point is hashable by a python dict.""" return tuple(map(float, x)) -class TargetSpace(object): - """ - Holds the param-space coordinates (X) and target values (Y) - Allows for constant-time appends while ensuring no duplicates are added +class TargetSpace(): + """Holds the param-space coordinates (X) and target values (Y). + + Allows for constant-time appends. + + Parameters + ---------- + target_func : function + Function to be maximized. + + pbounds : dict + Dictionary with parameters names as keys and a tuple with minimum + and maximum values. - Example - ------- + random_state : int, RandomState, or None + optionally specify a seed for a random number generator + + allow_duplicate_points: bool, optional (default=False) + If True, the optimizer will allow duplicate points to be registered. + This behavior may be desired in high noise situations where repeatedly probing + the same point will give different answers. In other situations, the acquisition + may occasionally generate a duplicate point. + + Examples + -------- >>> def target_func(p1, p2): >>> return p1 + p2 >>> pbounds = {'p1': (0, 1), 'p2': (1, 100)} @@ -29,25 +48,6 @@ class TargetSpace(object): def __init__(self, target_func, pbounds, constraint=None, random_state=None, allow_duplicate_points=False): - """ - Parameters - ---------- - target_func : function - Function to be maximized. - - pbounds : dict - Dictionary with parameters names as keys and a tuple with minimum - and maximum values. - - random_state : int, RandomState, or None - optionally specify a seed for a random number generator - - allow_duplicate_points: bool, optional (default=False) - If True, the optimizer will allow duplicate points to be registered. - This behavior may be desired in high noise situations where repeatedly probing - the same point will give different answers. In other situations, the acquisition - may occasionally generate a duplicate point. - """ self.random_state = ensure_rng(random_state) self._allow_duplicate_points = allow_duplicate_points self.n_duplicate_points = 0 @@ -65,7 +65,7 @@ def __init__(self, target_func, pbounds, constraint=None, random_state=None, # preallocated memory for X and Y points self._params = np.empty(shape=(0, self.dim)) - self._target = np.empty(shape=(0)) + self._target = np.empty(shape=(0,)) # keep track of unique points we have seen so far self._cache = {} @@ -80,48 +80,117 @@ def __init__(self, target_func, pbounds, constraint=None, random_state=None, self._constraint_values = np.empty(shape=(0, constraint.lb.size), dtype=float) def __contains__(self, x): + """Check if this parameter has already been registered. + + Returns + ------- + bool + """ return _hashable(x) in self._cache def __len__(self): + """Return number of observations registered. + + Returns + ------- + int + """ assert len(self._params) == len(self._target) return len(self._target) @property def empty(self): + """Check if anything has been registered. + + Returns + ------- + bool + """ return len(self) == 0 @property def params(self): + """Get the parameter values registered to this TargetSpace. + + Returns + ------- + np.ndarray + """ return self._params @property def target(self): + """Get the target function values registered to this TargetSpace. + + Returns + ------- + np.ndarray + """ return self._target @property def dim(self): + """Get the number of parameter names. + + Returns + ------- + int + """ return len(self._keys) @property def keys(self): + """Get the keys (or parameter names). + + Returns + ------- + list of str + """ return self._keys @property def bounds(self): + """Get the bounds of this TargetSpace. + + Returns + ------- + np.ndarray + """ return self._bounds @property def constraint(self): + """Get the constraint model. + + Returns + ------- + ConstraintModel + """ return self._constraint @property def constraint_values(self): - if self._constraint is not None: - return self._constraint_values + """Get the constraint values registered to this TargetSpace. + + Returns + ------- + np.ndarray + """ + if self._constraint is None: + raise AttributeError("TargetSpace belongs to an unconstrained optimization") + + return self._constraint_values @property def mask(self): - '''Returns a boolean array of the points that satisfy the constraint and boundary conditions''' + """Return a boolean array of valid points. + + Points are valid if they satisfy both the constraint and boundary conditions. + + Returns + ------- + np.ndarray + """ mask = np.ones_like(self.target, dtype=bool) # mask points that don't satisfy the constraint @@ -136,23 +205,44 @@ def mask(self): return mask + def params_to_array(self, params): - try: - assert set(params) == set(self.keys) - except AssertionError: + """Convert a dict representation of parameters into an array version. + + Parameters + ---------- + params : dict + a single point, with len(x) == self.dim. + + Returns + ------- + np.ndarray + Representation of the parameters as an array. + """ + if not set(params) == set(self.keys): raise ValueError( - "Parameters' keys ({}) do ".format(sorted(params)) + - "not match the expected set of keys ({}).".format(self.keys) + f"Parameters' keys ({sorted(params)}) do " + + f"not match the expected set of keys ({self.keys})." ) return np.asarray([params[key] for key in self.keys]) def array_to_params(self, x): - try: - assert len(x) == len(self.keys) - except AssertionError: + """Convert an array representation of parameters into a dict version. + + Parameters + ---------- + x : np.ndarray + a single point, with len(x) == self.dim. + + Returns + ------- + dict + Representation of the parameters as dictionary. + """ + if not len(x) == len(self.keys): raise ValueError( - "Size of array ({}) is different than the ".format(len(x)) + - "expected number of parameters ({}).".format(len(self.keys)) + f"Size of array ({len(x)}) is different than the " + + f"expected number of parameters ({len(self.keys)})." ) return dict(zip(self.keys, x)) @@ -163,37 +253,38 @@ def _as_array(self, x): x = self.params_to_array(x) x = x.ravel() - try: - assert x.size == self.dim - except AssertionError: + if not x.size == self.dim: raise ValueError( - "Size of array ({}) is different than the ".format(len(x)) + - "expected number of parameters ({}).".format(len(self.keys))) + f"Size of array ({len(x)}) is different than the " + + f"expected number of parameters ({len(self.keys)})." + ) return x def register(self, params, target, constraint_value=None): - """ - Append a point and its target value to the known data. + """Append a point and its target value to the known data. Parameters ---------- - x : ndarray - a single point, with len(x) == self.dim + params : np.ndarray + a single point, with len(x) == self.dim. - y : float + target : float target function value + constraint_value : float or None + Constraint function value + Raises ------ - KeyError: + NotUniqueError: if the point is not unique Notes ----- runs in amortized constant time - Example - ------- + Examples + -------- >>> target_func = lambda p1, p2: p1 + p2 >>> pbounds = {'p1': (0, 1), 'p2': (1, 100)} >>> space = TargetSpace(target_func, pbounds) @@ -209,11 +300,12 @@ def register(self, params, target, constraint_value=None): if x in self: if self._allow_duplicate_points: self.n_duplicate_points = self.n_duplicate_points + 1 - print(f'{Colours.RED}Data point {x} is not unique. {self.n_duplicate_points} duplicates registered.' - f' Continuing ...{Colours.END}') + + print(Fore.RED + f'Data point {x} is not unique. {self.n_duplicate_points}' + ' duplicates registered. Continuing ...') else: - raise NotUniqueError(f'Data point {x} is not unique. You can set "allow_duplicate_points=True" to ' - f'avoid this error') + raise NotUniqueError(f'Data point {x} is not unique. You can set' + ' "allow_duplicate_points=True" to avoid this error') # if x is not within the bounds of the parameter space, warn the user if self._bounds is not None: @@ -237,23 +329,22 @@ def register(self, params, target, constraint_value=None): [constraint_value]]) def probe(self, params): - """ - Evaluates a single point x, to obtain the value y and then registers the - point and its evaluation. + """Evaluate the target function on a point and register the result. Notes ----- - If x has been previously seen returns a cached value of y. + If `params` has been previously seen and duplicate points are not allowed, + returns a cached value of `result`. Parameters ---------- - x : ndarray + params : np.ndarray a single point, with len(x) == self.dim Returns ------- - y : float - target function value. + result : float | Tuple(float, float) + target function value, or Tuple(target function value, constraint value) Example ------- @@ -265,28 +356,32 @@ def probe(self, params): >>> assert self.max()['params'] == {'p1': 1.0, 'p2': 5.0} """ x = self._as_array(params) + if x in self: + if not self._allow_duplicate_points: + return self._cache[_hashable(x.ravel())] + params = dict(zip(self._keys, x)) target = self.target_func(**params) if self._constraint is None: self.register(x, target) return target - else: - constraint_value = self._constraint.eval(**params) - self.register(x, target, constraint_value) - return target, constraint_value + + constraint_value = self._constraint.eval(**params) + self.register(x, target, constraint_value) + return target, constraint_value def random_sample(self): """ - Creates a random point within the bounds of the space. + Sample a random point from within the bounds of the space. Returns - ---------- + ------- data: ndarray [1 x dim] array with dimensions corresponding to `self._keys` - Example - ------- + Examples + -------- >>> target_func = lambda p1, p2: p1 + p2 >>> pbounds = {'p1': (0, 1), 'p2': (1, 100)} >>> space = TargetSpace(target_func, pbounds, random_state=0) @@ -305,10 +400,9 @@ def _target_max(self): constraint within the parameter bounds is returned. Returns - ---------- + ------- max: float The maximum target value. - """ if len(self.target) == 0: return None @@ -319,20 +413,18 @@ def _target_max(self): return self.target[self.mask].max() def max(self): - """Get the maximum target value within the current parameter bounds, - and its associated parameters. + """Get maximum target value found and corresponding parameters. If there is a constraint present, the maximum value that fulfills the constraint within the parameter bounds is returned. Returns - ---------- + ------- res: dict A dictionary with the keys 'target' and 'params'. The value of 'target' is the maximum target value, and the value of 'params' is a dictionary with the parameter names as keys and the parameter values as values. - """ target_max = self._target_max() if target_max is None: @@ -359,7 +451,7 @@ def res(self): """Get all target values and constraint fulfillment for all parameters. Returns - ---------- + ------- res: list A list of dictionaries with the keys 'target', 'params', and 'constraint'. The value of 'target' is the target value, the value @@ -370,9 +462,7 @@ def res(self): Notes ----- Does not report if points are within the bounds of the parameter space. - """ - if self._constraint is None: params = [dict(zip(self.keys, p)) for p in self.params] @@ -380,27 +470,26 @@ def res(self): {"target": target, "params": param} for target, param in zip(self.target, params) ] - else: - params = [dict(zip(self.keys, p)) for p in self.params] - return [ - { - "target": target, - "constraint": constraint_value, - "params": param, - "allowed": allowed - } - for target, constraint_value, param, allowed in zip( - self.target, - self._constraint_values, - params, - self._constraint.allowed(self._constraint_values) - ) - ] + params = [dict(zip(self.keys, p)) for p in self.params] + + return [ + { + "target": target, + "constraint": constraint_value, + "params": param, + "allowed": allowed + } + for target, constraint_value, param, allowed in zip( + self.target, + self._constraint_values, + params, + self._constraint.allowed(self._constraint_values) + ) + ] def set_bounds(self, new_bounds): - """ - A method that allows changing the lower and upper searching bounds + """Change the lower and upper search bounds. Parameters ---------- diff --git a/bayes_opt/util.py b/bayes_opt/util.py index 48d8f3c17..9a2a82ea4 100644 --- a/bayes_opt/util.py +++ b/bayes_opt/util.py @@ -1,14 +1,13 @@ +"""Contains utility functions.""" +import json import warnings import numpy as np from scipy.stats import norm from scipy.optimize import minimize -from colorama import just_fix_windows_console -import json def acq_max(ac, gp, y_max, bounds, random_state, constraint=None, n_warmup=10000, n_iter=10, y_max_params=None): - """ - A function to find the maximum of the acquisition function + """Find the maximum of the acquisition function. It uses a combination of random sampling (cheap) and the 'L-BFGS-B' optimization method. First by sampling `n_warmup` (1e5) points at random, @@ -16,43 +15,63 @@ def acq_max(ac, gp, y_max, bounds, random_state, constraint=None, n_warmup=10000 Parameters ---------- - :param ac: - The acquisition function object that return its point-wise value. - - :param gp: - A gaussian process fitted to the relevant data. - - :param y_max: - The current maximum known value of the target function. - - :param bounds: - The variables bounds to limit the search of the acq max. - - :param random_state: - instance of np.RandomState random number generator - - :param constraint: - A ConstraintModel. - - :param n_warmup: - number of times to randomly sample the acquisition function - - :param n_iter: - number of times to run scipy.minimize + ac : callable + Acquisition function to use. Should accept an array of parameters `x`, + an from sklearn.gaussian_process.GaussianProcessRegressor `gp` and the + best current value `y_max` as parameters. + + gp : sklearn.gaussian_process.GaussianProcessRegressor + A gaussian process regressor modelling the target function based on + previous observations. + + y_max : number + Highest found value of the target function. + + bounds : np.ndarray + Bounds of the search space. For `N` parameters this has shape + `(N, 2)` with `[i, 0]` the lower bound of parameter `i` and + `[i, 1]` the upper bound. + + random_state : np.random.RandomState + A random state to sample from. + + constraint : ConstraintModel or None, default=None + If provided, the acquisition function will be adjusted according + to the probability of fulfilling the constraint. + + n_warmup : int, default=10000 + Number of points to sample from the acquisition function as seeds + before looking for a minimum. + + n_iter : int, default=10 + Points to run L-BFGS-B optimization from. + + y_max_params : np.array + Function parameters that produced the maximum known value given by `y_max`. :param y_max_params: Function parameters that produced the maximum known value given by `y_max`. Returns ------- - :return: x_max, The arg max of the acquisition function. - """ + Parameters maximizing the acquisition function. + """ # We need to adjust the acquisition function to deal with constraints when there is some if constraint is not None: def adjusted_ac(x): - """Acquisition function adjusted to fulfill the constraint when necessary""" + """Acquisition function adjusted to fulfill the constraint when necessary. + Parameters + ---------- + x : np.ndarray + Parameter at which to sample. + + + Returns + ------- + The value of the acquisition function adjusted for constraints. + """ # Transforms the problem in a minimization problem, this is necessary # because the solver we are using later on is a minimizer values = -ac(x.reshape(-1, bounds.shape[0]), gp=gp, y_max=y_max) @@ -121,33 +140,33 @@ def adjusted_ac(x): return np.clip(x_max, bounds[:, 0], bounds[:, 1]) -class UtilityFunction(object): - """ - An object to compute the acquisition functions. - +class UtilityFunction(): + """An object to compute the acquisition functions. + + Parameters + ---------- kind: {'ucb', 'ei', 'poi'} * 'ucb' stands for the Upper Confidence Bounds method * 'ei' is the Expected Improvement method * 'poi' is the Probability Of Improvement criterion. - + kappa: float, optional(default=2.576) Parameter to indicate how closed are the next parameters sampled. Higher value = favors spaces that are least explored. Lower value = favors spaces where the regression function is the highest. - + kappa_decay: float, optional(default=1) `kappa` is multiplied by this factor every iteration. - + kappa_decay_delay: int, optional(default=0) Number of iterations that must have passed before applying the decay to `kappa`. - + xi: float, optional(default=0.0) """ def __init__(self, kind='ucb', kappa=2.576, xi=0, kappa_decay=1, kappa_decay_delay=0): - self.kappa = kappa self._kappa_decay = kappa_decay self._kappa_decay_delay = kappa_decay_delay @@ -158,28 +177,81 @@ def __init__(self, kind='ucb', kappa=2.576, xi=0, kappa_decay=1, kappa_decay_del if kind not in ['ucb', 'ei', 'poi']: err = "The utility function " \ - "{} has not been implemented, " \ - "please choose one of ucb, ei, or poi.".format(kind) + f"{kind} has not been implemented, " \ + "please choose one of ucb, ei, or poi." raise NotImplementedError(err) - else: - self.kind = kind + self.kind = kind def update_params(self): + """Update internal parameters.""" self._iters_counter += 1 if self._kappa_decay < 1 and self._iters_counter > self._kappa_decay_delay: self.kappa *= self._kappa_decay def utility(self, x, gp, y_max): + """Calculate acquisition function. + + Parameters + ---------- + x : np.ndarray + Parameters to evaluate the function at. + + gp : sklearn.gaussian_process.GaussianProcessRegressor + A gaussian process regressor modelling the target function based on + previous observations. + + y_max : number + Highest found value of the target function. + + + Returns + ------- + Values of the acquisition function + """ if self.kind == 'ucb': - return self._ucb(x, gp, self.kappa) + return self.ucb(x, gp, self.kappa) if self.kind == 'ei': - return self._ei(x, gp, y_max, self.xi) + return self.ei(x, gp, y_max, self.xi) if self.kind == 'poi': - return self._poi(x, gp, y_max, self.xi) + return self.poi(x, gp, y_max, self.xi) + raise ValueError(f"{self.kind} is not a valid acquisition function.") @staticmethod - def _ucb(x, gp, kappa): + def ucb(x, gp, kappa): + r"""Calculate Upper Confidence Bound acquisition function. + + Similar to Probability of Improvement (`UtilityFunction.poi`), but also considers the + magnitude of improvement. + Calculated as + + .. math:: + \text{UCB}(x) = \mu(x) + \kappa \sigma(x) + + where :math:`\Phi` is the CDF and :math:`\phi` the PDF of the normal + distribution. + + Parameters + ---------- + x : np.ndarray + Parameters to evaluate the function at. + + gp : sklearn.gaussian_process.GaussianProcessRegressor + A gaussian process regressor modelling the target function based on + previous observations. + + y_max : number + Highest found value of the target function. + + kappa : float, positive + Governs the exploration/exploitation tradeoff. Lower prefers + exploitation, higher prefers exploration. + + + Returns + ------- + Values of the acquisition function + """ with warnings.catch_warnings(): warnings.simplefilter("ignore") mean, std = gp.predict(x, return_std=True) @@ -187,17 +259,82 @@ def _ucb(x, gp, kappa): return mean + kappa * std @staticmethod - def _ei(x, gp, y_max, xi): + def ei(x, gp, y_max, xi): + r"""Calculate Expected Improvement acqusition function. + + Similar to Probability of Improvement (`UtilityFunction.poi`), but also considers the + magnitude of improvement. + Calculated as + + .. math:: + \text{EI}(x) = (\mu(x)-y_{\text{max}} - \xi) \Phi\left( + \frac{\mu(x)-y_{\text{max}} - \xi }{\sigma(x)} \right) + + \sigma(x) \phi\left( + \frac{\mu(x)-y_{\text{max}} - \xi }{\sigma(x)} \right) + + where :math:`\Phi` is the CDF and :math:`\phi` the PDF of the normal + distribution. + + Parameters + ---------- + x : np.ndarray + Parameters to evaluate the function at. + + gp : sklearn.gaussian_process.GaussianProcessRegressor + A gaussian process regressor modelling the target function based on + previous observations. + + y_max : number + Highest found value of the target function. + + xi : float, positive + Governs the exploration/exploitation tradeoff. Lower prefers + exploitation, higher prefers exploration. + + + Returns + ------- + Values of the acquisition function + """ with warnings.catch_warnings(): warnings.simplefilter("ignore") mean, std = gp.predict(x, return_std=True) - a = (mean - y_max - xi) + a = mean - y_max - xi z = a / std return a * norm.cdf(z) + std * norm.pdf(z) @staticmethod - def _poi(x, gp, y_max, xi): + def poi(x, gp, y_max, xi): + r"""Calculate Probability of Improvement acqusition function. + + Calculated as + + .. math:: \text{POI}(x) = \Phi\left( \frac{\mu(x)-y_{\text{max}} - \xi }{\sigma(x)} \right) + + where :math:`\Phi` is the CDF of the normal distribution. + + Parameters + ---------- + x : np.ndarray + Parameters to evaluate the function at. + gp : sklearn.gaussian_process.GaussianProcessRegressor + A gaussian process regressor modelling the target function based on + previous observations. + + y_max : number + Highest found value of the target function. + + xi : float, positive + Governs the exploration/exploitation tradeoff. Lower prefers + exploitation, higher prefers exploration. + + + Returns + ------- + Values of the acquisition function + + """ with warnings.catch_warnings(): warnings.simplefilter("ignore") mean, std = gp.predict(x, return_std=True) @@ -208,15 +345,24 @@ def _poi(x, gp, y_max, xi): class NotUniqueError(Exception): """A point is non-unique.""" - pass def load_logs(optimizer, logs): """Load previous ... - """ + Parameters + ---------- + optimizer : BayesianOptimizer + Optimizer the register the previous observations with. + logs : str or bytes or os.PathLike + File to load the logs from. + Returns + ------- + The optimizer with the state loaded. + + """ if isinstance(logs, str): logs = [logs] @@ -233,7 +379,10 @@ def load_logs(optimizer, logs): optimizer.register( params=iteration["params"], target=iteration["target"], - constraint_value=iteration["constraint"] if optimizer.is_constrained else None + constraint_value=( + iteration["constraint"] + if optimizer.is_constrained else None + ) ) except NotUniqueError: continue @@ -242,10 +391,19 @@ def load_logs(optimizer, logs): def ensure_rng(random_state=None): - """ - Creates a random number generator based on an optional seed. This can be - an integer or another random state for a seeded rng, or None for an - unseeded rng. + """Create a random number generator based on an optional seed. + + Parameters + ---------- + random_state : np.random.RandomState or int or None, default=None + Random state to use. if `None`, will create an unseeded random state. + If `int`, creates a state using the argument as seed. If a + `np.random.RandomState` simply returns the argument. + + Returns + ------- + np.random.RandomState + """ if random_state is None: random_state = np.random.RandomState() @@ -255,74 +413,3 @@ def ensure_rng(random_state=None): assert isinstance(random_state, np.random.RandomState) return random_state - -class Colours: - """Print in nice colours.""" - - BLUE = '\033[94m' - BOLD = '\033[1m' - CYAN = '\033[96m' - DARKCYAN = '\033[36m' - END = '\033[0m' - GREEN = '\033[92m' - PURPLE = '\033[95m' - RED = '\033[91m' - UNDERLINE = '\033[4m' - YELLOW = '\033[93m' - - @classmethod - def _wrap_colour(cls, s, colour): - return colour + s + cls.END - - @classmethod - def black(cls, s): - """Wrap text in black.""" - return cls._wrap_colour(s, cls.END) - - @classmethod - def blue(cls, s): - """Wrap text in blue.""" - return cls._wrap_colour(s, cls.BLUE) - - @classmethod - def bold(cls, s): - """Wrap text in bold.""" - return cls._wrap_colour(s, cls.BOLD) - - @classmethod - def cyan(cls, s): - """Wrap text in cyan.""" - return cls._wrap_colour(s, cls.CYAN) - - @classmethod - def darkcyan(cls, s): - """Wrap text in darkcyan.""" - return cls._wrap_colour(s, cls.DARKCYAN) - - @classmethod - def green(cls, s): - """Wrap text in green.""" - return cls._wrap_colour(s, cls.GREEN) - - @classmethod - def purple(cls, s): - """Wrap text in purple.""" - return cls._wrap_colour(s, cls.PURPLE) - - @classmethod - def red(cls, s): - """Wrap text in red.""" - return cls._wrap_colour(s, cls.RED) - - @classmethod - def underline(cls, s): - """Wrap text in underline.""" - return cls._wrap_colour(s, cls.UNDERLINE) - - @classmethod - def yellow(cls, s): - """Wrap text in yellow.""" - return cls._wrap_colour(s, cls.YELLOW) - - -just_fix_windows_console() diff --git a/docsrc/Makefile b/docsrc/Makefile index e0e46fb58..c3886de30 100644 --- a/docsrc/Makefile +++ b/docsrc/Makefile @@ -15,6 +15,8 @@ BUILDDIR = ../docs .PHONY: help Makefile github: + @cp ../README.md . + @cp -r ../static . @make html @cp -a ../docs/html/. ../docs diff --git a/docsrc/code_docs.rst b/docsrc/code_docs.rst index ebd5a076b..289a1f8b8 100644 --- a/docsrc/code_docs.rst +++ b/docsrc/code_docs.rst @@ -1,7 +1,7 @@ Code Documentation ================== -This page shows the documentation generated by sphinx automatically scanning our source code +This page shows the documentation generated by sphinx automatically scanning the source code. Bayesian Optimization --------------------- diff --git a/docsrc/conf.py b/docsrc/conf.py index b758e36f4..9393cec85 100644 --- a/docsrc/conf.py +++ b/docsrc/conf.py @@ -42,7 +42,9 @@ 'sphinx.ext.githubpages', 'nbsphinx', 'IPython.sphinxext.ipython_console_highlighting', - 'sphinx.ext.mathjax'] + 'sphinx.ext.mathjax', + 'myst_parser' +] source_suffix = { '.rst': 'restructuredtext', @@ -63,6 +65,7 @@ # a list of builtin themes. # html_theme = 'sphinx_rtd_theme' +html_favicon = 'func.ico' # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, diff --git a/docsrc/func.ico b/docsrc/func.ico new file mode 100644 index 000000000..f29470261 Binary files /dev/null and b/docsrc/func.ico differ diff --git a/docsrc/index.rst b/docsrc/index.rst index 03e5da765..cfa017774 100644 --- a/docsrc/index.rst +++ b/docsrc/index.rst @@ -5,6 +5,7 @@ Bayesian Optimization :maxdepth: 2 :caption: Contents: + /quickstart /examples /code_docs diff --git a/docsrc/quickstart.rst b/docsrc/quickstart.rst new file mode 100644 index 000000000..9f12a4c65 --- /dev/null +++ b/docsrc/quickstart.rst @@ -0,0 +1,2 @@ +.. include:: README.md + :parser: myst_parser.sphinx_ \ No newline at end of file diff --git a/examples/async_optimization.py b/examples/async_optimization.py index 3eae4e8aa..3f983cfea 100644 --- a/examples/async_optimization.py +++ b/examples/async_optimization.py @@ -2,10 +2,11 @@ import random from bayes_opt import BayesianOptimization -from bayes_opt.util import UtilityFunction, Colours +from bayes_opt.util import UtilityFunction import asyncio import threading +from colorama import Fore try: import json @@ -96,19 +97,19 @@ def run_optimizer(): status += name + " got {} as target.\n".format(target) status += name + " will to register next: {}.\n".format(register_data) - print(colour(status), end="\n") + print(colour + status, end="\n") global results results.append((name, max_target)) - print(colour(name + " is done!"), end="\n\n") + print(colour + name + " is done!", end="\n\n") if __name__ == "__main__": ioloop = tornado.ioloop.IOLoop.instance() optimizers_config = [ - {"name": "optimizer 1", "colour": Colours.red}, - {"name": "optimizer 2", "colour": Colours.green}, - {"name": "optimizer 3", "colour": Colours.blue}, + {"name": "optimizer 1", "colour": Fore.RED}, + {"name": "optimizer 2", "colour": Fore.GREEN}, + {"name": "optimizer 3", "colour": Fore.BLUE}, ] app_thread = threading.Thread(target=run_optimization_app) diff --git a/examples/domain_reduction.ipynb b/examples/domain_reduction.ipynb index 4dd1041ad..81ec8f164 100644 --- a/examples/domain_reduction.ipynb +++ b/examples/domain_reduction.ipynb @@ -18,7 +18,7 @@ "\n", "**Zoom**: contract the region of interest.\n", "\n", - "![](sdr.png)\n", + "![](../static/sdr.png)\n", "\n", "\n", "## Parameters\n", diff --git a/examples/sklearn_example.py b/examples/sklearn_example.py index 27ef7e8b4..14be8dee6 100644 --- a/examples/sklearn_example.py +++ b/examples/sklearn_example.py @@ -4,7 +4,7 @@ from sklearn.svm import SVC from bayes_opt import BayesianOptimization -from bayes_opt.util import Colours +from colorama import Fore def get_data(): """Synthetic binary classification dataset.""" @@ -114,8 +114,8 @@ def rfc_crossval(n_estimators, min_samples_split, max_features): if __name__ == "__main__": data, targets = get_data() - print(Colours.yellow("--- Optimizing SVM ---")) + print(Fore.YELLOW + "--- Optimizing SVM ---") optimize_svc(data, targets) - print(Colours.green("--- Optimizing Random Forest ---")) + print(Fore.GREEN("--- Optimizing Random Forest ---")) optimize_rfc(data, targets) diff --git a/examples/bayesian_optimization.gif b/static/bayesian_optimization.gif similarity index 100% rename from examples/bayesian_optimization.gif rename to static/bayesian_optimization.gif diff --git a/examples/bo_example.png b/static/bo_example.png similarity index 100% rename from examples/bo_example.png rename to static/bo_example.png diff --git a/examples/func.png b/static/func.png similarity index 100% rename from examples/func.png rename to static/func.png diff --git a/examples/sdr.png b/static/sdr.png similarity index 100% rename from examples/sdr.png rename to static/sdr.png diff --git a/tests/test_target_space.py b/tests/test_target_space.py index 494b42495..d009cbc48 100644 --- a/tests/test_target_space.py +++ b/tests/test_target_space.py @@ -157,6 +157,19 @@ def test_probe(): assert all(space.params[1] == np.array([5, 4])) assert all(space.target == np.array([3, 9, 3 , 9])) + space = TargetSpace(target_func, PBOUNDS, allow_duplicate_points=False) + + # register wrong target to check probe doesn't recompute a duplicate point + space.register(params={"p1": 1, "p2": 2}, target=5) + + # probing same point with dict + target_ = space.probe(params={"p1": 1, "p2": 2}) + assert target_ == 5 + + # probing same point with array + target_ = space.probe(np.array([1, 2])) + assert target_ == 5 + def test_random_sample(): pbounds = { diff --git a/tests/test_util.py b/tests/test_util.py index 5414b3566..89b79c01e 100644 --- a/tests/test_util.py +++ b/tests/test_util.py @@ -2,7 +2,7 @@ import numpy as np from bayes_opt import BayesianOptimization -from bayes_opt.util import UtilityFunction, Colours +from bayes_opt.util import UtilityFunction from bayes_opt.util import acq_max, load_logs, ensure_rng from sklearn.gaussian_process.kernels import Matern @@ -189,28 +189,6 @@ def c(x, y): assert len(optimizer.space) == 7 -def test_colours(): - colour_wrappers = [ - (Colours.END, Colours.black), - (Colours.BLUE, Colours.blue), - (Colours.BOLD, Colours.bold), - (Colours.CYAN, Colours.cyan), - (Colours.DARKCYAN, Colours.darkcyan), - (Colours.GREEN, Colours.green), - (Colours.PURPLE, Colours.purple), - (Colours.RED, Colours.red), - (Colours.UNDERLINE, Colours.underline), - (Colours.YELLOW, Colours.yellow), - ] - - for colour, wrapper in colour_wrappers: - text1 = Colours._wrap_colour("test", colour) - text2 = wrapper("test") - - assert text1.split("test") == [colour, Colours.END] - assert text2.split("test") == [colour, Colours.END] - - if __name__ == '__main__': r""" CommandLine: