BayesOpt
kernel_hamming.hpp
1 /*
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 
23 #ifndef _KERNEL_HAMMING_HPP_
24 #define _KERNEL_HAMMING_HPP_
25 
27 
28 namespace bayesopt
29 {
30 
33 
38  {
39  public:
40  void init(size_t input_dim)
41  { n_params = 1; n_inputs = input_dim; };
42 
43  size_t hammingDistance(const vectori& s1, const vectori& s2)
44  {
45  size_t hdist = 0;
46  vectori::const_iterator i1;
47  vectori::const_iterator i2;
48  for( i1 = s1.begin(), i2 = s2.begin();
49  i1 < s1.end() && i2 < s2.end();
50  ++i1, ++i2 )
51  {
52  hdist += (*i1 == *i2) ? 0 : 1;
53  }
54  return hdist;
55  }
56 
57  double operator()(const vectord &x1, const vectord &x2)
58  {
59  const size_t n = x1.size();
60  const double coef = -params(0)/2.0;
61  vectori s1(n);
62  vectori s2(n);
63 
64  for(size_t i=0; i<n; ++i)
65  {
66  // We add 0.5 to avoid floating point approximation errors
67  s1(i) = static_cast<int>(x1(i)+0.5);
68  s2(i) = static_cast<int>(x2(i)+0.5);
69  }
70 
71  const double dist = static_cast<double>(hammingDistance(s1,s2));
72  return std::exp(coef*dist*dist);
73  };
74 
75  double gradient(const vectord &x1, const vectord &x2,
76  size_t component)
77  { return 0.0; };
78  };
79 
81 
82 } //namespace bayesopt
83 
84 #endif
Namespace of the library interface.
Definition: using.dox:1
Kernel for categorical data.
Atomic (simple) kernel functions.
Abstract class for an atomic kernel.