SHOGUN  v1.1.0
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
Chi2Kernel.cpp
Go to the documentation of this file.
1 /*
2  * This program is free software; you can redistribute it and/or modify
3  * it under the terms of the GNU General Public License as published by
4  * the Free Software Foundation; either version 3 of the License, or
5  * (at your option) any later version.
6  *
7  * Written (W) 1999-2009 Soeren Sonnenburg
8  * Copyright (C) 1999-2009 Fraunhofer Institute FIRST and Max-Planck-Society
9  */
10 
11 #include <shogun/lib/common.h>
15 #include <shogun/io/SGIO.h>
16 
17 using namespace shogun;
18 
19 void
20 CChi2Kernel::init()
21 {
22  m_parameters->add(&width, "width");
23 }
24 
26 : CDotKernel(0), width(0)
27 {
28  init();
29 }
30 
32 : CDotKernel(size), width(w)
33 {
34  init();
35 }
36 
39 : CDotKernel(size), width(w)
40 {
41  init();
42  init(l,r);
43 }
44 
46 {
47  cleanup();
48 }
49 
50 bool CChi2Kernel::init(CFeatures* l, CFeatures* r)
51 {
52  bool result=CDotKernel::init(l,r);
54  return result;
55 }
56 
57 float64_t CChi2Kernel::compute(int32_t idx_a, int32_t idx_b)
58 {
59  int32_t alen, blen;
60  bool afree, bfree;
61 
62  float64_t* avec=
63  ((CSimpleFeatures<float64_t>*) lhs)->get_feature_vector(idx_a, alen, afree);
64  float64_t* bvec=
65  ((CSimpleFeatures<float64_t>*) rhs)->get_feature_vector(idx_b, blen, bfree);
66  ASSERT(alen==blen);
67 
68  float64_t result=0;
69  for (int32_t i=0; i<alen; i++)
70  {
71  float64_t n=avec[i]-bvec[i];
72  float64_t d=avec[i]+bvec[i];
73  if (d!=0)
74  result+=n*n/d;
75  }
76 
77  result=exp(-result/width);
78 
79  ((CSimpleFeatures<float64_t>*) lhs)->free_feature_vector(avec, idx_a, afree);
80  ((CSimpleFeatures<float64_t>*) rhs)->free_feature_vector(bvec, idx_b, bfree);
81 
82  return result;
83 }

SHOGUN Machine Learning Toolbox - Documentation