Free cookie consent management tool by TermsFeed Policy Generator

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

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

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

File size: 18.6 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 SymbolicExpressionTreeParameterName = "SymbolicExpressionTree";
43    private const string SymbolicExpressionTreeInterpreterParameterName = "SymbolicExpressionTreeInterpreter";
44    private const string ProblemDataParameterName = "ProblemData";
45    private const string ValidationSamplesStartParameterName = "SamplesStart";
46    private const string ValidationSamplesEndParameterName = "SamplesEnd";
47    private const string QualityParameterName = "Quality";
48    private const string ScaledQualityParameterName = "ScaledQuality";
49    private const string UpperEstimationLimitParameterName = "UpperEstimationLimit";
50    private const string LowerEstimationLimitParameterName = "LowerEstimationLimit";
51    private const string AlphaParameterName = "Alpha";
52    private const string BetaParameterName = "Beta";
53    private const string BestSolutionParameterName = "Best solution (validation)";
54    private const string BestSolutionQualityParameterName = "Best solution quality (validation)";
55    private const string CurrentBestValidationQualityParameterName = "Current best validation quality";
56    private const string BestSolutionQualityValuesParameterName = "Validation Quality";
57    private const string ResultsParameterName = "Results";
58    private const string VariableFrequenciesParameterName = "VariableFrequencies";
59    private const string BestKnownQualityParameterName = "BestKnownQuality";
60    private const string GenerationsParameterName = "Generations";
61
62    private const string TrainingMeanSquaredErrorQualityParameterName = "Mean squared error (training)";
63    private const string MinTrainingMeanSquaredErrorQualityParameterName = "Min mean squared error (training)";
64    private const string MaxTrainingMeanSquaredErrorQualityParameterName = "Max mean squared error (training)";
65    private const string AverageTrainingMeanSquaredErrorQualityParameterName = "Average mean squared error (training)";
66    private const string BestTrainingMeanSquaredErrorQualityParameterName = "Best mean squared error (training)";
67
68    private const string TrainingAverageRelativeErrorQualityParameterName = "Average relative error (training)";
69    private const string MinTrainingAverageRelativeErrorQualityParameterName = "Min average relative error (training)";
70    private const string MaxTrainingAverageRelativeErrorQualityParameterName = "Max average relative error (training)";
71    private const string AverageTrainingAverageRelativeErrorQualityParameterName = "Average average relative error (training)";
72    private const string BestTrainingAverageRelativeErrorQualityParameterName = "Best average relative error (training)";
73
74    private const string TrainingRSquaredQualityParameterName = "R² (training)";
75    private const string MinTrainingRSquaredQualityParameterName = "Min R² (training)";
76    private const string MaxTrainingRSquaredQualityParameterName = "Max R² (training)";
77    private const string AverageTrainingRSquaredQualityParameterName = "Average R² (training)";
78    private const string BestTrainingRSquaredQualityParameterName = "Best R² (training)";
79
80    private const string TestMeanSquaredErrorQualityParameterName = "Mean squared error (test)";
81    private const string MinTestMeanSquaredErrorQualityParameterName = "Min mean squared error (test)";
82    private const string MaxTestMeanSquaredErrorQualityParameterName = "Max mean squared error (test)";
83    private const string AverageTestMeanSquaredErrorQualityParameterName = "Average mean squared error (test)";
84    private const string BestTestMeanSquaredErrorQualityParameterName = "Best mean squared error (test)";
85
86    private const string TestAverageRelativeErrorQualityParameterName = "Average relative error (test)";
87    private const string MinTestAverageRelativeErrorQualityParameterName = "Min average relative error (test)";
88    private const string MaxTestAverageRelativeErrorQualityParameterName = "Max average relative error (test)";
89    private const string AverageTestAverageRelativeErrorQualityParameterName = "Average average relative error (test)";
90    private const string BestTestAverageRelativeErrorQualityParameterName = "Best average relative error (test)";
91
92    private const string TestRSquaredQualityParameterName = "R² (test)";
93    private const string MinTestRSquaredQualityParameterName = "Min R² (test)";
94    private const string MaxTestRSquaredQualityParameterName = "Max R² (test)";
95    private const string AverageTestRSquaredQualityParameterName = "Average R² (test)";
96    private const string BestTestRSquaredQualityParameterName = "Best R² (test)";
97
98    private const string RSquaredValuesParameterName = "R²";
99    private const string MeanSquaredErrorValuesParameterName = "Mean squared error";
100    private const string RelativeErrorValuesParameterName = "Average relative error";
101
102    #region parameter properties
103    public ScopeTreeLookupParameter<SymbolicExpressionTree> SymbolicExpressionTreeParameter {
104      get { return (ScopeTreeLookupParameter<SymbolicExpressionTree>)Parameters[SymbolicExpressionTreeParameterName]; }
105    }
106    public ScopeTreeLookupParameter<DoubleValue> QualityParameter {
107      get { return (ScopeTreeLookupParameter<DoubleValue>)Parameters[QualityParameterName]; }
108    }
109    public ScopeTreeLookupParameter<DoubleValue> AlphaParameter {
110      get { return (ScopeTreeLookupParameter<DoubleValue>)Parameters[AlphaParameterName]; }
111    }
112    public ScopeTreeLookupParameter<DoubleValue> BetaParameter {
113      get { return (ScopeTreeLookupParameter<DoubleValue>)Parameters[BetaParameterName]; }
114    }
115    public IValueLookupParameter<ISymbolicExpressionTreeInterpreter> SymbolicExpressionTreeInterpreterParameter {
116      get { return (IValueLookupParameter<ISymbolicExpressionTreeInterpreter>)Parameters[SymbolicExpressionTreeInterpreterParameterName]; }
117    }
118    public IValueLookupParameter<DataAnalysisProblemData> ProblemDataParameter {
119      get { return (IValueLookupParameter<DataAnalysisProblemData>)Parameters[ProblemDataParameterName]; }
120    }
121    public IValueLookupParameter<IntValue> ValidationSamplesStartParameter {
122      get { return (IValueLookupParameter<IntValue>)Parameters[ValidationSamplesStartParameterName]; }
123    }
124    public IValueLookupParameter<IntValue> ValidationSamplesEndParameter {
125      get { return (IValueLookupParameter<IntValue>)Parameters[ValidationSamplesEndParameterName]; }
126    }
127    public IValueLookupParameter<DoubleValue> UpperEstimationLimitParameter {
128      get { return (IValueLookupParameter<DoubleValue>)Parameters[UpperEstimationLimitParameterName]; }
129    }
130    public IValueLookupParameter<DoubleValue> LowerEstimationLimitParameter {
131      get { return (IValueLookupParameter<DoubleValue>)Parameters[LowerEstimationLimitParameterName]; }
132    }
133    public ILookupParameter<SymbolicRegressionSolution> BestSolutionParameter {
134      get { return (ILookupParameter<SymbolicRegressionSolution>)Parameters[BestSolutionParameterName]; }
135    }
136    public ILookupParameter<IntValue> GenerationsParameter {
137      get { return (ILookupParameter<IntValue>)Parameters[GenerationsParameterName]; }
138    }
139    public ILookupParameter<DoubleValue> BestSolutionQualityParameter {
140      get { return (ILookupParameter<DoubleValue>)Parameters[BestSolutionQualityParameterName]; }
141    }
142    public ILookupParameter<ResultCollection> ResultsParameter {
143      get { return (ILookupParameter<ResultCollection>)Parameters[ResultsParameterName]; }
144    }
145    public ILookupParameter<DoubleValue> BestKnownQualityParameter {
146      get { return (ILookupParameter<DoubleValue>)Parameters[BestKnownQualityParameterName]; }
147    }
148    public ILookupParameter<DataTable> VariableFrequenciesParameter {
149      get { return (ILookupParameter<DataTable>)Parameters[VariableFrequenciesParameterName]; }
150    }
151
152    #endregion
153    #region properties
154    public ItemArray<SymbolicExpressionTree> SymbolicExpressionTree {
155      get { return SymbolicExpressionTreeParameter.ActualValue; }
156    }
157    public ItemArray<DoubleValue> Quality {
158      get { return QualityParameter.ActualValue; }
159    }
160    public ItemArray<DoubleValue> Alpha {
161      get { return AlphaParameter.ActualValue; }
162    }
163    public ItemArray<DoubleValue> Beta {
164      get { return BetaParameter.ActualValue; }
165    }
166    public ISymbolicExpressionTreeInterpreter SymbolicExpressionTreeInterpreter {
167      get { return SymbolicExpressionTreeInterpreterParameter.ActualValue; }
168    }
169    public DataAnalysisProblemData ProblemData {
170      get { return ProblemDataParameter.ActualValue; }
171    }
172    public IntValue ValidiationSamplesStart {
173      get { return ValidationSamplesStartParameter.ActualValue; }
174    }
175    public IntValue ValidationSamplesEnd {
176      get { return ValidationSamplesEndParameter.ActualValue; }
177    }
178    public DoubleValue UpperEstimationLimit {
179      get { return UpperEstimationLimitParameter.ActualValue; }
180    }
181    public DoubleValue LowerEstimationLimit {
182      get { return LowerEstimationLimitParameter.ActualValue; }
183    }
184    public ResultCollection Results {
185      get { return ResultsParameter.ActualValue; }
186    }
187    public DataTable VariableFrequencies {
188      get { return VariableFrequenciesParameter.ActualValue; }
189    }
190    public IntValue Generations {
191      get { return GenerationsParameter.ActualValue; }
192    }
193
194    #endregion
195
196    public FixedValidationBestScaledSymbolicRegressionSolutionAnalyzer()
197      : base() {
198      Parameters.Add(new ScopeTreeLookupParameter<SymbolicExpressionTree>(SymbolicExpressionTreeParameterName, "The symbolic expression trees to analyze."));
199      Parameters.Add(new ScopeTreeLookupParameter<DoubleValue>(QualityParameterName, "The quality of the symbolic expression trees to analyze."));
200      Parameters.Add(new ScopeTreeLookupParameter<DoubleValue>(AlphaParameterName, "The alpha parameter for linear scaling."));
201      Parameters.Add(new ScopeTreeLookupParameter<DoubleValue>(BetaParameterName, "The beta parameter for linear scaling."));
202      Parameters.Add(new ValueLookupParameter<ISymbolicExpressionTreeInterpreter>(SymbolicExpressionTreeInterpreterParameterName, "The interpreter that should be used for the analysis of symbolic expression trees."));
203      Parameters.Add(new ValueLookupParameter<DataAnalysisProblemData>(ProblemDataParameterName, "The problem data for which the symbolic expression tree is a solution."));
204      Parameters.Add(new ValueLookupParameter<IntValue>(ValidationSamplesStartParameterName, "The first index of the validation partition of the data set."));
205      Parameters.Add(new ValueLookupParameter<IntValue>(ValidationSamplesEndParameterName, "The last index of the validation partition of the data set."));
206      Parameters.Add(new ValueLookupParameter<DoubleValue>(UpperEstimationLimitParameterName, "The upper estimation limit that was set for the evaluation of the symbolic expression trees."));
207      Parameters.Add(new ValueLookupParameter<DoubleValue>(LowerEstimationLimitParameterName, "The lower estimation limit that was set for the evaluation of the symbolic expression trees."));
208      Parameters.Add(new LookupParameter<SymbolicRegressionSolution>(BestSolutionParameterName, "The best symbolic regression solution."));
209      Parameters.Add(new LookupParameter<IntValue>(GenerationsParameterName, "The number of generations calculated so far."));
210      Parameters.Add(new LookupParameter<DoubleValue>(BestSolutionQualityParameterName, "The quality of the best symbolic regression solution."));
211      Parameters.Add(new LookupParameter<ResultCollection>(ResultsParameterName, "The result collection where the best symbolic regression solution should be stored."));
212      Parameters.Add(new LookupParameter<DoubleValue>(BestKnownQualityParameterName, "The best known (validation) quality achieved on the data set."));
213      Parameters.Add(new LookupParameter<DataTable>(VariableFrequenciesParameterName, "The variable frequencies table to use for the calculation of variable impacts"));
214    }
215
216    [StorableConstructor]
217    private FixedValidationBestScaledSymbolicRegressionSolutionAnalyzer(bool deserializing) : base() { }
218
219    public override IOperation Apply() {
220      var alphas = Alpha;
221      var betas = Beta;
222      var trees = SymbolicExpressionTree;
223
224      IEnumerable<SymbolicExpressionTree> scaledTrees;
225      if (alphas.Length == trees.Length) {
226        scaledTrees = from i in Enumerable.Range(0, trees.Length)
227                      select SymbolicRegressionSolutionLinearScaler.Scale(trees[i], alphas[i].Value, betas[i].Value);
228      } else {
229        scaledTrees = trees;
230      }
231
232      string targetVariable = ProblemData.TargetVariable.Value;
233      int validationStart = ValidiationSamplesStart.Value;
234      int validationEnd = ValidationSamplesEnd.Value;
235      double upperEstimationLimit = UpperEstimationLimit != null ? UpperEstimationLimit.Value : double.PositiveInfinity;
236      double lowerEstimationLimit = LowerEstimationLimit != null ? LowerEstimationLimit.Value : double.NegativeInfinity;
237
238      double bestValidationMse = double.MaxValue;
239      SymbolicExpressionTree bestTree = null;
240
241      OnlineMeanSquaredErrorEvaluator mseEvaluator = new OnlineMeanSquaredErrorEvaluator();
242      foreach (var scaledTree in scaledTrees) {
243        double validationMse = SymbolicRegressionMeanSquaredErrorEvaluator.Calculate(SymbolicExpressionTreeInterpreter, scaledTree,
244          lowerEstimationLimit, upperEstimationLimit,
245          ProblemData.Dataset, targetVariable,
246         Enumerable.Range(validationStart, validationEnd - validationStart));
247
248        if (validationMse < bestValidationMse) {
249          bestValidationMse = validationMse;
250          bestTree = scaledTree;
251        }
252      }
253
254      if (BestSolutionQualityParameter.ActualValue == null || BestSolutionQualityParameter.ActualValue.Value > bestValidationMse) {
255        var model = new SymbolicRegressionModel((ISymbolicExpressionTreeInterpreter)SymbolicExpressionTreeInterpreter.Clone(),
256          bestTree);
257        var solution = new SymbolicRegressionSolution(ProblemData, model, lowerEstimationLimit, upperEstimationLimit);
258        solution.Name = BestSolutionParameterName;
259        solution.Description = "Best solution on validation partition found over the whole run.";
260
261        BestSolutionParameter.ActualValue = solution;
262        BestSolutionQualityParameter.ActualValue = new DoubleValue(bestValidationMse);
263
264        BestSymbolicRegressionSolutionAnalyzer.UpdateBestSolutionResults(solution, ProblemData, Results, Generations, VariableFrequencies);
265      }
266
267      if (!Results.ContainsKey(BestSolutionQualityValuesParameterName)) {
268        Results.Add(new Result(BestSolutionQualityValuesParameterName, new DataTable(BestSolutionQualityValuesParameterName, BestSolutionQualityValuesParameterName)));
269        Results.Add(new Result(BestSolutionQualityParameterName, new DoubleValue()));
270        Results.Add(new Result(CurrentBestValidationQualityParameterName, new DoubleValue()));
271      }
272      Results[BestSolutionQualityParameterName].Value = new DoubleValue(BestSolutionQualityParameter.ActualValue.Value);
273      Results[CurrentBestValidationQualityParameterName].Value = new DoubleValue(bestValidationMse);
274
275      DataTable validationValues = (DataTable)Results[BestSolutionQualityValuesParameterName].Value;
276      AddValue(validationValues, BestSolutionQualityParameter.ActualValue.Value, BestSolutionQualityParameterName, BestSolutionQualityParameterName);
277      AddValue(validationValues, bestValidationMse, CurrentBestValidationQualityParameterName, CurrentBestValidationQualityParameterName);
278      return base.Apply();
279    }
280
281    [StorableHook(HookType.AfterDeserialization)]
282    private void Initialize() {
283      if (!Parameters.ContainsKey(AlphaParameterName)) {
284        Parameters.Add(new ScopeTreeLookupParameter<DoubleValue>(AlphaParameterName, "The alpha parameter for linear scaling."));
285      }
286      if (!Parameters.ContainsKey(BetaParameterName)) {
287        Parameters.Add(new ScopeTreeLookupParameter<DoubleValue>(BetaParameterName, "The beta parameter for linear scaling."));
288      }
289      if (!Parameters.ContainsKey(VariableFrequenciesParameterName)) {
290        Parameters.Add(new LookupParameter<DataTable>(VariableFrequenciesParameterName, "The variable frequencies table to use for the calculation of variable impacts"));
291      }
292      if (!Parameters.ContainsKey(GenerationsParameterName)) {
293        Parameters.Add(new LookupParameter<IntValue>(GenerationsParameterName, "The number of generations calculated so far."));
294      }
295    }
296
297    private static void AddValue(DataTable table, double data, string name, string description) {
298      DataRow row;
299      table.Rows.TryGetValue(name, out row);
300      if (row == null) {
301        row = new DataRow(name, description);
302        row.Values.Add(data);
303        table.Rows.Add(row);
304      } else {
305        row.Values.Add(data);
306      }
307    }
308  }
309}
Note: See TracBrowser for help on using the repository browser.