Skip to content

Commit eb4a6d4

Browse files
committed
Added tests and a TravisCI script
1 parent 66249ba commit eb4a6d4

File tree

7 files changed

+198
-33
lines changed

7 files changed

+198
-33
lines changed

.travis.yml

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
language: python
2+
sudo: false
3+
4+
cache:
5+
apt: true
6+
directories:
7+
- $HOME/.cache/pip
8+
- $HOME/download
9+
python:
10+
- "2.7"
11+
- "3.4"
12+
- "3.5"
13+
- "3.6"
14+
before_install:
15+
- pip install pip -U
16+
- pip install pytest -U
17+
- pip install pytest-cov -U
18+
- pip install codecov -U
19+
#- pip install xdoctest -U
20+
# - pip install delorean
21+
install:
22+
#- travis_retry python setup.py build develop
23+
- travis_retry pip install -e .
24+
script:
25+
- travis_wait pytest --cov-config .coveragerc --cov-report html --cov bayes_opt bayes_opt
26+
#-p no:doctest --xdoctest --cov=ubelt ubelt
27+
after_success:
28+
#- coveralls || echo "Coveralls upload failed"
29+
- codecov
30+
#after_failure:
31+
# - cat failed_doctests.txt
32+
cache:
33+
apt: true
34+
directories:
35+
- $HOME/.pip-cache

bayes_opt/bayesian_optimization.py

Lines changed: 22 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,7 @@
55
import warnings
66
from sklearn.gaussian_process import GaussianProcessRegressor
77
from sklearn.gaussian_process.kernels import Matern
8-
from .helpers import (UtilityFunction, PrintLog, unique_rows, acq_max,
9-
ensure_rng)
8+
from .helpers import (UtilityFunction, PrintLog, acq_max, ensure_rng)
109
from .target_space import TargetSpace
1110

1211

@@ -86,12 +85,13 @@ def init(self, init_points):
8685
y = self._observe_point(x)
8786

8887
# Add the points from `self.initialize` to the observations
89-
x_init = np.vstack(self.x_init)
90-
y_init = np.hstack(self.y_init)
91-
for x, y in zip(x_init, y_init):
92-
self.space.add_observation(x, y)
93-
if self.verbose:
94-
self.plog.print_step(x, y)
88+
if self.x_init:
89+
x_init = np.vstack(self.x_init)
90+
y_init = np.hstack(self.y_init)
91+
for x, y in zip(x_init, y_init):
92+
self.space.add_observation(x, y)
93+
if self.verbose:
94+
self.plog.print_step(x, y)
9595

9696
# Updates the flag
9797
self.initialized = True
@@ -102,26 +102,23 @@ def _observe_point(self, x):
102102
self.plog.print_step(x, y)
103103
return y
104104

105-
def explore(self, points_dict):
106-
"""Method to lazy explore user defined points.
107-
108-
:param points_dict:
109-
"""
110-
points = self.space._dict_to_points(points_dict)
111-
self.init_points = points
112-
113-
def explore_eager(self, points_dict):
114-
"""Method to eagerly explore more points
105+
def explore(self, points_dict, eager=False):
106+
"""Method to explore user defined points.
115107
116108
:param points_dict:
109+
:param eager: if True, these points are evaulated immediately
117110
"""
118-
self.plog.reset_timer()
119-
if self.verbose:
120-
self.plog.print_header(initialization=True)
121-
122-
points = self.space._dict_to_points(points_dict)
123-
for x in points:
124-
self._observe_point(x)
111+
if eager:
112+
self.plog.reset_timer()
113+
if self.verbose:
114+
self.plog.print_header(initialization=True)
115+
116+
points = self.space._dict_to_points(points_dict)
117+
for x in points:
118+
self._observe_point(x)
119+
else:
120+
points = self.space._dict_to_points(points_dict)
121+
self.init_points = points
125122

126123
def initialize(self, points_dict):
127124
"""

pytest.ini

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
[pytest]
2+
;addopts = -p no:doctest --xdoctest --xdoctest-style=google
3+
norecursedirs = .git ignore build __pycache__
4+
5+
filterwarnings= default

