UFJF - Machine Learning Toolkit  0.51.8
PerceptronCommittee.hpp
1 #pragma once
2 
3 #include "Ensemble.hpp"
6 
7 namespace mltk{
8  namespace ensemble {
9  template<typename T>
10  class PerceptronCommittee : public Ensemble<T>, public classifier::Classifier<T> {
11  private:
12  size_t n = 0;
13  double epslon = -1;
14  public:
15  explicit PerceptronCommittee(const Data<T> &samples, size_t size = 10, double epslon = -1) : n(size),
16  epslon(epslon) {
17  this->samples = std::make_shared<Data<T> >(samples);
18  }
19 
20  bool train() override {
21  this->m_learners.resize(n);
22  for (size_t i = 0; i < n; i++) {
23  this->m_learners[i] = std::make_shared<classifier::BalancedPerceptron<T>>();
24  this->m_learners[i]->setSamples(this->samples);
25  this->m_learners[i]->train();
26  }
27  return true;
28  }
29 
30  double evaluate(const Point<T> &p, bool raw_value = false) override {
31  auto _classes = this->samples->classes();
32  mltk::Point<double> votes(_classes.size(), 0.0);
33 
34  for (size_t i = 0; i < this->m_learners.size(); i++) {
35  auto pred = this->m_learners[i]->evaluate(p);
36 
37  // get prediction position
38  size_t pred_pos = std::find_if(_classes.begin(), _classes.end(), [&pred](const auto &a) {
39  return (a == pred);
40  }) - _classes.begin();
41  // count prediction as a vote
42  votes[pred_pos] += 1;
43  }
44  size_t max_votes = std::max_element(votes.X().begin(), votes.X().end()) - votes.X().begin();
45  return _classes[max_votes];
46  }
47 
48  std::string getFormulationString() override {
49  return "Primal";
50  }
51  };
52  }
53 
54 }
const std::vector< int > classes() const
Returns a vector containing the numeric values of the classes.
Definition: Data.hpp:1831
std::shared_ptr< Data< T > > samples
Samples used in the model training.
Definition: Learner.hpp:21
Rep const & X() const
Returns the attributes representation of the point (std::vector by default).
Definition: Point.hpp:139
Definition: classifier/Classifier.hpp:17
Namespace for ensemble methods.
Definition: ensemble/Ensemble.hpp:16
std::vector< LearnerPointer< T > > m_learners
Pointer to base learner used by the ensemble method.
Definition: ensemble/Ensemble.hpp:22
Definition: PerceptronCommittee.hpp:10
bool train() override
Function that execute the training phase of a Learner.
Definition: PerceptronCommittee.hpp:20
double evaluate(const Point< T > &p, bool raw_value=false) override
Returns the class of a feature point based on the trained Learner.
Definition: PerceptronCommittee.hpp:30
std::string getFormulationString() override
getFormulationString Returns a string that represents the formulation of the learner (Primal or Dual)...
Definition: PerceptronCommittee.hpp:48
UFJF-MLTK main namespace for core functionalities.
Definition: classifier/Classifier.hpp:11