SHOGUN  6.1.3
KNNSolver.cpp
Go to the documentation of this file.
1 /* This software is distributed under BSD 3-clause license (see LICENSE file).
2  *
3  * Copyright (c) 2012-2013 Sergey Lisitsyn
4  */
5 
6 #include <shogun/labels/Labels.h>
7 #include <shogun/lib/Time.h>
9 #include <shogun/lib/Signal.h>
11 
12 using namespace shogun;
13 
14 CKNNSolver::CKNNSolver(const int32_t k, const float64_t q, const int32_t num_classes, const int32_t min_label, const SGVector<int32_t> train_labels)
16 {
17  init();
18 
19  m_k=k;
20  m_q=q;
21  m_num_classes=num_classes;
22  m_min_label=min_label;
23  m_train_labels=train_labels;
24 }
25 
26 void CKNNSolver::init()
27 {
28  m_k=3;
29  m_q=1.0;
30  m_num_classes=0;
31  m_min_label=0;
33 }
34 
35 int32_t CKNNSolver::choose_class(float64_t* classes, const int32_t* train_lab) const
36 {
37  memset(classes, 0, sizeof(float64_t)*m_num_classes);
38 
39  float64_t multiplier = m_q;
40  for (int32_t j=0; j<m_k; j++)
41  {
42  classes[train_lab[j]]+= multiplier;
43  multiplier*= multiplier;
44  }
45 
46  //choose the class that got 'outputted' most often
47  int32_t out_idx=0;
48  float64_t out_max=0;
49 
50  for (index_t j=0; j<m_num_classes; j++)
51  {
52  if (out_max< classes[j])
53  {
54  out_idx= j;
55  out_max= classes[j];
56  }
57  }
58 
59  return out_idx;
60 }
61 
62 void CKNNSolver::choose_class_for_multiple_k(int32_t* output, int32_t* classes, const int32_t* train_lab, const int32_t step) const
63 {
64  //compute histogram of class outputs of the first k nearest neighbours
65  memset(classes, 0, sizeof(int32_t)*m_num_classes);
66 
67  for (index_t j=0; j<m_k; j++)
68  {
69  classes[train_lab[j]]++;
70 
71  //choose the class that got 'outputted' most often
72  int32_t out_idx=0;
73  int32_t out_max=0;
74 
75  for (index_t c=0; c<m_num_classes; c++)
76  {
77  if (out_max< classes[c])
78  {
79  out_idx= c;
80  out_max= classes[c];
81  }
82  }
83 
84  output[j*step]=out_idx+m_min_label;
85  }
86 }
int32_t m_k
the k parameter in KNN
Definition: KNNSolver.h:94
int32_t choose_class(float64_t *classes, const int32_t *train_lab) const
Definition: KNNSolver.cpp:35
SGVector< int32_t > m_train_labels
Definition: KNNSolver.h:106
int32_t index_t
Definition: common.h:72
A generic DistanceMachine interface.
double float64_t
Definition: common.h:60
int32_t m_num_classes
number of classes (i.e. number of values labels can take)
Definition: KNNSolver.h:100
int32_t m_min_label
smallest label, i.e. -1
Definition: KNNSolver.h:103
all of classes and functions are contained in the shogun namespace
Definition: class_list.h:18
void choose_class_for_multiple_k(int32_t *output, int32_t *classes, const int32_t *train_lab, const int32_t step) const
Definition: KNNSolver.cpp:62
float64_t m_q
parameter q of rank weighting
Definition: KNNSolver.h:97

SHOGUN Machine Learning Toolbox - Documentation