tests/test_bayesian_optimization.py

Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
from bayes_opt import BayesianOptimization
2+
from bayes_opt.helpers import ensure_rng
3+
import numpy as np
4+
5+
6+
def test_bayes_opt_demo():
7+
"""
8+
pytest tests/test_bayesian_optimization.py::test_bayes_opt_demo
9+
10+
See Also
11+
--------
12+
https://github.com/fmfn/BayesianOptimization/blob/master/examples/exploitation%20vs%20exploration.ipynb
13+
"""
14+
random_state = ensure_rng(0)
15+
xs = np.linspace(-2, 10, 1000)
16+
f = np.exp(-(xs - 2)**2) + np.exp(-(xs - 6)**2 / 10) + 1 / (xs**2 + 1)
17+
bo = BayesianOptimization(f=lambda x: f[int(x)],
18+
pbounds={'x': (0, len(f) - 1)},
19+
random_state=random_state,
20+
verbose=0)
21+
gp_params = {'alpha': 1e-5, 'n_restarts_optimizer': 2}
22+
bo.maximize(init_points=10, n_iter=10, acq='ucb', kappa=5, **gp_params)
23+
res = bo.space.max_point()
24+
max_params = res['max_params']
25+
max_val = res['max_val']
26+
27+
assert max_val > 1.2, 'function range is ~.2 - ~1.4, should be above 1.'
28+
assert max_val / f.max() > .9, 'should be better than 90% of max val'
29+
30+
assert max_params['x'] > 300, 'should be in a peak area (around 300)'
31+
assert max_params['x'] < 400, 'should be in a peak area (around 300)'
32+
33+
34+
def test_only_random():
35+
random_state = ensure_rng(0)
36+
xs = np.linspace(-2, 10, 1000)
37+
f = np.exp(-(xs - 2)**2) + np.exp(-(xs - 6)**2 / 10) + 1 / (xs**2 + 1)
38+
bo = BayesianOptimization(f=lambda x: f[int(x)],
39+
pbounds={'x': (0, len(f) - 1)},
40+
random_state=random_state,
41+
verbose=0)
42+
bo.init(20)
43+
res = bo.space.max_point()
44+
max_params = res['max_params']
45+
max_val = res['max_val']
46+
47+
assert max_val > 1.0, 'function range is ~.2 - ~1.4, should be above 1.'
48+
assert max_val / f.max() > .8, 'should be better than 80% of max val'
49+
50+
assert max_params['x'] > 200, 'should be in a peak area (around 300)'
51+
assert max_params['x'] < 500, 'should be in a peak area (around 300)'
52+
53+
54+
def test_explore_lazy():
55+
random_state = ensure_rng(0)
56+
xs = np.linspace(-2, 10, 1000)
57+
f = np.exp(-(xs - 2)**2) + np.exp(-(xs - 6)**2 / 10) + 1 / (xs**2 + 1)
58+
bo = BayesianOptimization(f=lambda x: f[int(x)],
59+
pbounds={'x': (0, len(f) - 1)},
60+
random_state=random_state,
61+
verbose=0)
62+
bo.explore({'x': [f.argmin()]}, eager=False)
63+
assert len(bo.space) == 0
64+
assert len(bo.init_points) == 1
65+
66+
# Note we currently expect lazy explore to override points
67+
# This may not be the case in the future.
68+
bo.explore({'x': [f.argmax()]}, eager=False)
69+
assert len(bo.space) == 0
70+
assert len(bo.init_points) == 1
71+
72+
bo.maximize(init_points=0, n_iter=0, acq='ucb', kappa=5)
73+
74+
res = bo.space.max_point()
75+
max_params = res['max_params']
76+
max_val = res['max_val']
77+
78+
assert max_params['x'] == f.argmax()
79+
assert max_val == f.max()
80+
81+
82+
def test_explore_eager():
83+
random_state = ensure_rng(0)
84+
xs = np.linspace(-2, 10, 1000)
85+
f = np.exp(-(xs - 2)**2) + np.exp(-(xs - 6)**2 / 10) + 1 / (xs**2 + 1)
86+
bo = BayesianOptimization(f=lambda x: f[int(x)],
87+
pbounds={'x': (0, len(f) - 1)},
88+
random_state=random_state,
89+
verbose=0)
90+
bo.explore({'x': [f.argmin()]}, eager=True)
91+
assert len(bo.space) == 1
92+
assert len(bo.init_points) == 0
93+
94+
# Note we currently expect lazy explore to override points
95+
# This may not be the case in the future.
96+
bo.explore({'x': [f.argmax()]}, eager=True)
97+
assert len(bo.space) == 2
98+
assert len(bo.init_points) == 0
99+
100+
res = bo.space.max_point()
101+
max_params = res['max_params']
102+
max_val = res['max_val']
103+
104+
assert max_params['x'] == f.argmax()
105+
assert max_val == f.max()
106+
107+
108+
if __name__ == '__main__':
109+
r"""
110+
CommandLine:
111+
python tests/test_bayesian_optimization.py
112+
"""
113+
import pytest
114+
pytest.main([__file__])

