BayesOpt
demo_quad.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 sys
23 import bayesopt
24 from bayesoptmodule import BayesOptContinuous
25 import numpy as np
26 
27 from time import clock
28 
29 # Python3 compat
30 if hasattr(__builtins__, 'raw_input'):
31  input = raw_input
32 
33 # Function for testing.
34 def testfunc(Xin):
35  total = 5.0
36  for value in Xin:
37  total = total + (value - 0.33) * (value - 0.33)
38 
39  return total
40 
41 # Class for OO testing.
43  def evaluateSample(self,Xin):
44  return testfunc(Xin)
45 
46 
47 # Let's define the parameters
48 # For different options: see parameters.h and cpp
49 # If a parameter is not define, it will be automatically set
50 # to a default value.
51 params = {}
52 params['n_iterations'] = 50
53 params['n_iter_relearn'] = 5
54 params['n_init_samples'] = 2
55 
56 print("Callback implementation")
57 
58 n = 5 # n dimensions
59 lb = np.zeros((n,))
60 ub = np.ones((n,))
61 
62 start = clock()
63 mvalue, x_out, error = bayesopt.optimize(testfunc, n, lb, ub, params)
64 
65 print("Result", mvalue, "at", x_out)
66 print("Running time:", clock() - start, "seconds")
67 input('Press INTRO to continue')
68 
69 print("OO implementation")
70 bo_test = BayesOptTest(n)
71 bo_test.parameters = params
72 bo_test.lower_bound = lb
73 bo_test.upper_bound = ub
74 
75 start = clock()
76 mvalue, x_out, error = bo_test.optimize()
77 
78 print("Result", mvalue, "at", x_out)
79 print("Running time:", clock() - start, "seconds")
80 input('Press INTRO to continue')
81 
82 print("Callback discrete implementation")
83 x_set = np.random.rand(100, n)
84 start = clock()
85 
86 mvalue, x_out, error = bayesopt.optimize_discrete(testfunc, x_set, params)
87 
88 print("Result", mvalue, "at", x_out)
89 print("Running time:", clock() - start, "seconds")
90 
91 value = np.array([testfunc(i) for i in x_set])
92 print("Optimum", value.min(), "at", x_set[value.argmin()])
Python Module for BayesOptContinuous.