[1814] | 1 | using System;
|
---|
| 2 | using System.Collections.Generic;
|
---|
| 3 | using System.Linq;
|
---|
| 4 | using System.Text;
|
---|
| 5 | using HeuristicLab.Core;
|
---|
| 6 | using HeuristicLab.Data;
|
---|
| 7 | using HeuristicLab.DataAnalysis;
|
---|
| 8 |
|
---|
[1869] | 9 | namespace HeuristicLab.Modeling {
|
---|
[1888] | 10 | public class SimpleR2Evaluator : SimpleEvaluatorBase {
|
---|
[1814] | 11 |
|
---|
[1888] | 12 | public override string OutputVariableName {
|
---|
| 13 | get {
|
---|
| 14 | return "R2";
|
---|
| 15 | }
|
---|
[1814] | 16 | }
|
---|
| 17 |
|
---|
[1888] | 18 | public override double Evaluate(double[,] values) {
|
---|
[2136] | 19 | try {
|
---|
| 20 | return Calculate(values);
|
---|
| 21 | }
|
---|
| 22 | catch (ArgumentException) {
|
---|
| 23 | return double.NegativeInfinity;
|
---|
| 24 | }
|
---|
[1888] | 25 | }
|
---|
[1814] | 26 |
|
---|
[1888] | 27 | public static double Calculate(double[,] values) {
|
---|
[1814] | 28 | double targetMean = 0;
|
---|
| 29 | double sse = 0;
|
---|
| 30 | double cnt = 0;
|
---|
[1888] | 31 | for (int i = 0; i < values.GetLength(0); i++) {
|
---|
| 32 | double estimated = values[i, 0];
|
---|
| 33 | double target = values[i, 1];
|
---|
[1814] | 34 | if (!double.IsNaN(estimated) && !double.IsInfinity(estimated) &&
|
---|
| 35 | !double.IsNaN(target) && !double.IsInfinity(target)) {
|
---|
| 36 | targetMean += target;
|
---|
| 37 | double error = estimated - target;
|
---|
| 38 | sse += error * error;
|
---|
| 39 | cnt++;
|
---|
| 40 | }
|
---|
| 41 | }
|
---|
| 42 |
|
---|
[2136] | 43 | if (cnt > 0) {
|
---|
| 44 | targetMean /= cnt;
|
---|
| 45 |
|
---|
| 46 | double targetDeviationTotalSumOfSquares = 0;
|
---|
| 47 | for (int i = 0; i < values.GetLength(0); i++) {
|
---|
| 48 | double target = values[i, 1];
|
---|
| 49 | if (!double.IsNaN(target) && !double.IsInfinity(target)) {
|
---|
| 50 | target = target - targetMean;
|
---|
| 51 | target = target * target;
|
---|
| 52 | targetDeviationTotalSumOfSquares += target;
|
---|
| 53 | }
|
---|
[1814] | 54 | }
|
---|
[2136] | 55 | double quality = 1 - sse / targetDeviationTotalSumOfSquares;
|
---|
| 56 | if (quality > 1)
|
---|
| 57 | throw new InvalidProgramException();
|
---|
| 58 |
|
---|
| 59 | return quality;
|
---|
| 60 | } else {
|
---|
| 61 | throw new ArgumentException("Coefficient of determination is not defined for input vectors of NaN or Inf");
|
---|
[1814] | 62 | }
|
---|
| 63 | }
|
---|
| 64 | }
|
---|
| 65 | }
|
---|