Machine learning algorithms in C++
LeastSquares.hpp
Go to the documentation of this file.
1 //
2 // Created by dodo on 11/10/17.
3 //
4 
5 #ifndef MACHINE_LEARNING_LEASTSQUARES_HPP
6 #define MACHINE_LEARNING_LEASTSQUARES_HPP
7 
8 #include <utility>
9 #include <vector>
10 #include "../include/matrix/Matrix.hpp"
11 
12 using namespace std;
13 
17 class LeastSquares {
18  public:
20  REGULAR, WEIGHTED
21  };
22  private:
23  MatrixD X, y, coefs, residuals;
25  public :
26  LeastSquares(MatrixD data, MatrixD labels, RegressionType regType = REGULAR) : regressionType(regType) {
27  X = std::move(data);
28  X.addColumn(MatrixD::ones(X.nRows(), 1), 0);
29  y = std::move(labels);
30  }
31 
33  return regressionType;
34  }
35 
36  void setRegressionType(RegressionType regressionType) {
37  this->regressionType = regressionType;
38  }
39 
40  void fit() {
41  // The formula for least squares is the following
42  // B^ = (X'X)^{-1} X'y
43  // Weighted least squares is like this
44  // B^ = (X'WX)^{-1} X'Wy
45  // where W is a Square matrix with the weights in the diagonal
46  // if W = I, weighted least squares behaves just like ordinary least squares
47 
48  MatrixD W;
49  if (regressionType == WEIGHTED) {
50  MatrixD vars = X.transpose().var();
51  W = vars.asDiagonal();
52  } else
53  W = MatrixD::identity(X.nRows());
54 
55  MatrixD Xt = X.transpose();
56  MatrixD first_part = Xt * W * X;
57  first_part = first_part.inverse();
58  MatrixD second_part = Xt * W * y;
59  coefs = first_part * second_part;
60 
61  residuals = y - (X * coefs);
62  residuals = residuals.transpose() * residuals;
63  }
64 
65  MatrixD predict(MatrixD m) {
66  m.addColumn(MatrixD::ones(1, X.nCols()), 0);
67  return m.transpose() * coefs;
68  }
69 
70  const MatrixD &getCoefs() const {
71  return coefs;
72  }
73 
74  const MatrixD &getResiduals() const {
75  return residuals;
76  }
77 };
78 
79 #endif //MACHINE_LEARNING_LEASTSQUARES_HPP
RegressionType regressionType
Ordinary and weighted Least squares algorithm.
RegressionType getRegressionType() const
k-nearest neighbors algorithm, able to do regression and classification
void setRegressionType(RegressionType regressionType)
LeastSquares(MatrixD data, MatrixD labels, RegressionType regType=REGULAR)
const MatrixD & getResiduals() const
const MatrixD & getCoefs() const
MatrixD predict(MatrixD m)