Class: Rumale::EvaluationMeasure::R2Score

Inherits:
Object
  • Object
show all
Includes:
Base::Evaluator
Defined in:
lib/rumale/evaluation_measure/r2_score.rb

Overview

R2Score is a class that calculates the coefficient of determination for the predicted values.

Examples:

evaluator = Rumale::EvaluationMeasure::R2Score.new
puts evaluator.score(ground_truth, predicted)

Instance Method Summary collapse

Constructor Details

#initializeR2Score

Create a new evaluation measure calculater for coefficient of determination.



17
# File 'lib/rumale/evaluation_measure/r2_score.rb', line 17

def initialize; end

Instance Method Details

#score(y_true, y_pred) ⇒ Float

Calculate the coefficient of determination.

Parameters:

  • y_true (Numo::DFloat)

    (shape: [n_samples, n_outputs]) Ground truth target values.

  • y_pred (Numo::DFloat)

    (shape: [n_samples, n_outputs]) Estimated taget values.

Returns:

  • (Float)

    Coefficient of determination

Raises:

  • (ArgumentError)


24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/rumale/evaluation_measure/r2_score.rb', line 24

def score(y_true, y_pred)
  check_tvalue_array(y_true)
  check_tvalue_array(y_pred)
  raise ArgumentError, 'Expect to have the same size both y_true and y_pred.' unless y_true.shape == y_pred.shape

  n_samples, n_outputs = y_true.shape
  numerator = ((y_true - y_pred)**2).sum(0)
  yt_mean = y_true.sum(0) / n_samples
  denominator = ((y_true - yt_mean)**2).sum(0)
  if n_outputs.nil?
    denominator.zero? ? 0.0 : 1.0 - numerator / denominator
  else
    scores = 1 - numerator / denominator
    scores[denominator.eq(0)] = 0.0
    scores.sum / scores.size
  end
end