tests/tests_helper_functions.py renamed to tests/test_helper_functions.py

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,7 @@
44
import numpy as np
55
from sklearn.gaussian_process import GaussianProcessRegressor
66
from sklearn.gaussian_process.kernels import Matern
7-
# import sys
8-
# sys.path.append("./")
9-
# sys.path.append("../bayes_opt/")
10-
# from bayes_opt.helpers import UtilityFunction, acq_max
11-
from bayes_opt.helpers import UtilityFunction, acq_max
7+
from bayes_opt.helpers import UtilityFunction, acq_max, ensure_rng
128

139

1410
def get_globals():
@@ -61,11 +57,13 @@ def setUp(self, kind='ucb', kappa=1.0, xi=1e-6):
6157
self.util = UtilityFunction(kind=kind, kappa=kappa, xi=xi)
6258
self.episilon = 1e-2
6359
self.y_max = 2.0
60+
self.random_state = ensure_rng(0)
6461

6562
def test_acq_max_function_with_ucb_algo(self):
6663
self.setUp(kind='ucb', kappa=1.0, xi=1.0)
6764
max_arg = acq_max(
68-
self.util.utility, GP, self.y_max, bounds=np.array([[0, 1], [0, 1]])
65+
self.util.utility, GP, self.y_max, bounds=np.array([[0, 1], [0, 1]]),
66+
random_state=self.random_state
6967
)
7068
_, brute_max_arg = brute_force_maximum(MESH, GP)
7169

@@ -74,12 +72,19 @@ def test_acq_max_function_with_ucb_algo(self):
7472
def test_ei_max_function_with_ucb_algo(self):
7573
self.setUp(kind='ei', kappa=1.0, xi=1e-6)
7674
max_arg = acq_max(
77-
self.util.utility, GP, self.y_max, bounds=np.array([[0, 1], [0, 1]])
75+
self.util.utility, GP, self.y_max, bounds=np.array([[0, 1], [0, 1]]),
76+
random_state=self.random_state
7877
)
7978
_, brute_max_arg = brute_force_maximum(MESH, GP, kind='ei')
8079

8180
self.assertTrue( all(abs(brute_max_arg - max_arg) < self.episilon))
8281

8382

8483
if __name__ == '__main__':
85-
unittest.main()
84+
r"""
85+
CommandLine:
86+
python tests/test_target_space.py
87+
"""
88+
# unittest.main()
89+
import pytest
90+
pytest.main([__file__])

tests/test_target_space.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,3 +107,12 @@ def test_observe_m_nd_points(m, n):
107107
space.observe_point(x)
108108
space._assert_internal_invariants(fast=False)
109109
space._assert_internal_invariants(fast=False)
110+
111+
112+
if __name__ == '__main__':
113+
r"""
114+
CommandLine:
115+
python tests/test_target_space.py
116+
"""
117+
import pytest
118+
pytest.main([__file__])

tests/tests_bayesian_optimization.py

Whitespace-only changes.

0 commit comments

Comments
 (0)