From 201c6b24d4a8e93d442a46ad4a2980adfc5df1ea Mon Sep 17 00:00:00 2001 From: till-m <36440677+till-m@users.noreply.github.com> Date: Sat, 5 Aug 2023 16:10:14 +0200 Subject: [PATCH 01/13] Replace custom colour implementation, add docs for `logger.py`, `util.py` (#435) * Replace custom colour implementation, add docs for `logger.py`, `util.py` * minor typo/syntax fixes * User `or` to separate different possible types --- bayes_opt/logger.py | 191 +++++++++++++++--- bayes_opt/target_space.py | 6 +- bayes_opt/util.py | 342 ++++++++++++++++++++------------- docsrc/code_docs.rst | 2 +- examples/async_optimization.py | 13 +- examples/sklearn_example.py | 6 +- tests/test_util.py | 24 +-- 7 files changed, 388 insertions(+), 196 deletions(-) diff --git a/bayes_opt/logger.py b/bayes_opt/logger.py index edcfa836c..273087e9f 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 + + + 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 + + + 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 + + + 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,43 @@ 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. + """ + def __init__(self, path, reset=True): + """ + Initialize the logger. + + Parameters + ---------- + path : str or bytes or os.PathLike + + """ 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/target_space.py b/bayes_opt/target_space.py index e90cfbcf0..dea99f976 100644 --- a/bayes_opt/target_space.py +++ b/bayes_opt/target_space.py @@ -1,6 +1,6 @@ import numpy as np from .util import ensure_rng, NotUniqueError -from .util import Colours +from colorama import Fore def _hashable(x): @@ -188,8 +188,8 @@ 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.' + f' Continuing ...') else: raise NotUniqueError(f'Data point {x} is not unique. You can set "allow_duplicate_points=True" to ' f'avoid this error') diff --git a/bayes_opt/util.py b/bayes_opt/util.py index 2ac87254b..d8a4f9077 100644 --- a/bayes_opt/util.py +++ b/bayes_opt/util.py @@ -1,55 +1,69 @@ +"""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): - """ - 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, - and then running L-BFGS-B from `n_iter` (250) random starting points. + and then running L-BFGS-B from `n_iter` (10) random starting points. 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 + + 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. 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) @@ -110,33 +124,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 @@ -147,28 +161,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) @@ -176,17 +243,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) @@ -197,15 +329,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] @@ -222,7 +363,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 @@ -231,10 +375,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() @@ -244,74 +397,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/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/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/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/tests/test_util.py b/tests/test_util.py index 16ec28fd6..b3a73668a 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 @@ -174,28 +174,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: From b9f16f276eab29a820b2330485fe26aa10f598fc Mon Sep 17 00:00:00 2001 From: till-m <36440677+till-m@users.noreply.github.com> Date: Sun, 13 Aug 2023 16:35:57 +0200 Subject: [PATCH 02/13] Update docs & linting for `constraints.py`, `target_space.py` (#440) * Run tests on any PR * Update docs, linting * Update bayes_opt/constraint.py Co-authored-by: Leandro Braga <18340809+leandrobbraga@users.noreply.github.com> * Rename mislabelled parameters --------- Co-authored-by: Leandro Braga <18340809+leandrobbraga@users.noreply.github.com> --- .github/workflows/run_tests.yml | 1 - bayes_opt/constraint.py | 174 ++++++++++++++------ bayes_opt/target_space.py | 282 ++++++++++++++++++++++---------- 3 files changed, 314 insertions(+), 143 deletions(-) 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/bayes_opt/constraint.py b/bayes_opt/constraint.py index a31142310..5ea333525 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,42 +6,35 @@ class ConstraintModel(): - """ + """Model constraints using GPRs. + 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. - - lb: numeric or numpy.ndarray - Upper limit(s) for the constraints. The return value of `fun` should - have exactly this shape. - - ub: numeric or numpy.ndarray - Upper limit(s) for the constraints. The return value of `fun` should - have exactly this shape. - - 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. - - Note - ---- - 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 - is a simply the product of the individual probabilities. + 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 : float or np.ndarray + The lower bound on the constraints. Should have the same + dimensionality as the return value of the constraint function. + + 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 : np.random.RandomState or int or None, default=None + Random state to use. """ 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 +52,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. + """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 +96,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 +117,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 +162,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/target_space.py b/bayes_opt/target_space.py index dea99f976..195474cb2 100644 --- a/bayes_opt/target_space.py +++ b/bayes_opt/target_space.py @@ -1,20 +1,39 @@ +"""Manages the optimization domain and holds points.""" import numpy as np -from .util import ensure_rng, NotUniqueError from colorama import Fore +from .util import ensure_rng, NotUniqueError 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. + + random_state : int, RandomState, or None + optionally specify a seed for a random number generator - Example - ------- + 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)} @@ -26,25 +45,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 @@ -62,7 +62,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 = {} @@ -77,63 +77,149 @@ 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 def params_to_array(self, params): + """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 dictionary. + """ try: assert set(params) == set(self.keys) - except AssertionError: + except AssertionError as e: 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})." + ) from e return np.asarray([params[key] for key in self.keys]) def array_to_params(self, x): + """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. + """ try: assert len(x) == len(self.keys) - except AssertionError: + except AssertionError as e: 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)})." + ) from e return dict(zip(self.keys, x)) def _as_array(self, x): @@ -145,20 +231,20 @@ def _as_array(self, x): x = x.ravel() try: assert x.size == self.dim - except AssertionError: + except AssertionError as e: 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)})." + ) from e 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 + x : np.ndarray + a single point, with len(x) == self.dim. y : float target function value @@ -172,8 +258,8 @@ def register(self, params, target, constraint_value=None): ----- runs in amortized constant time - Example - ------- + Examples + -------- >>> pbounds = {'p1': (0, 1), 'p2': (1, 100)} >>> space = TargetSpace(lambda p1, p2: p1 + p2, pbounds) >>> len(space) @@ -188,11 +274,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(Fore.RED + f'Data point {x} is not unique. {self.n_duplicate_points} duplicates registered.' - f' Continuing ...') + + 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') self._params = np.concatenate([self._params, x.reshape(1, -1)]) self._target = np.concatenate([self._target, [target]]) @@ -211,17 +298,15 @@ 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 records them - as observations. + """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 returns a cached value of `y`. Parameters ---------- - x : ndarray + params : np.ndarray a single point, with len(x) == self.dim Returns @@ -236,22 +321,21 @@ def probe(self, 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 random points within the bounds of the space. + """Create random points within the bounds of the space. Returns - ---------- - data: ndarray + ------- + data: np.ndarray [num x dim] array points 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) @@ -267,7 +351,15 @@ def _target_max(self): """Get maximum target value found. If there is a constraint present, the maximum value that fulfills the - constraint is returned.""" + constraint is returned. + + + Returns + ------- + dict | None + The maximum allowed point's target function value. + Returns None if there is no (allowed) maximum. + """ if len(self.target) == 0: return None @@ -284,7 +376,15 @@ def max(self): """Get maximum target value found and corresponding parameters. If there is a constraint present, the maximum value that fulfills the - constraint is returned.""" + constraint is returned. + + Returns + ------- + dict | None + A dictionary containing the maximum allowed point's target function + value, parameters, and, if applicable, constraint function value. + Returns None if there is no (allowed) maximum. + """ target_max = self._target_max() if target_max is None: @@ -299,10 +399,9 @@ def max(self): else: target = self.target params = self.params - constraint_values = self.constraint_values - + target_max_idx = np.where(target == target_max)[0][0] - + res = { 'target': target_max, @@ -318,6 +417,12 @@ def max(self): def res(self): """Get all target values and constraint fulfillment for all parameters. + + Returns + ------- + dict + A dictionary containing the target function values, parameters, + and, if applicable, constraint function values and allowedness. """ if self._constraint is None: params = [dict(zip(self.keys, p)) for p in self.params] @@ -326,27 +431,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 ---------- From 77c71116f4d83121dd9be5765ab13096d3ae3219 Mon Sep 17 00:00:00 2001 From: till-m <36440677+till-m@users.noreply.github.com> Date: Sat, 14 Oct 2023 13:02:22 +0200 Subject: [PATCH 03/13] Update various docstrings, add workflow to check docstrings (#445) * Fixes issue-436: Constrained optimization does not allow duplicate points (#437) * Update docs of `bayesian_optimization.py` and `observer.py`. * Fix minor style issue in module docstring * Update docs of `__init__.py` and `events.py`. * Fix minor style issue in class docstring * Add workflow to check docstrings * Update bayes_opt/bayesian_optimization.py Co-authored-by: Leandro Braga <18340809+leandrobbraga@users.noreply.github.com> --------- Co-authored-by: YoungJae Bae <57710489+YoungJaeBae@users.noreply.github.com> Co-authored-by: Leandro Braga <18340809+leandrobbraga@users.noreply.github.com> --- .github/workflows/check_docstrings.yml | 30 +++++++++ bayes_opt/__init__.py | 1 + bayes_opt/bayesian_optimization.py | 85 ++++++++++++++++++++------ bayes_opt/event.py | 7 +++ bayes_opt/observer.py | 23 ++++--- 5 files changed, 119 insertions(+), 27 deletions(-) create mode 100644 .github/workflows/check_docstrings.yml diff --git a/.github/workflows/check_docstrings.yml b/.github/workflows/check_docstrings.yml new file mode 100644 index 000000000..4f6e8ce94 --- /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 bayes_opt/* + #- name: Run linting + # run : pylint bayes_opt/* --disable=C0103 # ignore no snake_case conformity of arguments diff --git a/bayes_opt/__init__.py b/bayes_opt/__init__.py index 3c9d4791c..50cd81bcb 100644 --- a/bayes_opt/__init__.py +++ b/bayes_opt/__init__.py @@ -1,3 +1,4 @@ +"""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 diff --git a/bayes_opt/bayesian_optimization.py b/bayes_opt/bayesian_optimization.py index 97a7b9de1..da0702a8d 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. @@ -150,7 +164,8 @@ def __init__(self, f, pbounds, constraint=constraint_, - random_state=random_state + random_state=random_state, + allow_duplicate_points=self._allow_duplicate_points ) self.is_constrained = True @@ -167,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 ---------- @@ -201,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: @@ -209,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()) @@ -233,7 +277,13 @@ def suggest(self, utility_function): 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) @@ -257,10 +307,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. + Maximize the given function over the target space. Parameters ---------- @@ -318,8 +366,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 ---------- @@ -329,5 +376,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/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/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 From a4df58c86372a3e9bba00d0d38cec8ce110c012c Mon Sep 17 00:00:00 2001 From: till-m <36440677+till-m@users.noreply.github.com> Date: Sun, 10 Dec 2023 16:49:57 +0100 Subject: [PATCH 04/13] Pydocstyle (#453) * Improve acq_max seeding of L-BFGS-B optimization (#297) --------- Co-authored-by: ptapping <63924582+ptapping@users.noreply.github.com> --- bayes_opt/bayesian_optimization.py | 3 ++- bayes_opt/util.py | 14 ++++++++++++-- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/bayes_opt/bayesian_optimization.py b/bayes_opt/bayesian_optimization.py index da0702a8d..3c20eab6d 100644 --- a/bayes_opt/bayesian_optimization.py +++ b/bayes_opt/bayesian_optimization.py @@ -272,7 +272,8 @@ def suggest(self, utility_function): constraint=self.constraint, y_max=self._space._target_max(), bounds=self._space.bounds, - random_state=self._random_state) + random_state=self._random_state, + y_max_params=self._space.params_to_array(self._space.max()['params'])) return self._space.array_to_params(suggestion) diff --git a/bayes_opt/util.py b/bayes_opt/util.py index d8a4f9077..417e307f7 100644 --- a/bayes_opt/util.py +++ b/bayes_opt/util.py @@ -6,7 +6,7 @@ from scipy.optimize import minimize -def acq_max(ac, gp, y_max, bounds, random_state, constraint=None, n_warmup=10000, n_iter=10): +def acq_max(ac, gp, y_max, bounds, random_state, constraint=None, n_warmup=10000, n_iter=10, y_max_params=None): """Find the maximum of the acquisition function. It uses a combination of random sampling (cheap) and the 'L-BFGS-B' @@ -44,6 +44,9 @@ def acq_max(ac, gp, y_max, bounds, random_state, constraint=None, n_warmup=10000 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`. + Returns ------- Parameters maximizing the acquisition function. @@ -101,7 +104,14 @@ def adjusted_ac(x): # Explore the parameter space more thoroughly x_seeds = random_state.uniform(bounds[:, 0], bounds[:, 1], - size=(n_iter, bounds.shape[0])) + size=(1+n_iter+int(not y_max_params is None), + bounds.shape[0])) + + x_seeds[0] = x_max + if not y_max_params is None: + # Add the provided best sample to the seeds so that the optimization + # algorithm is aware of it and will attempt to find its local maxima + x_seeds[1] = y_max_params for x_try in x_seeds: # Find the minimum of minus the acquisition function From a58ecaf65e494a6a94788a8905469d20289cd558 Mon Sep 17 00:00:00 2001 From: till-m <36440677+till-m@users.noreply.github.com> Date: Wed, 24 Jan 2024 22:28:19 +0100 Subject: [PATCH 05/13] Domain reduction, Sphinx docs (#455) * Fixes issue-436: Constrained optimization does not allow duplicate points (#437) * Update docs of `bayesian_optimization.py` and `observer.py`. * Fix minor style issue in module docstring * Update docs of `__init__.py` and `events.py`. * Fix minor style issue in class docstring * Add workflow to check docstrings * Update bayes_opt/bayesian_optimization.py Co-authored-by: Leandro Braga <18340809+leandrobbraga@users.noreply.github.com> * Improve acq_max seeding of L-BFGS-B optimization (#297) * bounds_transformer could bypass global_bounds due to the test logic within _trim function in domain_reduction.py (#441) * Update trim bounds in domain_reduction.py Previously, when the new upper limit was less than the original lower limit, the new_bounds could bypass the global_bounds. * Update test_seq_domain_red.py Added test cases to catch an error when both bounds of new_bounds exceeded the global_bounds * Update domain_reduction.py _trim function now avoids an error when both bounds for a given parameter in new_bounds exceed the global_bounds * Update domain_reduction.py comments * fixed English in domain_reduction.py * use numpy to sort bounds, boundary exceeded warn. * simple sort test added * domain_red windows target_space to global_bounds Added windowing function to improve the convergence of optimizers that use domain_reduction. Improved comments and documentation. * target_space.max respects bounds; SDRT warnings * Remove unused function. This function was used to prototype a solution. It should not have been pushed and can be removed. * Updated target_space.py docstrings * Update tests/test_target_space.py Co-authored-by: till-m <36440677+till-m@users.noreply.github.com> * Added pbound warnings, updated various tests. * updated line spacing for consistency and style * added pbound test condition --------- Co-authored-by: till-m <36440677+till-m@users.noreply.github.com> * DomainReduction docs, docstyle * Add missing doc dependency --------- Co-authored-by: YoungJae Bae <57710489+YoungJaeBae@users.noreply.github.com> Co-authored-by: Leandro Braga <18340809+leandrobbraga@users.noreply.github.com> Co-authored-by: ptapping <63924582+ptapping@users.noreply.github.com> Co-authored-by: Edgar <50716923+perezed00@users.noreply.github.com> --- .github/workflows/build_docs.yml | 2 + .gitignore | 4 +- README.md | 137 +++++++++-------- bayes_opt/constraint.py | 2 +- bayes_opt/domain_reduction.py | 141 +++++++++++++----- bayes_opt/target_space.py | 129 ++++++++++------ bayes_opt/util.py | 3 +- docsrc/Makefile | 2 + docsrc/conf.py | 5 +- docsrc/func.ico | Bin 0 -> 136207 bytes docsrc/index.rst | 1 + docsrc/quickstart.rst | 2 + examples/domain_reduction.ipynb | 2 +- .../bayesian_optimization.gif | Bin {examples => static}/bo_example.png | Bin {examples => static}/func.png | Bin {examples => static}/sdr.png | Bin tests/test_logs_bounds.log | 5 + tests/test_seq_domain_red.py | 51 ++++++- tests/test_target_space.py | 38 ++++- tests/test_util.py | 22 ++- 21 files changed, 386 insertions(+), 160 deletions(-) create mode 100644 docsrc/func.ico create mode 100644 docsrc/quickstart.rst rename {examples => static}/bayesian_optimization.gif (100%) rename {examples => static}/bo_example.png (100%) rename {examples => static}/func.png (100%) rename {examples => static}/sdr.png (100%) create mode 100644 tests/test_logs_bounds.log diff --git a/.github/workflows/build_docs.yml b/.github/workflows/build_docs.yml index 07282413b..a57745b01 100644 --- a/.github/workflows/build_docs.yml +++ b/.github/workflows/build_docs.yml @@ -29,6 +29,8 @@ jobs: pip install nbsphinx pip install sphinx_rtd_theme pip install jupyter + pip install numpydoc + pip install myst-parser - name: Install package run: | pip install -e . 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..652dc9a18 100644 --- a/README.md +++ b/README.md @@ -1,16 +1,18 @@

