BayesOpt
demo_distance.py
1 #!/usr/bin/env python
2 # -------------------------------------------------------------------------
3 # This file is part of BayesOpt, an efficient C++ library for
4 # Bayesian optimization.
5 #
6 # Copyright (C) 2011-2015 Ruben Martinez-Cantin <rmcantin@unizar.es>
7 #
8 # BayesOpt is free software: you can redistribute it and/or modify it
9 # under the terms of the GNU Affero General Public License as published by
10 # the Free Software Foundation, either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # BayesOpt is distributed in the hope that it will be useful, but
14 # WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU Affero General Public License for more details.
17 #
18 # You should have received a copy of the GNU Affero General Public License
19 # along with BayesOpt. If not, see <http://www.gnu.org/licenses/>.
20 # ------------------------------------------------------------------------
21 
22 import bayesopt
23 from bayesoptmodule import BayesOptContinuous
24 import numpy as np
25 
26 from time import clock
27 
28 # Function for testing.
29 def testfunc(Xin):
30  total = 5.0
31  for value in Xin:
32  total = total + (value -0.33)*(value-0.33)
33 
34  return total
35 
36 # Class for OO testing.
38  def evaluateSample(self,Xin):
39  return testfunc(Xin)
40 
41 
42 # Let's define the parameters
43 # For different options: see parameters.h and cpp
44 # If a parameter is not define, it will be automatically set
45 # to a default value.
46 params = {}
47 params['n_iterations'] = 50
48 params['n_init_samples'] = 20
49 params['crit_name'] = "cSum(cEI,cDistance)"
50 params['crit_params'] = [1, 0.5]
51 params['kernel_name'] = "kMaternISO3"
52 print("Callback implementation")
53 
54 n = 2 # n dimensions
55 lb = np.zeros((n,))
56 ub = np.ones((n,))
57 
58 start = clock()
59 
60 mvalue, x_out, error = bayesopt.optimize(testfunc, n, lb, ub, params)
61 
62 print("Result", x_out)
63 print("Seconds", clock() - start)
64 
65 
66 print("OO implementation")
67 bo_test = BayesOptTest(n)
68 bo_test.parameters = params
69 bo_test.lower_bound = lb
70 bo_test.upper_bound = ub
71 
72 start = clock()
73 mvalue, x_out, error = bo_test.optimize()
74 
75 print("Result", x_out)
76 print("Seconds", clock() - start)
77 
78 
79 print("Callback discrete implementation")
80 x_set = np.random.rand(100,n)
81 start = clock()
82 
83 mvalue, x_out, error = bayesopt.optimize_discrete(testfunc, x_set, params)
84 
85 print("Result", x_out)
86 print("Seconds", clock() - start)
87 
88 value = np.array([testfunc(i) for i in x_set])
89 print("Optimun", x_set[value.argmin()])
Python Module for BayesOptContinuous.