From d29231926d99d09bf948ec24b8b31ccd5838ad39 Mon Sep 17 00:00:00 2001 From: till-m Date: Thu, 6 Jul 2023 20:38:49 +0200 Subject: [PATCH 1/3] Replace custom colour implementation, add docs for `logger.py`, `util.py` --- bayes_opt/logger.py | 191 ++++++++++++++++--- bayes_opt/target_space.py | 6 +- bayes_opt/util.py | 339 ++++++++++++++++++++------------- docsrc/code_docs.rst | 2 +- examples/async_optimization.py | 13 +- examples/sklearn_example.py | 6 +- tests/test_util.py | 24 +-- 7 files changed, 385 insertions(+), 196 deletions(-) diff --git a/bayes_opt/logger.py b/bayes_opt/logger.py index edcfa836c..0593d5bf9 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 | bytes | 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..2cc960381 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 | 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,80 @@ 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"""Calcualte 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 +242,80 @@ 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 +326,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 | bytes | os.PathLike + File to load the logs from. + Returns + ------- + The optimizer with the state loaded. + + """ if isinstance(logs, str): logs = [logs] @@ -222,7 +360,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 +372,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 | int | 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 +394,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 ae4d580ad0db136e677dc32a828258d4fe78484f Mon Sep 17 00:00:00 2001 From: till-m Date: Thu, 13 Jul 2023 10:02:32 +0200 Subject: [PATCH 2/3] minor typo/syntax fixes --- bayes_opt/util.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/bayes_opt/util.py b/bayes_opt/util.py index 2cc960381..412c21e40 100644 --- a/bayes_opt/util.py +++ b/bayes_opt/util.py @@ -203,7 +203,7 @@ def utility(self, x, gp, y_max): @staticmethod def ucb(x, gp, kappa): - r"""Calcualte Upper Confidence Bound acquisition function. + r"""Calculate Upper Confidence Bound acquisition function. Similar to Probability of Improvement (`UtilityFunction.poi`), but also considers the magnitude of improvement. @@ -211,6 +211,7 @@ def ucb(x, gp, kappa): .. math:: \text{UCB}(x) = \mu(x) + \kappa \sigma(x) + where :math:`\Phi` is the CDF and :math:`\phi` the PDF of the normal distribution. @@ -254,6 +255,7 @@ def ei(x, gp, y_max, xi): \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. @@ -293,6 +295,7 @@ def poi(x, gp, y_max, xi): 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 From cde37006990708b919724cd98ab88b525aa8fe61 Mon Sep 17 00:00:00 2001 From: till-m Date: Fri, 28 Jul 2023 12:39:21 +0200 Subject: [PATCH 3/3] User `or` to separate different possible types --- bayes_opt/logger.py | 2 +- bayes_opt/util.py | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/bayes_opt/logger.py b/bayes_opt/logger.py index 0593d5bf9..273087e9f 100644 --- a/bayes_opt/logger.py +++ b/bayes_opt/logger.py @@ -253,7 +253,7 @@ def __init__(self, path, reset=True): Parameters ---------- - path : str | bytes | os.PathLike + path : str or bytes or os.PathLike """ self._path = path diff --git a/bayes_opt/util.py b/bayes_opt/util.py index 412c21e40..d8a4f9077 100644 --- a/bayes_opt/util.py +++ b/bayes_opt/util.py @@ -35,7 +35,7 @@ def acq_max(ac, gp, y_max, bounds, random_state, constraint=None, n_warmup=10000 random_state : np.random.RandomState A random state to sample from. - constraint : ConstraintModel | None, default=None + constraint : ConstraintModel or None, default=None n_warmup : int, default=10000 Number of points to sample from the acquisition function as seeds @@ -339,7 +339,7 @@ def load_logs(optimizer, logs): optimizer : BayesianOptimizer Optimizer the register the previous observations with. - logs : str | bytes | os.PathLike + logs : str or bytes or os.PathLike File to load the logs from. Returns @@ -379,7 +379,7 @@ def ensure_rng(random_state=None): Parameters ---------- - random_state : np.random.RandomState | int | None, default=None + 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.