source: trunk/sources/HeuristicLab.Problems.DataAnalysis.Regression/3.3/Symbolic/Analyzers/FixedValidationBestScaledSymbolicRegressionSolutionAnalyzer.cs @ 4127

Last change on this file since 4127 was 4127, checked in by gkronber, 10 years ago

Added correlation coefficient evaluator for symbolic regression problems. #1117

File size: 18.0 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.Collections.Generic;
23using System.Linq;
24using HeuristicLab.Analysis;
25using HeuristicLab.Core;
26using HeuristicLab.Data;
27using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
28using HeuristicLab.Operators;
29using HeuristicLab.Optimization;
30using HeuristicLab.Parameters;
31using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
32using HeuristicLab.Problems.DataAnalysis.Evaluators;
33using HeuristicLab.Problems.DataAnalysis.Symbolic;
34
35namespace HeuristicLab.Problems.DataAnalysis.Regression.Symbolic.Analyzers {
36  /// <summary>
37  /// An operator that analyzes the validation best scaled symbolic regression solution.
38  /// </summary>
39  [Item("FixedValidationBestScaledSymbolicRegressionSolutionAnalyzer", "An operator that analyzes the validation best scaled symbolic regression solution.")]
40  [StorableClass]
41  public sealed class FixedValidationBestScaledSymbolicRegressionSolutionAnalyzer : SingleSuccessorOperator, ISymbolicRegressionAnalyzer {
42    private const string RandomParameterName = "Random";
43    private const string SymbolicExpressionTreeParameterName = "SymbolicExpressionTree";
44    private const string SymbolicExpressionTreeInterpreterParameterName = "SymbolicExpressionTreeInterpreter";
45    private const string ProblemDataParameterName = "ProblemData";
46    private const string ValidationSamplesStartParameterName = "SamplesStart";
47    private const string ValidationSamplesEndParameterName = "SamplesEnd";
48    private const string QualityParameterName = "Quality";
49    private const string UpperEstimationLimitParameterName = "UpperEstimationLimit";
50    private const string LowerEstimationLimitParameterName = "LowerEstimationLimit";
51    private const string BestSolutionParameterName = "Best solution (validation)";
52    private const string BestSolutionQualityParameterName = "Best solution quality (validation)";
53    private const string CurrentBestValidationQualityParameterName = "Current best validation quality";
54    private const string BestSolutionQualityValuesParameterName = "Validation Quality";
55    private const string ResultsParameterName = "Results";
56    private const string VariableFrequenciesParameterName = "VariableFrequencies";
57    private const string BestKnownQualityParameterName = "BestKnownQuality";
58    private const string GenerationsParameterName = "Generations";
59    private const string RelativeNumberOfEvaluatedSamplesParameterName = "RelativeNumberOfEvaluatedSamples";
60
61    private const string TrainingMeanSquaredErrorQualityParameterName = "Mean squared error (training)";
62    private const string MinTrainingMeanSquaredErrorQualityParameterName = "Min mean squared error (training)";
63    private const string MaxTrainingMeanSquaredErrorQualityParameterName = "Max mean squared error (training)";
64    private const string AverageTrainingMeanSquaredErrorQualityParameterName = "Average mean squared error (training)";
65    private const string BestTrainingMeanSquaredErrorQualityParameterName = "Best mean squared error (training)";
66
67    private const string TrainingAverageRelativeErrorQualityParameterName = "Average relative error (training)";
68    private const string MinTrainingAverageRelativeErrorQualityParameterName = "Min average relative error (training)";
69    private const string MaxTrainingAverageRelativeErrorQualityParameterName = "Max average relative error (training)";
70    private const string AverageTrainingAverageRelativeErrorQualityParameterName = "Average average relative error (training)";
71    private const string BestTrainingAverageRelativeErrorQualityParameterName = "Best average relative error (training)";
72
73    private const string TrainingRSquaredQualityParameterName = "R² (training)";
74    private const string MinTrainingRSquaredQualityParameterName = "Min R² (training)";
75    private const string MaxTrainingRSquaredQualityParameterName = "Max R² (training)";
76    private const string AverageTrainingRSquaredQualityParameterName = "Average R² (training)";
77    private const string BestTrainingRSquaredQualityParameterName = "Best R² (training)";
78
79    private const string TestMeanSquaredErrorQualityParameterName = "Mean squared error (test)";
80    private const string MinTestMeanSquaredErrorQualityParameterName = "Min mean squared error (test)";
81    private const string MaxTestMeanSquaredErrorQualityParameterName = "Max mean squared error (test)";
82    private const string AverageTestMeanSquaredErrorQualityParameterName = "Average mean squared error (test)";
83    private const string BestTestMeanSquaredErrorQualityParameterName = "Best mean squared error (test)";
84
85    private const string TestAverageRelativeErrorQualityParameterName = "Average relative error (test)";
86    private const string MinTestAverageRelativeErrorQualityParameterName = "Min average relative error (test)";
87    private const string MaxTestAverageRelativeErrorQualityParameterName = "Max average relative error (test)";
88    private const string AverageTestAverageRelativeErrorQualityParameterName = "Average average relative error (test)";
89    private const string BestTestAverageRelativeErrorQualityParameterName = "Best average relative error (test)";
90
91    private const string TestRSquaredQualityParameterName = "R² (test)";
92    private const string MinTestRSquaredQualityParameterName = "Min R² (test)";
93    private const string MaxTestRSquaredQualityParameterName = "Max R² (test)";
94    private const string AverageTestRSquaredQualityParameterName = "Average R² (test)";
95    private const string BestTestRSquaredQualityParameterName = "Best R² (test)";
96
97    private const string RSquaredValuesParameterName = "R²";
98    private const string MeanSquaredErrorValuesParameterName = "Mean squared error";
99    private const string RelativeErrorValuesParameterName = "Average relative error";
100
101    #region parameter properties
102    public ILookupParameter<IRandom> RandomParameter {
103      get { return (ILookupParameter<IRandom>)Parameters[RandomParameterName]; }
104    }
105    public ScopeTreeLookupParameter<SymbolicExpressionTree> SymbolicExpressionTreeParameter {
106      get { return (ScopeTreeLookupParameter<SymbolicExpressionTree>)Parameters[SymbolicExpressionTreeParameterName]; }
107    }
108    public IValueLookupParameter<ISymbolicExpressionTreeInterpreter> SymbolicExpressionTreeInterpreterParameter {
109      get { return (IValueLookupParameter<ISymbolicExpressionTreeInterpreter>)Parameters[SymbolicExpressionTreeInterpreterParameterName]; }
110    }
111    public IValueLookupParameter<DataAnalysisProblemData> ProblemDataParameter {
112      get { return (IValueLookupParameter<DataAnalysisProblemData>)Parameters[ProblemDataParameterName]; }
113    }
114    public IValueLookupParameter<IntValue> ValidationSamplesStartParameter {
115      get { return (IValueLookupParameter<IntValue>)Parameters[ValidationSamplesStartParameterName]; }
116    }
117    public IValueLookupParameter<IntValue> ValidationSamplesEndParameter {
118      get { return (IValueLookupParameter<IntValue>)Parameters[ValidationSamplesEndParameterName]; }
119    }
120    public IValueParameter<PercentValue> RelativeNumberOfEvaluatedSamplesParameter {
121      get { return (IValueParameter<PercentValue>)Parameters[RelativeNumberOfEvaluatedSamplesParameterName]; }
122    }
123
124    public IValueLookupParameter<DoubleValue> UpperEstimationLimitParameter {
125      get { return (IValueLookupParameter<DoubleValue>)Parameters[UpperEstimationLimitParameterName]; }
126    }
127    public IValueLookupParameter<DoubleValue> LowerEstimationLimitParameter {
128      get { return (IValueLookupParameter<DoubleValue>)Parameters[LowerEstimationLimitParameterName]; }
129    }
130    public ILookupParameter<SymbolicRegressionSolution> BestSolutionParameter {
131      get { return (ILookupParameter<SymbolicRegressionSolution>)Parameters[BestSolutionParameterName]; }
132    }
133    public ILookupParameter<IntValue> GenerationsParameter {
134      get { return (ILookupParameter<IntValue>)Parameters[GenerationsParameterName]; }
135    }
136    public ILookupParameter<DoubleValue> BestSolutionQualityParameter {
137      get { return (ILookupParameter<DoubleValue>)Parameters[BestSolutionQualityParameterName]; }
138    }
139    public ILookupParameter<ResultCollection> ResultsParameter {
140      get { return (ILookupParameter<ResultCollection>)Parameters[ResultsParameterName]; }
141    }
142    public ILookupParameter<DoubleValue> BestKnownQualityParameter {
143      get { return (ILookupParameter<DoubleValue>)Parameters[BestKnownQualityParameterName]; }
144    }
145    public ILookupParameter<DataTable> VariableFrequenciesParameter {
146      get { return (ILookupParameter<DataTable>)Parameters[VariableFrequenciesParameterName]; }
147    }
148
149    #endregion
150    #region properties
151    public IRandom Random {
152      get { return RandomParameter.ActualValue; }
153    }
154    public ItemArray<SymbolicExpressionTree> SymbolicExpressionTree {
155      get { return SymbolicExpressionTreeParameter.ActualValue; }
156    }
157    public ISymbolicExpressionTreeInterpreter SymbolicExpressionTreeInterpreter {
158      get { return SymbolicExpressionTreeInterpreterParameter.ActualValue; }
159    }
160    public DataAnalysisProblemData ProblemData {
161      get { return ProblemDataParameter.ActualValue; }
162    }
163    public IntValue ValidiationSamplesStart {
164      get { return ValidationSamplesStartParameter.ActualValue; }
165    }
166    public IntValue ValidationSamplesEnd {
167      get { return ValidationSamplesEndParameter.ActualValue; }
168    }
169    public PercentValue RelativeNumberOfEvaluatedSamples {
170      get { return RelativeNumberOfEvaluatedSamplesParameter.Value; }
171    }
172
173    public DoubleValue UpperEstimationLimit {
174      get { return UpperEstimationLimitParameter.ActualValue; }
175    }
176    public DoubleValue LowerEstimationLimit {
177      get { return LowerEstimationLimitParameter.ActualValue; }
178    }
179    public ResultCollection Results {
180      get { return ResultsParameter.ActualValue; }
181    }
182    public DataTable VariableFrequencies {
183      get { return VariableFrequenciesParameter.ActualValue; }
184    }
185    public IntValue Generations {
186      get { return GenerationsParameter.ActualValue; }
187    }
188
189    #endregion
190
191    public FixedValidationBestScaledSymbolicRegressionSolutionAnalyzer()
192      : base() {
193      Parameters.Add(new LookupParameter<IRandom>(RandomParameterName, "The random generator to use."));
194      Parameters.Add(new ScopeTreeLookupParameter<SymbolicExpressionTree>(SymbolicExpressionTreeParameterName, "The symbolic expression trees to analyze."));
195      Parameters.Add(new ScopeTreeLookupParameter<DoubleValue>(QualityParameterName, "The quality of the symbolic expression trees to analyze."));
196      Parameters.Add(new ValueLookupParameter<ISymbolicExpressionTreeInterpreter>(SymbolicExpressionTreeInterpreterParameterName, "The interpreter that should be used for the analysis of symbolic expression trees."));
197      Parameters.Add(new ValueLookupParameter<DataAnalysisProblemData>(ProblemDataParameterName, "The problem data for which the symbolic expression tree is a solution."));
198      Parameters.Add(new ValueLookupParameter<IntValue>(ValidationSamplesStartParameterName, "The first index of the validation partition of the data set."));
199      Parameters.Add(new ValueLookupParameter<IntValue>(ValidationSamplesEndParameterName, "The last index of the validation partition of the data set."));
200      Parameters.Add(new ValueParameter<PercentValue>(RelativeNumberOfEvaluatedSamplesParameterName, "The relative number of samples of the dataset partition, which should be randomly chosen for evaluation between the start and end index.", new PercentValue(1)));
201      Parameters.Add(new ValueLookupParameter<DoubleValue>(UpperEstimationLimitParameterName, "The upper estimation limit that was set for the evaluation of the symbolic expression trees."));
202      Parameters.Add(new ValueLookupParameter<DoubleValue>(LowerEstimationLimitParameterName, "The lower estimation limit that was set for the evaluation of the symbolic expression trees."));
203      Parameters.Add(new LookupParameter<SymbolicRegressionSolution>(BestSolutionParameterName, "The best symbolic regression solution."));
204      Parameters.Add(new LookupParameter<IntValue>(GenerationsParameterName, "The number of generations calculated so far."));
205      Parameters.Add(new LookupParameter<DoubleValue>(BestSolutionQualityParameterName, "The quality of the best symbolic regression solution."));
206      Parameters.Add(new LookupParameter<ResultCollection>(ResultsParameterName, "The result collection where the best symbolic regression solution should be stored."));
207      Parameters.Add(new LookupParameter<DoubleValue>(BestKnownQualityParameterName, "The best known (validation) quality achieved on the data set."));
208      Parameters.Add(new LookupParameter<DataTable>(VariableFrequenciesParameterName, "The variable frequencies table to use for the calculation of variable impacts"));
209    }
210
211    [StorableConstructor]
212    private FixedValidationBestScaledSymbolicRegressionSolutionAnalyzer(bool deserializing) : base() { }
213
214    public override IOperation Apply() {
215      var trees = SymbolicExpressionTree;
216
217      string targetVariable = ProblemData.TargetVariable.Value;
218
219      // select a random subset of rows in the validation set
220      int validationStart = ValidiationSamplesStart.Value;
221      int validationEnd = ValidationSamplesEnd.Value;
222      uint seed = (uint)Random.Next();
223      int count = (int)((validationEnd - validationStart) * RelativeNumberOfEvaluatedSamples.Value);
224      if (count == 0) count = 1;
225      IEnumerable<int> rows = RandomEnumerable.SampleRandomNumbers(seed, validationStart, validationEnd, count);
226
227      double upperEstimationLimit = UpperEstimationLimit != null ? UpperEstimationLimit.Value : double.PositiveInfinity;
228      double lowerEstimationLimit = LowerEstimationLimit != null ? LowerEstimationLimit.Value : double.NegativeInfinity;
229
230      double bestValidationRSquared = -1.0;
231      SymbolicExpressionTree bestTree = null;
232
233      foreach (var tree in trees) {
234        double validationRSquared = SymbolicRegressionPearsonsRSquaredEvaluator.Calculate(SymbolicExpressionTreeInterpreter, tree,
235          lowerEstimationLimit, upperEstimationLimit,
236          ProblemData.Dataset, targetVariable,
237         rows);
238
239        if (validationRSquared > bestValidationRSquared) {
240          bestValidationRSquared = validationRSquared;
241          bestTree = tree;
242        }
243      }
244
245
246      // if the best validation tree is better than the current best solution => update
247      if (BestSolutionQualityParameter.ActualValue == null || BestSolutionQualityParameter.ActualValue.Value < bestValidationRSquared) {
248        // calculate scaling parameters and validation MSE only for the best tree
249        // scale tree for solution
250        double alpha, beta;
251        double validationMSE = SymbolicRegressionScaledMeanSquaredErrorEvaluator.Calculate(SymbolicExpressionTreeInterpreter, bestTree,
252          lowerEstimationLimit, upperEstimationLimit,
253          ProblemData.Dataset, targetVariable,
254          rows, out beta, out alpha);
255
256        var scaledTree = SymbolicRegressionSolutionLinearScaler.Scale(bestTree, alpha, beta);
257        var model = new SymbolicRegressionModel((ISymbolicExpressionTreeInterpreter)SymbolicExpressionTreeInterpreter.Clone(),
258          scaledTree);
259        var solution = new SymbolicRegressionSolution(ProblemData, model, lowerEstimationLimit, upperEstimationLimit);
260        solution.Name = BestSolutionParameterName;
261        solution.Description = "Best solution on validation partition found over the whole run.";
262
263        BestSolutionParameter.ActualValue = solution;
264        BestSolutionQualityParameter.ActualValue = new DoubleValue(bestValidationRSquared);
265
266        BestSymbolicRegressionSolutionAnalyzer.UpdateBestSolutionResults(solution, ProblemData, Results, Generations, VariableFrequencies);
267      }
268
269      if (!Results.ContainsKey(BestSolutionQualityValuesParameterName)) {
270        Results.Add(new Result(BestSolutionQualityValuesParameterName, new DataTable(BestSolutionQualityValuesParameterName, BestSolutionQualityValuesParameterName)));
271        Results.Add(new Result(BestSolutionQualityParameterName, new DoubleValue()));
272        Results.Add(new Result(CurrentBestValidationQualityParameterName, new DoubleValue()));
273      }
274      Results[BestSolutionQualityParameterName].Value = new DoubleValue(BestSolutionQualityParameter.ActualValue.Value);
275      Results[CurrentBestValidationQualityParameterName].Value = new DoubleValue(bestValidationRSquared);
276
277      DataTable validationValues = (DataTable)Results[BestSolutionQualityValuesParameterName].Value;
278      AddValue(validationValues, BestSolutionQualityParameter.ActualValue.Value, BestSolutionQualityParameterName, BestSolutionQualityParameterName);
279      AddValue(validationValues, bestValidationRSquared, CurrentBestValidationQualityParameterName, CurrentBestValidationQualityParameterName);
280      return base.Apply();
281    }
282
283    [StorableHook(HookType.AfterDeserialization)]
284    private void Initialize() { }
285
286    private static void AddValue(DataTable table, double data, string name, string description) {
287      DataRow row;
288      table.Rows.TryGetValue(name, out row);
289      if (row == null) {
290        row = new DataRow(name, description);
291        row.Values.Add(data);
292        table.Rows.Add(row);
293      } else {
294        row.Values.Add(data);
295      }
296    }
297  }
298}
Note: See TracBrowser for help on using the repository browser.