SHOGUN  3.2.1
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
TanimotoKernelNormalizer.h
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 Soeren Sonnenburg
8  * Copyright (C) 2008-2009 Fraunhofer Institute FIRST and Max-Planck-Society
9  */
10 
11 #ifndef _TANIMOTOKERNELNORMALIZER_H___
12 #define _TANIMOTOKERNELNORMALIZER_H___
13 
14 #include <shogun/lib/config.h>
15 
18 
19 namespace shogun
20 {
29 {
30  public:
35  CTanimotoKernelNormalizer(bool use_opt_diag=false)
36  : CKernelNormalizer(), diag_lhs(NULL), diag_rhs(NULL),
38  {
39  }
40 
43  {
44  SG_FREE(diag_lhs);
45  SG_FREE(diag_rhs);
46  }
47 
50  virtual bool init(CKernel* k)
51  {
52  ASSERT(k)
53  int32_t num_lhs=k->get_num_vec_lhs();
54  int32_t num_rhs=k->get_num_vec_rhs();
55  ASSERT(num_lhs>0)
56  ASSERT(num_rhs>0)
57 
58  CFeatures* old_lhs=k->lhs;
59  CFeatures* old_rhs=k->rhs;
60 
61  k->lhs=old_lhs;
62  k->rhs=old_lhs;
63  bool r1=alloc_and_compute_diag(k, diag_lhs, num_lhs);
64 
65  k->lhs=old_rhs;
66  k->rhs=old_rhs;
67  bool r2=alloc_and_compute_diag(k, diag_rhs, num_rhs);
68 
69  k->lhs=old_lhs;
70  k->rhs=old_rhs;
71 
72  return r1 && r2;
73  }
74 
81  float64_t value, int32_t idx_lhs, int32_t idx_rhs)
82  {
83  float64_t diag_sum=diag_lhs[idx_lhs]*diag_rhs[idx_rhs];
84  return value/(diag_sum-value);
85  }
86 
91  virtual float64_t normalize_lhs(float64_t value, int32_t idx_lhs)
92  {
93  SG_ERROR("linadd not supported with Tanimoto normalization.\n")
94  return 0;
95  }
96 
101  virtual float64_t normalize_rhs(float64_t value, int32_t idx_rhs)
102  {
103  SG_ERROR("linadd not supported with Tanimoto normalization.\n")
104  return 0;
105  }
106 
112  virtual const char* get_name() const {
113  return "TanimotoKernelNormalizer"; }
114 
115  public:
120  bool alloc_and_compute_diag(CKernel* k, float64_t* &v, int32_t num)
121  {
122  SG_FREE(v);
123  v=SG_MALLOC(float64_t, num);
124 
125  for (int32_t i=0; i<num; i++)
126  {
127  if (k->get_kernel_type() == K_COMMWORDSTRING)
128  {
130  v[i]=((CCommWordStringKernel*) k)->compute_diag(i);
131  else
132  v[i]=((CCommWordStringKernel*) k)->compute_helper(i,i, true);
133  }
134  else
135  v[i]=k->compute(i,i);
136 
137  if (v[i]==0.0)
138  v[i]=1e-16; /* avoid divide by zero exception */
139  }
140 
141  return (v!=NULL);
142  }
143 
144  protected:
151 };
152 }
153 #endif

SHOGUN Machine Learning Toolbox - Documentation