SHOGUN  3.2.1
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
WeightedDegreeRBFKernel.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>
14 #include <shogun/io/SGIO.h>
15 
16 using namespace shogun;
17 
19 : CDotKernel(), width(1), degree(1), weights(0)
20 {
21 }
22 
23 
24 CWeightedDegreeRBFKernel::CWeightedDegreeRBFKernel(int32_t size, float64_t w, int32_t d, int32_t nof_prop)
25 : CDotKernel(size), width(w), degree(d), nof_properties(nof_prop), weights(0)
26 {
28 }
29 
31  CDenseFeatures<float64_t>* l, CDenseFeatures<float64_t>* r, float64_t w, int32_t d, int32_t nof_prop, int32_t size)
32 : CDotKernel(size), width(w), degree(d), nof_properties(nof_prop), weights(0)
33 {
35  init(l,r);
36 }
37 
39 {
40  SG_FREE(weights);
41  weights=NULL;
42 }
43 
44 bool CWeightedDegreeRBFKernel::init(CFeatures* l, CFeatures* r)
45 {
46  CDotKernel::init(l, r);
47  SG_DEBUG("Initialized WeightedDegreeRBFKernel (%p).\n", this)
48  return init_normalizer();
49 }
50 
52 {
53  ASSERT(degree>0)
54 
55  if (weights!=0) SG_FREE(weights);
56  weights=SG_MALLOC(float64_t, degree);
57  if (weights)
58  {
59  int32_t i;
60  float64_t sum=0;
61  for (i=0; i<degree; i++)
62  {
63  weights[i]=degree-i;
64  sum+=weights[i];
65  }
66  for (i=0; i<degree; i++)
67  weights[i]/=sum;
68 
69  SG_DEBUG("Initialized weights for WeightedDegreeRBFKernel (%p).\n", this)
70  return true;
71  }
72  else
73  return false;
74 }
75 
76 
77 float64_t CWeightedDegreeRBFKernel::compute(int32_t idx_a, int32_t idx_b)
78 {
79  int32_t alen, blen;
80  bool afree, bfree;
81 
82  float64_t* avec=((CDenseFeatures<float64_t>*) lhs)->get_feature_vector(idx_a, alen, afree);
83  float64_t* bvec=((CDenseFeatures<float64_t>*) rhs)->get_feature_vector(idx_b, blen, bfree);
84  ASSERT(alen==blen)
85  ASSERT(alen%nof_properties == 0)
86 
87  float64_t result=0;
88 
89  for (int32_t i=0; i<alen; i+=nof_properties)
90  {
91  float64_t resulti = 0.0;
92 
93  for (int32_t d=0; (i+(d*nof_properties)<alen) && (d<degree); d++)
94  {
95  float64_t resultid = 0.0;
96  int32_t limit = (d + 1 ) * nof_properties;
97  for (int32_t k=0; k < limit; k++)
98  {
99  resultid+=CMath::sq(avec[i+k]-bvec[i+k]);
100  }
101 
102  resulti += weights[d] * exp(-resultid/width);
103  }
104 
105  result+=resulti ;
106  }
107 
108  return result;
109 }

SHOGUN Machine Learning Toolbox - Documentation