Skip to content

Commit a6dd5de

Browse files
committed
Bayesian optimization example added to tests
1 parent 4e295f0 commit a6dd5de

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

tests/core_tests.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -749,6 +749,7 @@ def test_examples(self):
749749
import example_tests.stream_based_sampling
750750
import example_tests.custom_query_strategies
751751
import example_tests.information_density
752+
import example_tests.bayesian_optimization
752753

753754

754755
if __name__ == '__main__':
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import numpy as np
2+
from functools import partial
3+
from sklearn.gaussian_process import GaussianProcessRegressor
4+
from sklearn.gaussian_process.kernels import Matern
5+
from modAL.models import BayesianOptimizer
6+
from modAL.acquisition import PI, EI, UCB, max_PI, max_EI, max_UCB
7+
8+
9+
# generating the data
10+
X = np.linspace(0, 20, 1000).reshape(-1, 1)
11+
y = np.sin(X)/2 - ((10 - X)**2)/50 + 2
12+
13+
# assembling initial training set
14+
X_initial, y_initial = X[150].reshape(1, -1), y[150].reshape(1, -1)
15+
16+
# defining the kernel for the Gaussian process
17+
kernel = Matern(length_scale=1.0)
18+
19+
tr = 0.1
20+
PI_tr = partial(PI, tradeoff=tr)
21+
PI_tr.__name__ = 'PI, tradeoff = %1.1f' % tr
22+
max_PI_tr = partial(max_PI, tradeoff=tr)
23+
24+
acquisitions = zip(
25+
[PI_tr, EI, UCB],
26+
[max_PI_tr, max_EI, max_UCB],
27+
)
28+
29+
for acquisition, query_strategy in acquisitions:
30+
31+
# initializing the optimizer
32+
optimizer = BayesianOptimizer(
33+
estimator=GaussianProcessRegressor(kernel=kernel),
34+
X_training=X_initial, y_training=y_initial,
35+
query_strategy=query_strategy
36+
)
37+
38+
for n_query in range(5):
39+
query_idx, query_inst = optimizer.query(X)
40+
optimizer.teach(X[query_idx].reshape(1, -1), y[query_idx].reshape(1, -1))

0 commit comments

Comments
 (0)