Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression/3.4/SymbolicRegressionPhenotypicDiversityAnalyzer.cs @ 14353

Last change on this file since 14353 was 14353, checked in by bburlacu, 7 years ago

#2685: Add correction step for values miscalculated due to cyclical symbol dependencies in the grammar. Updated unit test.

File size: 7.9 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2016 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.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Data;
28using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
29using HeuristicLab.Optimization;
30using HeuristicLab.Parameters;
31using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
32
33namespace HeuristicLab.Problems.DataAnalysis.Symbolic.Regression {
34  [Item("SymbolicRegressionPhenotypicDiversityAnalyzer", "An analyzer which calculates diversity based on the phenotypic distance between trees")]
35  [StorableClass]
36  public class SymbolicRegressionPhenotypicDiversityAnalyzer : PopulationSimilarityAnalyzer,
37    ISymbolicDataAnalysisBoundedOperator, ISymbolicDataAnalysisInterpreterOperator, ISymbolicExpressionTreeAnalyzer {
38    #region parameter names
39    private const string SymbolicExpressionTreeParameterName = "SymbolicExpressionTree";
40    private const string EvaluatedValuesParameterName = "EstimatedValues";
41    private const string SymbolicDataAnalysisTreeInterpreterParameterName = "SymbolicExpressionTreeInterpreter";
42    private const string ProblemDataParameterName = "ProblemData";
43    private const string EstimationLimitsParameterName = "EstimationLimits";
44    private const string ApplyLinearScalingParameterName = "ApplyLinearScaling";
45    #endregion
46
47    #region parameter properties
48    public IScopeTreeLookupParameter<ISymbolicExpressionTree> SymbolicExpressionTreeParameter {
49      get { return (IScopeTreeLookupParameter<ISymbolicExpressionTree>)Parameters[SymbolicExpressionTreeParameterName]; }
50    }
51    private IScopeTreeLookupParameter<DoubleArray> EvaluatedValuesParameter {
52      get { return (IScopeTreeLookupParameter<DoubleArray>)Parameters[EvaluatedValuesParameterName]; }
53    }
54    public ILookupParameter<ISymbolicDataAnalysisExpressionTreeInterpreter> SymbolicDataAnalysisTreeInterpreterParameter {
55      get { return (ILookupParameter<ISymbolicDataAnalysisExpressionTreeInterpreter>)Parameters[SymbolicDataAnalysisTreeInterpreterParameterName]; }
56    }
57    public IValueLookupParameter<IRegressionProblemData> ProblemDataParameter {
58      get { return (IValueLookupParameter<IRegressionProblemData>)Parameters[ProblemDataParameterName]; }
59    }
60    public IValueLookupParameter<DoubleLimit> EstimationLimitsParameter {
61      get { return (IValueLookupParameter<DoubleLimit>)Parameters[EstimationLimitsParameterName]; }
62    }
63    public ILookupParameter<BoolValue> ApplyLinearScalingParameter {
64      get { return (ILookupParameter<BoolValue>)Parameters[ApplyLinearScalingParameterName]; }
65    }
66    #endregion
67
68    public SymbolicRegressionPhenotypicDiversityAnalyzer(IEnumerable<ISolutionSimilarityCalculator> validSimilarityCalculators)
69      : base(validSimilarityCalculators) {
70      #region add parameters
71      Parameters.Add(new ScopeTreeLookupParameter<ISymbolicExpressionTree>(SymbolicExpressionTreeParameterName, "The symbolic expression trees."));
72      Parameters.Add(new ScopeTreeLookupParameter<DoubleArray>(EvaluatedValuesParameterName, "Intermediate estimated values to be saved in the scopes."));
73      Parameters.Add(new LookupParameter<ISymbolicDataAnalysisExpressionTreeInterpreter>(SymbolicDataAnalysisTreeInterpreterParameterName, "The interpreter that should be used to calculate the output values of the symbolic data analysis tree."));
74      Parameters.Add(new ValueLookupParameter<IRegressionProblemData>(ProblemDataParameterName, "The problem data on which the symbolic data analysis solution should be evaluated."));
75      Parameters.Add(new ValueLookupParameter<DoubleLimit>(EstimationLimitsParameterName, "The upper and lower limit that should be used as cut off value for the output values of symbolic data analysis trees."));
76      Parameters.Add(new LookupParameter<BoolValue>(ApplyLinearScalingParameterName, "Whether or not to apply linear scaling to the estimated values"));
77      #endregion
78
79      UpdateCounterParameter.ActualName = "PhenotypicDiversityAnalyzerUpdateCounter";
80      DiversityResultName = "Phenotypic Diversity";
81    }
82
83    [StorableConstructor]
84    protected SymbolicRegressionPhenotypicDiversityAnalyzer(bool deserializing)
85      : base(deserializing) {
86    }
87
88    [StorableHook(HookType.AfterDeserialization)]
89    private void AfterDeserialization() {
90      if (!Parameters.ContainsKey(ApplyLinearScalingParameterName))
91        Parameters.Add(new LookupParameter<BoolValue>(ApplyLinearScalingParameterName, "Whether or not to apply linear scaling to the estimated values"));
92    }
93
94    public override IDeepCloneable Clone(Cloner cloner) {
95      return new SymbolicRegressionPhenotypicDiversityAnalyzer(this, cloner);
96    }
97
98    protected SymbolicRegressionPhenotypicDiversityAnalyzer(SymbolicRegressionPhenotypicDiversityAnalyzer original, Cloner cloner)
99      : base(original, cloner) {
100    }
101
102    public override IOperation Apply() {
103      int updateInterval = UpdateIntervalParameter.Value.Value;
104      IntValue updateCounter = UpdateCounterParameter.ActualValue;
105
106      if (updateCounter == null) {
107        updateCounter = new IntValue(updateInterval);
108        UpdateCounterParameter.ActualValue = updateCounter;
109      }
110
111      if (updateCounter.Value != updateInterval) return base.Apply();
112
113      var scopes = ExecutionContext.Scope.SubScopes;
114      var applyLinearScaling = ApplyLinearScalingParameter.ActualValue.Value;
115
116      foreach (var scope in scopes.Where(x => !x.Variables.ContainsKey("EstimatedValues"))) {
117        var tree = (ISymbolicExpressionTree)scope.Variables["SymbolicExpressionTree"].Value;
118        var interpreter = SymbolicDataAnalysisTreeInterpreterParameter.ActualValue;
119        var ds = ProblemDataParameter.ActualValue.Dataset;
120        var rows = ProblemDataParameter.ActualValue.TrainingIndices;
121        var estimatedValues = interpreter.GetSymbolicExpressionTreeValues(tree, ds, rows).ToArray();
122
123        var estimationLimits = EstimationLimitsParameter.ActualValue;
124
125        if (applyLinearScaling) {
126          var linearScalingCalculator = new OnlineLinearScalingParameterCalculator();
127          var targetValues = ds.GetDoubleValues(ProblemDataParameter.ActualValue.TargetVariable, rows);
128          int i = 0;
129          foreach (var target in targetValues) {
130            var estimated = estimatedValues[i];
131            if (!double.IsNaN(estimated) && !double.IsInfinity(estimated))
132              linearScalingCalculator.Add(estimated, target);
133            i++;
134          }
135          if (linearScalingCalculator.ErrorState == OnlineCalculatorError.None) {
136            var alpha = linearScalingCalculator.Alpha;
137            var beta = linearScalingCalculator.Beta;
138            for (i = 0; i < estimatedValues.Length; ++i) {
139              estimatedValues[i] = estimatedValues[i] * beta + alpha;
140            }
141          }
142        }
143        // add estimated values to escope
144        scope.Variables.Add(new Core.Variable("EstimatedValues", new DoubleArray(estimatedValues.LimitToRange(estimationLimits.Lower, estimationLimits.Upper).ToArray())));
145      }
146      return base.Apply();
147    }
148  }
149}
Note: See TracBrowser for help on using the repository browser.