SHOGUN  v1.1.0
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
CosineDistance.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) 2008-2009 Christian Gehl
8  * Copyright (C) 2008-2009 Fraunhofer Institute FIRST
9  */
10 
11 #include <shogun/lib/config.h>
12 #include <shogun/lib/common.h>
13 #include <shogun/io/SGIO.h>
17 
18 using namespace shogun;
19 
22 {
23 }
24 
27 {
28  init(l, r);
29 }
30 
32 {
33  cleanup();
34 }
35 
36 bool CCosineDistance::init(CFeatures* l, CFeatures* r)
37 {
39 }
40 
42 {
43 }
44 
45 float64_t CCosineDistance::compute(int32_t idx_a, int32_t idx_b)
46 {
47  int32_t alen, blen;
48  bool afree, bfree;
49 
50  float64_t* avec=
51  ((CSimpleFeatures<float64_t>*) lhs)->get_feature_vector(idx_a, alen, afree);
52  float64_t* bvec=
53  ((CSimpleFeatures<float64_t>*) rhs)->get_feature_vector(idx_b, blen, bfree);
54 
55  ASSERT(alen==blen);
56  float64_t s=0;
57  float64_t ab=0;
58  float64_t sa=0;
59  float64_t sb=0;
60  {
61  for (int32_t i=0; i<alen; i++)
62  {
63  ab+=avec[i]*bvec[i];
64  sa+=pow(fabs(avec[i]),2);
65  sb+=pow(fabs(bvec[i]),2);
66  }
67  }
68 
69  ((CSimpleFeatures<float64_t>*) lhs)->free_feature_vector(avec, idx_a, afree);
70  ((CSimpleFeatures<float64_t>*) rhs)->free_feature_vector(bvec, idx_b, bfree);
71 
72  s=sqrt(sa)*sqrt(sb);
73 
74  // trap division by zero
75  if(s==0)
76  return 0;
77 
78  s=1-ab/s;
79  if(s<0)
80  return 0;
81  else
82  return s ;
83 }

SHOGUN Machine Learning Toolbox - Documentation