GestureRecognitionToolkit  Version: 0.1.0
The Gesture Recognition Toolkit (GRT) is a cross-platform, open-source, c++ machine learning library for real-time gesture recognition.
LinearLeastSquares.h
Go to the documentation of this file.
1 
33 #ifndef GRT_LINEAR_LEAST_SQUARES_HEADER
34 #define GRT_LINEAR_LEAST_SQUARES_HEADER
35 
36 #include "../../CoreModules/MLBase.h"
37 
38 GRT_BEGIN_NAMESPACE
39 
40 class LinearLeastSquares : public MLBase{
41 public:
43  classType = "LinearLeastSquares";
44  infoLog.setProceedingText("[LinearLeastSquares]");
45  debugLog.setProceedingText("[DEBUG LinearLeastSquares]");
46  errorLog.setProceedingText("[ERROR LinearLeastSquares]");
47  trainingLog.setProceedingText("[TRAINING LinearLeastSquares]");
48  warningLog.setProceedingText("[WARNING LinearLeastSquares]");
49 
50  m = 0;
51  b = 0;
52  r = 0;
53  }
54 
55  virtual ~LinearLeastSquares(){
56 
57  }
58 
59  bool solve( const VectorFloat &x, const VectorFloat &y ){
60 
61  if( x.size() == 0 && y.size() == 0 ){
62  warningLog << "solve( const VectorFloat &x, const VectorFloat &y ) - Failed to compute solution, input vectors are empty!" << endl;
63  return false;
64  }
65 
66  if( x.size() != y.size() ){
67  warningLog << "solve( const VectorFloat &x, const VectorFloat &y ) - Failed to compute solution, input vectors do not have the same size!" << endl;
68  return false;
69  }
70 
71  const unsigned int N = (unsigned int)x.size();
72  Float sumx = 0.0; //Stores the sum of x
73  Float sumx2 = 0.0; //Stores the sum of x^2
74  Float sumxy = 0.0; //Stores the sum of x * y
75  Float sumy = 0.0; //Stores the sum of y
76  Float sumy2 = 0.0; //Stores the sum of y**2
77  Float denom = 0;
78 
79  m = 0;
80  b = 0;
81  r = 0;
82 
83  for(unsigned int i=0; i<N; i++){
84  sumx += x[i];
85  sumx2 += SQR(x[i]);
86  sumxy += x[i] * y[i];
87  sumy += y[i];
88  sumy2 += SQR(y[i]);
89  }
90 
91  denom = (n * sumx2 - sqr(sumx));
92  if (denom == 0) {
93  // singular matrix. can't solve the problem.
94  warningLog << "solve( const VectorFloat &x, const VectorFloat &y ) - Failed to compute solution, singular matrix detected!" << endl;
95  return false;
96  }
97 
98  m = (n * sumxy - sumx * sumy) / denom;
99  b = (sumy * sumx2 - sumx * sumxy) / denom;
100 
101  //compute correlation coeff
102  r = (sumxy - sumx * sumy / n) / sqrt( (sumx2 - sqr(sumx)/n) * (sumy2 - sqr(sumy)/n) );
103 
104  return true;
105  }
106 
107 protected:
108 
109  Float m;
110  Float b;
111  Float r;
112 
113 };
114 
115 GRT_END_NAMESPACE
116 
117 #endif //GRT_MEAN_SHIFT_HEADER
Definition: MLBase.h:70