SHOGUN
v3.0.0
Main Page
Related Pages
Modules
Classes
Files
File List
File Members
All
Classes
Namespaces
Files
Functions
Variables
Typedefs
Enumerations
Enumerator
Friends
Macros
Groups
Pages
src
shogun
kernel
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
>
12
#include <
shogun/kernel/Chi2Kernel.h
>
13
#include <
shogun/features/Features.h
>
14
#include <
shogun/io/SGIO.h
>
15
16
using namespace
shogun;
17
18
void
19
CChi2Kernel::init()
20
{
21
SG_ADD
(&
width
,
"width"
,
"Kernel width."
,
MS_AVAILABLE
);
22
}
23
24
CChi2Kernel::CChi2Kernel
()
25
:
CDotKernel
(0), width(0)
26
{
27
init();
28
}
29
30
CChi2Kernel::CChi2Kernel
(int32_t size,
float64_t
w)
31
:
CDotKernel
(size), width(w)
32
{
33
init();
34
}
35
36
CChi2Kernel::CChi2Kernel
(
37
CDenseFeatures<float64_t>
* l,
CDenseFeatures<float64_t>
* r,
float64_t
w, int32_t size)
38
:
CDotKernel
(size), width(w)
39
{
40
init();
41
init(l,r);
42
}
43
44
CChi2Kernel::~CChi2Kernel
()
45
{
46
cleanup
();
47
}
48
49
bool
CChi2Kernel::init(
CFeatures
* l,
CFeatures
* r)
50
{
51
bool
result=CDotKernel::init(l,r);
52
init_normalizer
();
53
return
result;
54
}
55
56
float64_t
CChi2Kernel::compute
(int32_t idx_a, int32_t idx_b)
57
{
58
int32_t alen, blen;
59
bool
afree, bfree;
60
61
float64_t
* avec=
62
((
CDenseFeatures<float64_t>
*)
lhs
)->get_feature_vector(idx_a, alen, afree);
63
float64_t
* bvec=
64
((
CDenseFeatures<float64_t>
*)
rhs
)->get_feature_vector(idx_b, blen, bfree);
65
ASSERT
(alen==blen)
66
67
float64_t
result=0;
68
for
(int32_t i=0; i<alen; i++)
69
{
70
float64_t
n=avec[i]-bvec[i];
71
float64_t
d=avec[i]+bvec[i];
72
if
(d!=0)
73
result+=n*n/d;
74
}
75
76
result=exp(-result/
width
);
77
78
((
CDenseFeatures<float64_t>
*)
lhs
)->free_feature_vector(avec, idx_a, afree);
79
((
CDenseFeatures<float64_t>
*)
rhs
)->free_feature_vector(bvec, idx_b, bfree);
80
81
return
result;
82
}
83
84
float64_t
CChi2Kernel::get_width
()
85
{
86
return
width
;
87
}
88
89
CChi2Kernel
*
CChi2Kernel::obtain_from_generic
(
CKernel
* kernel)
90
{
91
if
(kernel->
get_kernel_type
()!=
K_CHI2
)
92
{
93
SG_SERROR
(
"Provided kernel is "
94
"not of type CChi2Kernel!\n"
);
95
}
96
97
/* since an additional reference is returned */
98
SG_REF
(kernel);
99
return
(
CChi2Kernel
*)
kernel
;
100
}
SHOGUN
Machine Learning Toolbox - Documentation