mlpack
r2_score_impl.hpp
Go to the documentation of this file.
1 
12 #ifndef MLPACK_CORE_CV_METRICS_R2SCORE_IMPL_HPP
13 #define MLPACK_CORE_CV_METRICS_R2SCORE_IMPL_HPP
14 
15 namespace mlpack {
16 namespace cv {
17 
18 template<bool AdjustedR2>
19 template<typename MLAlgorithm, typename DataType, typename ResponsesType>
20 double R2Score<AdjustedR2>::Evaluate(MLAlgorithm& model,
21  const DataType& data,
22  const ResponsesType& responses)
23 {
24  util::CheckSameSizes(data, (size_t) responses.n_cols, "R2Score::Evaluate()",
25  "responses");
26 
27  ResponsesType predictedResponses;
28  // Taking Predicted Output from the model.
29  model.Predict(data, predictedResponses);
30  // Mean value of response.
31  double meanResponses = arma::mean(responses);
32 
33  // Calculate the numerator i.e. residual sum of squares.
34  double residualSumSquared = arma::accu(arma::square(responses -
35  predictedResponses));
36 
37  // Calculate the denominator i.e.total sum of squares.
38  double totalSumSquared = arma::accu(arma::square(responses - meanResponses));
39 
40  // Handling undefined R2 Score when both denominator and numerator is 0.0.
41  if (residualSumSquared == 0.0)
42  return totalSumSquared ? 1.0 : DBL_MIN;
43 
44  if (AdjustedR2)
45  {
46  // Returning adjusted R-squared.
47  double rsq = 1 - (residualSumSquared / totalSumSquared);
48  return (1 - ((1 - rsq) * ((data.n_cols - 1) /
49  (data.n_cols - data.n_rows - 1))));
50  }
51  else
52  {
53  // Returning R-squared
54  return 1 - residualSumSquared / totalSumSquared;
55  }
56 }
57 
58 } // namespace cv
59 } // namespace mlpack
60 
61 #endif
Linear algebra utility functions, generally performed on matrices or vectors.
Definition: cv.hpp:1
static double Evaluate(MLAlgorithm &model, const DataType &data, const ResponsesType &responses)
Run prediction and calculate the R squared or Adjusted R squared error.
Definition: r2_score_impl.hpp:20