SHOGUN  3.2.1
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
JensenShannonKernel.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) 2012 Viktor Gal
8  * Copyright (C) 2012 Viktor Gal
9  */
10 
11 #include <shogun/lib/common.h>
14 #include <shogun/io/SGIO.h>
15 
16 using namespace shogun;
17 
19 : CDotKernel(0)
20 {
21 }
22 
24 : CDotKernel(size)
25 {
26 }
27 
30 : CDotKernel(size)
31 {
32  init(l,r);
33 }
34 
36 {
37  cleanup();
38 }
39 
40 bool CJensenShannonKernel::init(CFeatures* l, CFeatures* r)
41 {
42  bool result=CDotKernel::init(l,r);
44  return result;
45 }
46 
47 float64_t CJensenShannonKernel::compute(int32_t idx_a, int32_t idx_b)
48 {
49  int32_t alen, blen;
50  bool afree, bfree;
51 
52  float64_t* avec=
53  ((CDenseFeatures<float64_t>*) lhs)->get_feature_vector(idx_a, alen, afree);
54  float64_t* bvec=
55  ((CDenseFeatures<float64_t>*) rhs)->get_feature_vector(idx_b, blen, bfree);
56  ASSERT(alen==blen)
57 
58  float64_t result=0;
59 
60  /* calcualte Jensen-Shannon kernel */
61  for (int32_t i=0; i<alen; i++) {
62  float64_t a_i = 0, b_i = 0;
63  float64_t ab = avec[i]+bvec[i];
64  if (avec[i] != 0)
65  a_i = avec[i] * CMath::log2(ab/avec[i]);
66  if (bvec[i] != 0)
67  b_i = bvec[i] * CMath::log2(ab/bvec[i]);
68 
69  result += 0.5*(a_i + b_i);
70  }
71 
72  ((CDenseFeatures<float64_t>*) lhs)->free_feature_vector(avec, idx_a, afree);
73  ((CDenseFeatures<float64_t>*) rhs)->free_feature_vector(bvec, idx_b, bfree);
74 
75  return result;
76 }
77 

SHOGUN Machine Learning Toolbox - Documentation