Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions .github/workflows/check_docstrings.yml
Original file line number Diff line number Diff line change
@@ -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
1 change: 1 addition & 0 deletions bayes_opt/__init__.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down
85 changes: 66 additions & 19 deletions bayes_opt/bayesian_optimization.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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]
Expand All @@ -35,35 +48,36 @@ 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
# str -> dict
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.
Expand Down Expand Up @@ -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

Expand All @@ -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
----------
Expand All @@ -201,15 +239,21 @@ 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:
self._space.probe(params)
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())

Expand All @@ -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.
"""
Comment thread
t-muser marked this conversation as resolved.
Resolved
if self._queue.empty and self._space.empty:
init_points = max(init_points, 1)

Expand All @@ -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
----------
Expand Down Expand Up @@ -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
----------
Expand All @@ -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)
7 changes: 7 additions & 0 deletions bayes_opt/event.py
Original file line number Diff line number Diff line change
@@ -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'
Expand Down
23 changes: 15 additions & 8 deletions bayes_opt/observer.py
Original file line number Diff line number Diff line change
@@ -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

Expand All @@ -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

Expand All @@ -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
Expand Down