Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Problems.DataAnalysis.Regression/3.3/Symbolic/Analyzers/SymbolicRegressionModelQualityAnalyzer.cs @ 4415

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

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

File size: 15.6 KB
RevLine 
[3652]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
[4068]22using System;
23using System.Collections.Generic;
[3652]24using System.Linq;
[4068]25using HeuristicLab.Analysis;
[3652]26using HeuristicLab.Core;
27using HeuristicLab.Data;
[4068]28using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
[3652]29using HeuristicLab.Operators;
30using HeuristicLab.Optimization;
31using HeuristicLab.Parameters;
32using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
[4068]33using HeuristicLab.Problems.DataAnalysis.Evaluators;
[3652]34using HeuristicLab.Problems.DataAnalysis.Symbolic;
35
36namespace HeuristicLab.Problems.DataAnalysis.Regression.Symbolic.Analyzers {
37  /// <summary>
38  /// "An operator for analyzing the quality of symbolic regression solutions symbolic expression tree encoding."
39  /// </summary>
[3681]40  [Item("SymbolicRegressionModelQualityAnalyzer", "An operator for analyzing the quality of symbolic regression solutions symbolic expression tree encoding.")]
[3652]41  [StorableClass]
[3996]42  public sealed class SymbolicRegressionModelQualityAnalyzer : SingleSuccessorOperator, ISymbolicRegressionAnalyzer {
[3652]43    private const string SymbolicExpressionTreeInterpreterParameterName = "SymbolicExpressionTreeInterpreter";
44    private const string SymbolicExpressionTreeParameterName = "SymbolicExpressionTree";
45    private const string ProblemDataParameterName = "ProblemData";
46    private const string ResultsParameterName = "Results";
[3666]47
[3710]48    private const string TrainingMeanSquaredErrorQualityParameterName = "Mean squared error (training)";
49    private const string MinTrainingMeanSquaredErrorQualityParameterName = "Min mean squared error (training)";
50    private const string MaxTrainingMeanSquaredErrorQualityParameterName = "Max mean squared error (training)";
51    private const string AverageTrainingMeanSquaredErrorQualityParameterName = "Average mean squared error (training)";
52    private const string BestTrainingMeanSquaredErrorQualityParameterName = "Best mean squared error (training)";
[3666]53
[3710]54    private const string TrainingAverageRelativeErrorQualityParameterName = "Average relative error (training)";
55    private const string MinTrainingAverageRelativeErrorQualityParameterName = "Min average relative error (training)";
56    private const string MaxTrainingAverageRelativeErrorQualityParameterName = "Max average relative error (training)";
57    private const string AverageTrainingAverageRelativeErrorQualityParameterName = "Average average relative error (training)";
58    private const string BestTrainingAverageRelativeErrorQualityParameterName = "Best average relative error (training)";
[3666]59
[3710]60    private const string TrainingRSquaredQualityParameterName = "R² (training)";
61    private const string MinTrainingRSquaredQualityParameterName = "Min R² (training)";
62    private const string MaxTrainingRSquaredQualityParameterName = "Max R² (training)";
63    private const string AverageTrainingRSquaredQualityParameterName = "Average R² (training)";
64    private const string BestTrainingRSquaredQualityParameterName = "Best R² (training)";
[3666]65
[3710]66    private const string TestMeanSquaredErrorQualityParameterName = "Mean squared error (test)";
67    private const string MinTestMeanSquaredErrorQualityParameterName = "Min mean squared error (test)";
68    private const string MaxTestMeanSquaredErrorQualityParameterName = "Max mean squared error (test)";
69    private const string AverageTestMeanSquaredErrorQualityParameterName = "Average mean squared error (test)";
70    private const string BestTestMeanSquaredErrorQualityParameterName = "Best mean squared error (test)";
[3666]71
[3710]72    private const string TestAverageRelativeErrorQualityParameterName = "Average relative error (test)";
73    private const string MinTestAverageRelativeErrorQualityParameterName = "Min average relative error (test)";
74    private const string MaxTestAverageRelativeErrorQualityParameterName = "Max average relative error (test)";
75    private const string AverageTestAverageRelativeErrorQualityParameterName = "Average average relative error (test)";
76    private const string BestTestAverageRelativeErrorQualityParameterName = "Best average relative error (test)";
[3666]77
[3710]78    private const string TestRSquaredQualityParameterName = "R² (test)";
79    private const string MinTestRSquaredQualityParameterName = "Min R² (test)";
80    private const string MaxTestRSquaredQualityParameterName = "Max R² (test)";
81    private const string AverageTestRSquaredQualityParameterName = "Average R² (test)";
82    private const string BestTestRSquaredQualityParameterName = "Best R² (test)";
[3666]83
[3710]84    private const string RSquaredValuesParameterName = "R²";
85    private const string MeanSquaredErrorValuesParameterName = "Mean squared error";
86    private const string RelativeErrorValuesParameterName = "Average relative error";
[3666]87
[3652]88    private const string UpperEstimationLimitParameterName = "UpperEstimationLimit";
89    private const string LowerEstimationLimitParameterName = "LowerEstimationLimit";
90
91    #region parameter properties
[3681]92    public ScopeTreeLookupParameter<SymbolicExpressionTree> SymbolicExpressionTreeParameter {
93      get { return (ScopeTreeLookupParameter<SymbolicExpressionTree>)Parameters[SymbolicExpressionTreeParameterName]; }
[3652]94    }
[3681]95    public IValueLookupParameter<ISymbolicExpressionTreeInterpreter> SymbolicExpressionTreeInterpreterParameter {
96      get { return (IValueLookupParameter<ISymbolicExpressionTreeInterpreter>)Parameters[SymbolicExpressionTreeInterpreterParameterName]; }
[3652]97    }
[3681]98    public IValueLookupParameter<DataAnalysisProblemData> ProblemDataParameter {
99      get { return (IValueLookupParameter<DataAnalysisProblemData>)Parameters[ProblemDataParameterName]; }
[3652]100    }
101    public IValueLookupParameter<DoubleValue> UpperEstimationLimitParameter {
102      get { return (IValueLookupParameter<DoubleValue>)Parameters[UpperEstimationLimitParameterName]; }
103    }
104    public IValueLookupParameter<DoubleValue> LowerEstimationLimitParameter {
105      get { return (IValueLookupParameter<DoubleValue>)Parameters[LowerEstimationLimitParameterName]; }
106    }
[3681]107    public ILookupParameter<ResultCollection> ResultsParameter {
108      get { return (ILookupParameter<ResultCollection>)Parameters[ResultsParameterName]; }
109    }
[3652]110    #endregion
[3996]111    #region properties
112    public DoubleValue UpperEstimationLimit {
113      get { return UpperEstimationLimitParameter.ActualValue; }
114    }
115    public DoubleValue LowerEstimationLimit {
116      get { return LowerEstimationLimitParameter.ActualValue; }
117    }
118    #endregion
[3652]119
[3681]120    public SymbolicRegressionModelQualityAnalyzer()
[3652]121      : base() {
[3659]122      Parameters.Add(new ScopeTreeLookupParameter<SymbolicExpressionTree>(SymbolicExpressionTreeParameterName, "The symbolic expression trees to analyze."));
[3681]123      Parameters.Add(new ValueLookupParameter<ISymbolicExpressionTreeInterpreter>(SymbolicExpressionTreeInterpreterParameterName, "The interpreter that should be used to calculate the output values of the symbolic expression tree."));
124      Parameters.Add(new ValueLookupParameter<DataAnalysisProblemData>(ProblemDataParameterName, "The problem data containing the input varaibles for the symbolic regression problem."));
[3652]125      Parameters.Add(new ValueLookupParameter<DoubleValue>(UpperEstimationLimitParameterName, "The upper limit that should be used as cut off value for the output values of symbolic expression trees."));
126      Parameters.Add(new ValueLookupParameter<DoubleValue>(LowerEstimationLimitParameterName, "The lower limit that should be used as cut off value for the output values of symbolic expression trees."));
[3681]127      Parameters.Add(new ValueLookupParameter<DataTable>(MeanSquaredErrorValuesParameterName, "The data table to collect mean squared error values."));
128      Parameters.Add(new ValueLookupParameter<DataTable>(RSquaredValuesParameterName, "The data table to collect R² correlation coefficient values."));
129      Parameters.Add(new ValueLookupParameter<DataTable>(RelativeErrorValuesParameterName, "The data table to collect relative error values."));
130      Parameters.Add(new LookupParameter<ResultCollection>(ResultsParameterName, "The result collection where the best symbolic regression solution should be stored."));
[3996]131    }
[3652]132
[3996]133    [StorableConstructor]
134    private SymbolicRegressionModelQualityAnalyzer(bool deserializing) : base() { }
[3681]135
[3996]136    public override IOperation Apply() {
137      Analyze(SymbolicExpressionTreeParameter.ActualValue, SymbolicExpressionTreeInterpreterParameter.ActualValue,
138        UpperEstimationLimit.Value, LowerEstimationLimit.Value, ProblemDataParameter.ActualValue,
[4054]139        ProblemDataParameter.ActualValue.TrainingSamplesStart.Value, ProblemDataParameter.ActualValue.TrainingSamplesEnd.Value,
140        ProblemDataParameter.ActualValue.TestSamplesStart.Value, ProblemDataParameter.ActualValue.TestSamplesEnd.Value,
[3996]141        ResultsParameter.ActualValue);
142      return base.Apply();
143    }
[3681]144
[3996]145    public static void Analyze(IEnumerable<SymbolicExpressionTree> trees, ISymbolicExpressionTreeInterpreter interpreter,
146      double upperEstimationLimit, double lowerEstimationLimit,
147      DataAnalysisProblemData problemData, int trainingStart, int trainingEnd, int testStart, int testEnd, ResultCollection results) {
148      int targetVariableIndex = problemData.Dataset.GetVariableIndex(problemData.TargetVariable.Value);
149      IEnumerable<double> originalTrainingValues = problemData.Dataset.GetEnumeratedVariableValues(targetVariableIndex, trainingStart, trainingEnd);
150      IEnumerable<double> originalTestValues = problemData.Dataset.GetEnumeratedVariableValues(targetVariableIndex, testStart, testEnd);
151      List<double> trainingMse = new List<double>();
152      List<double> trainingR2 = new List<double>();
153      List<double> trainingRelErr = new List<double>();
154      List<double> testMse = new List<double>();
155      List<double> testR2 = new List<double>();
156      List<double> testRelErr = new List<double>();
[3652]157
[3996]158      OnlineMeanSquaredErrorEvaluator mseEvaluator = new OnlineMeanSquaredErrorEvaluator();
159      OnlineMeanAbsolutePercentageErrorEvaluator relErrEvaluator = new OnlineMeanAbsolutePercentageErrorEvaluator();
160      OnlinePearsonsRSquaredEvaluator r2Evaluator = new OnlinePearsonsRSquaredEvaluator();
[3666]161
[3996]162      foreach (var tree in trees) {
163        #region training
164        var estimatedTrainingValues = interpreter.GetSymbolicExpressionTreeValues(tree, problemData.Dataset, Enumerable.Range(trainingStart, trainingEnd - trainingStart));
165        mseEvaluator.Reset();
166        r2Evaluator.Reset();
167        relErrEvaluator.Reset();
168        var estimatedEnumerator = estimatedTrainingValues.GetEnumerator();
169        var originalEnumerator = originalTrainingValues.GetEnumerator();
170        while (estimatedEnumerator.MoveNext() & originalEnumerator.MoveNext()) {
171          double estimated = estimatedEnumerator.Current;
172          if (double.IsNaN(estimated)) estimated = upperEstimationLimit;
173          else estimated = Math.Min(upperEstimationLimit, Math.Max(lowerEstimationLimit, estimated));
174          mseEvaluator.Add(originalEnumerator.Current, estimated);
175          r2Evaluator.Add(originalEnumerator.Current, estimated);
176          relErrEvaluator.Add(originalEnumerator.Current, estimated);
177        }
178        if (estimatedEnumerator.MoveNext() || originalEnumerator.MoveNext()) {
179          throw new InvalidOperationException("Number of elements in estimated and original enumeration doesn't match.");
180        }
181        trainingMse.Add(mseEvaluator.MeanSquaredError);
182        trainingR2.Add(r2Evaluator.RSquared);
183        trainingRelErr.Add(relErrEvaluator.MeanAbsolutePercentageError);
184        #endregion
185        #region test
186        var estimatedTestValues = interpreter.GetSymbolicExpressionTreeValues(tree, problemData.Dataset, Enumerable.Range(testStart, testEnd - testStart));
[3666]187
[3996]188        mseEvaluator.Reset();
189        r2Evaluator.Reset();
190        relErrEvaluator.Reset();
191        estimatedEnumerator = estimatedTestValues.GetEnumerator();
192        originalEnumerator = originalTestValues.GetEnumerator();
193        while (estimatedEnumerator.MoveNext() & originalEnumerator.MoveNext()) {
194          double estimated = estimatedEnumerator.Current;
195          if (double.IsNaN(estimated)) estimated = upperEstimationLimit;
196          else estimated = Math.Min(upperEstimationLimit, Math.Max(lowerEstimationLimit, estimated));
197          mseEvaluator.Add(originalEnumerator.Current, estimated);
198          r2Evaluator.Add(originalEnumerator.Current, estimated);
199          relErrEvaluator.Add(originalEnumerator.Current, estimated);
200        }
201        if (estimatedEnumerator.MoveNext() || originalEnumerator.MoveNext()) {
202          throw new InvalidOperationException("Number of elements in estimated and original enumeration doesn't match.");
203        }
204        testMse.Add(mseEvaluator.MeanSquaredError);
205        testR2.Add(r2Evaluator.RSquared);
206        testRelErr.Add(relErrEvaluator.MeanAbsolutePercentageError);
207        #endregion
208      }
[3710]209
[3996]210      AddResultTableValues(results, MeanSquaredErrorValuesParameterName, "mean squared error (training)", trainingMse.Min(), trainingMse.Average(), trainingMse.Max());
211      AddResultTableValues(results, MeanSquaredErrorValuesParameterName, "mean squared error (test)", testMse.Min(), testMse.Average(), testMse.Max());
212      AddResultTableValues(results, RelativeErrorValuesParameterName, "mean relative error (training)", trainingRelErr.Min(), trainingRelErr.Average(), trainingRelErr.Max());
213      AddResultTableValues(results, RelativeErrorValuesParameterName, "mean relative error (test)", testRelErr.Min(), testRelErr.Average(), testRelErr.Max());
214      AddResultTableValues(results, RSquaredValuesParameterName, "Pearson's R² (training)", trainingR2.Min(), trainingR2.Average(), trainingR2.Max());
215      AddResultTableValues(results, RSquaredValuesParameterName, "Pearson's R² (test)", testR2.Min(), testR2.Average(), testR2.Max());
[3652]216    }
[3681]217
[3996]218    private static void AddResultTableValues(ResultCollection results, string tableName, string valueName, double minValue, double avgValue, double maxValue) {
219      if (!results.ContainsKey(tableName)) {
220        results.Add(new Result(tableName, new DataTable(tableName)));
221      }
222      DataTable table = (DataTable)results[tableName].Value;
223      AddValue(table, minValue, "Min. " + valueName, string.Empty);
224      AddValue(table, avgValue, "Avg. " + valueName, string.Empty);
225      AddValue(table, maxValue, "Max. " + valueName, string.Empty);
[3681]226    }
227
[3996]228    private static void AddValue(DataTable table, double data, string name, string description) {
229      DataRow row;
230      table.Rows.TryGetValue(name, out row);
231      if (row == null) {
232        row = new DataRow(name, description);
233        row.Values.Add(data);
234        table.Rows.Add(row);
235      } else {
236        row.Values.Add(data);
237      }
[3681]238    }
239
[3996]240
241    private static void SetResultValue(ResultCollection results, string name, double value) {
242      if (results.ContainsKey(name))
243        results[name].Value = new DoubleValue(value);
244      else
245        results.Add(new Result(name, new DoubleValue(value)));
[3681]246    }
[3652]247  }
248}
Note: See TracBrowser for help on using the repository browser.