Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Problems.DataAnalysis.Regression/3.3/Symbolic/SymbolicRegressionScaledMeanAndVarianceSquaredErrorEvaluator.cs @ 4077

Last change on this file since 4077 was 4068, checked in by swagner, 14 years ago

Sorted usings and removed unused usings in entire solution (#1094)

File size: 8.8 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2010 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
22using System;
23using System.Collections.Generic;
24using HeuristicLab.Common;
25using HeuristicLab.Core;
26using HeuristicLab.Data;
27using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
28using HeuristicLab.Parameters;
29using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
30using HeuristicLab.Problems.DataAnalysis.Evaluators;
31using HeuristicLab.Problems.DataAnalysis.Symbolic;
32
33namespace HeuristicLab.Problems.DataAnalysis.Regression.Symbolic {
34  [Item("SymbolicRegressionScaledMeanAndVarianceSquaredErrorEvaluator", "Calculates the mean and the variance of the squared errors of a linearly scaled symbolic regression solution.")]
35  [StorableClass]
36  public class SymbolicRegressionScaledMeanAndVarianceSquaredErrorEvaluator : SymbolicRegressionMeanSquaredErrorEvaluator {
37    private const string QualityVarianceParameterName = "QualityVariance";
38    private const string QualitySamplesParameterName = "QualitySamples";
39
40    #region parameter properties
41    public ILookupParameter<DoubleValue> AlphaParameter {
42      get { return (ILookupParameter<DoubleValue>)Parameters["Alpha"]; }
43    }
44    public ILookupParameter<DoubleValue> BetaParameter {
45      get { return (ILookupParameter<DoubleValue>)Parameters["Beta"]; }
46    }
47    public ILookupParameter<DoubleValue> QualityVarianceParameter {
48      get { return (ILookupParameter<DoubleValue>)Parameters[QualityVarianceParameterName]; }
49    }
50    public ILookupParameter<IntValue> QualitySamplesParameter {
51      get { return (ILookupParameter<IntValue>)Parameters[QualitySamplesParameterName]; }
52    }
53
54    #endregion
55    #region properties
56    public DoubleValue Alpha {
57      get { return AlphaParameter.ActualValue; }
58      set { AlphaParameter.ActualValue = value; }
59    }
60    public DoubleValue Beta {
61      get { return BetaParameter.ActualValue; }
62      set { BetaParameter.ActualValue = value; }
63    }
64    public DoubleValue QualityVariance {
65      get { return QualityVarianceParameter.ActualValue; }
66      set { QualityVarianceParameter.ActualValue = value; }
67    }
68    public IntValue QualitySamples {
69      get { return QualitySamplesParameter.ActualValue; }
70      set { QualitySamplesParameter.ActualValue = value; }
71    }
72    #endregion
73    public SymbolicRegressionScaledMeanAndVarianceSquaredErrorEvaluator()
74      : base() {
75      Parameters.Add(new LookupParameter<DoubleValue>("Alpha", "Alpha parameter for linear scaling of the estimated values."));
76      Parameters.Add(new LookupParameter<DoubleValue>("Beta", "Beta parameter for linear scaling of the estimated values."));
77      Parameters.Add(new LookupParameter<DoubleValue>(QualityVarianceParameterName, "A parameter which stores the variance of the squared errors."));
78      Parameters.Add(new LookupParameter<IntValue>(QualitySamplesParameterName, " The number of evaluated samples."));
79    }
80
81    protected override double Evaluate(ISymbolicExpressionTreeInterpreter interpreter, SymbolicExpressionTree solution, Dataset dataset, StringValue targetVariable, IEnumerable<int> rows) {
82      double alpha, beta;
83      double meanSE, varianceSE;
84      int count;
85      double mse = Calculate(interpreter, solution, LowerEstimationLimit.Value, UpperEstimationLimit.Value, dataset, targetVariable.Value, rows, out beta, out alpha, out meanSE, out varianceSE, out count);
86      Alpha = new DoubleValue(alpha);
87      Beta = new DoubleValue(beta);
88      QualityVariance = new DoubleValue(varianceSE);
89      QualitySamples = new IntValue(count);
90      return mse;
91    }
92
93    public static double Calculate(ISymbolicExpressionTreeInterpreter interpreter, SymbolicExpressionTree solution, double lowerEstimationLimit, double upperEstimationLimit, Dataset dataset, string targetVariable, IEnumerable<int> rows, out double beta, out double alpha, out double meanSE, out double varianceSE, out int count) {
94      IEnumerable<double> originalValues = dataset.GetEnumeratedVariableValues(targetVariable, rows);
95      IEnumerable<double> estimatedValues = interpreter.GetSymbolicExpressionTreeValues(solution, dataset, rows);
96      CalculateScalingParameters(originalValues, estimatedValues, out beta, out alpha);
97
98      return CalculateWithScaling(interpreter, solution, lowerEstimationLimit, upperEstimationLimit, dataset, targetVariable, rows, beta, alpha, out meanSE, out varianceSE, out count);
99    }
100
101    public static double CalculateWithScaling(ISymbolicExpressionTreeInterpreter interpreter, SymbolicExpressionTree solution, double lowerEstimationLimit, double upperEstimationLimit, Dataset dataset, string targetVariable, IEnumerable<int> rows, double beta, double alpha, out double meanSE, out double varianceSE, out int count) {
102      IEnumerable<double> estimatedValues = interpreter.GetSymbolicExpressionTreeValues(solution, dataset, rows);
103      IEnumerable<double> originalValues = dataset.GetEnumeratedVariableValues(targetVariable, rows);
104      IEnumerator<double> originalEnumerator = originalValues.GetEnumerator();
105      IEnumerator<double> estimatedEnumerator = estimatedValues.GetEnumerator();
106      OnlineMeanAndVarianceCalculator seEvaluator = new OnlineMeanAndVarianceCalculator();
107
108      while (originalEnumerator.MoveNext() & estimatedEnumerator.MoveNext()) {
109        double estimated = estimatedEnumerator.Current * beta + alpha;
110        double original = originalEnumerator.Current;
111        if (double.IsNaN(estimated))
112          estimated = upperEstimationLimit;
113        else
114          estimated = Math.Min(upperEstimationLimit, Math.Max(lowerEstimationLimit, estimated));
115        double error = estimated - original;
116        error *= error;
117        seEvaluator.Add(error);
118      }
119
120      if (estimatedEnumerator.MoveNext() || originalEnumerator.MoveNext()) {
121        throw new ArgumentException("Number of elements in original and estimated enumeration doesn't match.");
122      } else {
123        meanSE = seEvaluator.Mean;
124        varianceSE = seEvaluator.Variance;
125        count = seEvaluator.Count;
126        return seEvaluator.Mean;
127      }
128    }
129
130    /// <summary>
131    /// Calculates linear scaling parameters in one pass.
132    /// The formulas to calculate the scaling parameters were taken from Scaled Symblic Regression by Maarten Keijzer.
133    /// http://www.springerlink.com/content/x035121165125175/
134    /// </summary>
135    public static void CalculateScalingParameters(IEnumerable<double> original, IEnumerable<double> estimated, out double beta, out double alpha) {
136      IEnumerator<double> originalEnumerator = original.GetEnumerator();
137      IEnumerator<double> estimatedEnumerator = estimated.GetEnumerator();
138      OnlineMeanAndVarianceCalculator yVarianceCalculator = new OnlineMeanAndVarianceCalculator();
139      OnlineMeanAndVarianceCalculator tMeanCalculator = new OnlineMeanAndVarianceCalculator();
140      OnlineCovarianceEvaluator ytCovarianceEvaluator = new OnlineCovarianceEvaluator();
141      int cnt = 0;
142
143      while (originalEnumerator.MoveNext() & estimatedEnumerator.MoveNext()) {
144        double y = estimatedEnumerator.Current;
145        double t = originalEnumerator.Current;
146        if (IsValidValue(t) && IsValidValue(y)) {
147          tMeanCalculator.Add(t);
148          yVarianceCalculator.Add(y);
149          ytCovarianceEvaluator.Add(y, t);
150
151          cnt++;
152        }
153      }
154
155      if (estimatedEnumerator.MoveNext() || originalEnumerator.MoveNext())
156        throw new ArgumentException("Number of elements in original and estimated enumeration doesn't match.");
157      if (cnt < 2) {
158        alpha = 0;
159        beta = 1;
160      } else {
161        if (yVarianceCalculator.Variance.IsAlmost(0.0))
162          beta = 1;
163        else
164          beta = ytCovarianceEvaluator.Covariance / yVarianceCalculator.Variance;
165
166        alpha = tMeanCalculator.Mean - beta * yVarianceCalculator.Mean;
167      }
168    }
169
170    private static bool IsValidValue(double d) {
171      return !double.IsInfinity(d) && !double.IsNaN(d) && d > -1.0E07 && d < 1.0E07;  // don't consider very large or very small values for scaling
172    }
173  }
174}
Note: See TracBrowser for help on using the repository browser.