Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Modeling/3.2/SimpleStableCorrelationCoefficientEvaluator.cs @ 2428

Last change on this file since 2428 was 2428, checked in by gkronber, 15 years ago

Implemented #782 (Additional model quality metrics: Pearson product-moment correlation coefficient and Spearman's rank correlation coefficient)

File size: 2.1 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Text;
5using HeuristicLab.Core;
6using HeuristicLab.Data;
7using HeuristicLab.DataAnalysis;
8
9namespace HeuristicLab.Modeling {
10  public class SimpleStableCorrelationCoefficientEvaluator : SimpleEvaluatorBase {
11
12    public override string OutputVariableName {
13      get {
14        return "R2";
15      }
16    }
17
18    public override double Evaluate(double[,] values) {
19      try {
20        return Calculate(values);
21      }
22      catch (ArgumentException) {
23        return double.NegativeInfinity;
24      }
25    }
26
27    public static double Calculate(double[,] values) {
28      double sum_sq_x = 0.0;
29      double sum_sq_y = 0.0;
30      double sum_coproduct = 0.0;
31      if (IsInvalidValue(values[0, ORIGINAL_INDEX]) || IsInvalidValue(values[0, ESTIMATION_INDEX])) {
32        throw new ArgumentException("Correlation coefficient is not defined for variables with NaN or infinity values.");
33      }
34      double mean_x = values[0, ORIGINAL_INDEX];
35      double mean_y = values[0, ESTIMATION_INDEX];
36      for (int i = 1; i < values.GetLength(0); i++) {
37        double sweep = (i - 1.0) / i;
38        if (IsInvalidValue(values[i, ORIGINAL_INDEX]) || IsInvalidValue(values[i, ESTIMATION_INDEX])) {
39          throw new ArgumentException("Correlation coefficient is not defined for variables with NaN or infinity values.");
40        }
41        double delta_x = values[i, ORIGINAL_INDEX] - mean_x;
42        double delta_y = values[i, ESTIMATION_INDEX] - mean_y;
43        sum_sq_x += delta_x * delta_x * sweep;
44        sum_sq_y += delta_y * delta_y * sweep;
45        sum_coproduct += delta_x * delta_y * sweep;
46        mean_x += delta_x / i;
47        mean_y += delta_y / i;
48      }
49      double pop_sd_x = Math.Sqrt(sum_sq_x / values.GetLength(0));
50      double pop_sd_y = Math.Sqrt(sum_sq_y / values.GetLength(0));
51      double cov_x_y = sum_coproduct / values.GetLength(0);
52      double r = cov_x_y / (pop_sd_x * pop_sd_y);
53      return r * r;
54    }
55
56    private static bool IsInvalidValue(double d) {
57      return double.IsNaN(d) || double.IsInfinity(d);
58    }
59  }
60}
Note: See TracBrowser for help on using the repository browser.