UFJF - Machine Learning Toolkit  0.51.8
KNNRegressor.hpp
1 #pragma once
2 
3 
4 #include "PrimalRegressor.hpp"
5 #include "ufjfmltk/core/DistanceMetric.hpp"
6 #include <cassert>
7 
8 namespace mltk{
9  namespace regressor {
13  template<typename T = double, typename Callable = metrics::dist::Euclidean <T> >
14  class KNNRegressor : public PrimalRegressor<T> {
15  private:
17  size_t k;
19  Callable dist_function;
20  public:
21  KNNRegressor() = default;
22  explicit KNNRegressor(const Data<T>& _samples, size_t _k=3):
23  PrimalRegressor<T> (mltk::make_data<T>(_samples)), k(_k) {}
24  explicit KNNRegressor(size_t _k=3): k(_k) {}
25 
26  bool train() override{
27  return true;
28  }
29 
30  std::string getFormulationString() override{
31  return "Regressor";
32  }
33 
34  double evaluate(const Point <T> &p, bool raw_value = false) override{
35  auto points = this->samples->points();
36  std::vector<double> distances(this->samples->size());
37  std::vector<int> classes = this->samples->classes();
38  std::vector<size_t> idx(distances.size()), freq(classes.size());
39  auto p0 = std::make_shared<Point<T> >(p);
40  // fill the index vector
41  std::iota(idx.begin(), idx.end(), 0);
42 
43  // compute the metrics from the sample to be evaluated to the samples vector
44  std::transform(points.begin(), points.end(), distances.begin(),
45  [p0, this](const std::shared_ptr<Point<T> > q) {
46  return this->dist_function(*p0, *q);
47  });
48  // sort the index vector by the metrics from the sample to be evaluated
49  std::stable_sort(idx.begin(), idx.end(), [&distances](size_t i1, size_t i2) {
50  return distances[i1] < distances[i2];
51  });
52 
53  double sum = 0.0;
54 
55  // sum the values in the k nearest neighbors and return the average
56  for (size_t j = 0; j < this->k; j++) {
57  sum += points[idx[j]]->Y();
58  }
59  return sum / this->k;
60  }
61  };
62  }
63 }
std::shared_ptr< Data< T > > samples
Samples used in the model training.
Definition: Learner.hpp:21
Wrapper for the implementation of the K-Nearest Neighbors regression algorithm.
Definition: KNNRegressor.hpp:14
double evaluate(const Point< T > &p, bool raw_value=false) override
Returns the class of a feature point based on the trained Learner.
Definition: KNNRegressor.hpp:34
std::string getFormulationString() override
getFormulationString Returns a string that represents the formulation of the learner (Primal or Dual)...
Definition: KNNRegressor.hpp:30
bool train() override
Function that execute the training phase of a Learner.
Definition: KNNRegressor.hpp:26
Definition: PrimalRegressor.hpp:11
UFJF-MLTK main namespace for core functionalities.
Definition: classifier/Classifier.hpp:11