1 | #region License Information
|
---|
2 | /* HeuristicLab
|
---|
3 | * Copyright (C) 2002-2012 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
|
---|
4 | *
|
---|
5 | * This file is part of HeuristicLab.
|
---|
6 | *
|
---|
7 | * HeuristicLab is free software: you can redistribute it and/or modify
|
---|
8 | * it under the terms of the GNU General Public License as published by
|
---|
9 | * the Free Software Foundation, either version 3 of the License, or
|
---|
10 | * (at your option) any later version.
|
---|
11 | *
|
---|
12 | * HeuristicLab is distributed in the hope that it will be useful,
|
---|
13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
|
---|
14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
---|
15 | * GNU General Public License for more details.
|
---|
16 | *
|
---|
17 | * You should have received a copy of the GNU General Public License
|
---|
18 | * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
|
---|
19 | */
|
---|
20 | #endregion
|
---|
21 |
|
---|
22 | using System;
|
---|
23 | using System.Linq;
|
---|
24 |
|
---|
25 | namespace HeuristicLab.Analysis.AlgorithmBehavior.Analyzers {
|
---|
26 | public class LinearLeastSquaresFitting {
|
---|
27 | public static void Calculate(double[] dataPoints, out double a1, out double a0) {
|
---|
28 | double sxy = 0.0;
|
---|
29 | double sxx = 0.0;
|
---|
30 | int n = dataPoints.Count();
|
---|
31 | double sy = dataPoints.Sum();
|
---|
32 | double sx = ((n - 1) * n) / 2;
|
---|
33 | double avgy = sy / n;
|
---|
34 | double avgx = sx / n;
|
---|
35 |
|
---|
36 | for (int i = 0; i < n; i++) {
|
---|
37 | sxy += i * dataPoints[i];
|
---|
38 | sxx += i * i;
|
---|
39 | }
|
---|
40 |
|
---|
41 | a1 = (sxy - (n * avgx * avgy)) / (sxx - (n * avgx * avgx));
|
---|
42 | a0 = avgy - a1 * avgx;
|
---|
43 | }
|
---|
44 |
|
---|
45 | public static double CalculateError(double[] dataPoints, double a1, double a0) {
|
---|
46 | double r = 0.0;
|
---|
47 | double avgy = dataPoints.Average();
|
---|
48 | double sstot = 0.0;
|
---|
49 | double sserr = 0.0;
|
---|
50 |
|
---|
51 | for (int i = 0; i < dataPoints.Count(); i++) {
|
---|
52 | double y = a1 * i + a0;
|
---|
53 | sstot += Math.Pow(dataPoints[i] - avgy, 2);
|
---|
54 | sserr += Math.Pow(dataPoints[i] - y, 2);
|
---|
55 | }
|
---|
56 |
|
---|
57 | r = 1.0 - (sserr / sstot);
|
---|
58 | return r;
|
---|
59 | }
|
---|
60 | }
|
---|
61 | }
|
---|