Free cookie consent management tool by TermsFeed Policy Generator

source: branches/3076_IA_evaluators_analyzers/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression/3.4/MultiObjective/SymbolicRegressionMultiObjectiveMultiSoftConstraintEvaluator.cs @ 17743

Last change on this file since 17743 was 17743, checked in by chaider, 4 years ago

#3076 Added parameter to use smart splitting and extended constraint checking method for splitting

File size: 10.4 KB
Line 
1#region License Information
2
3/* HeuristicLab
4 * Copyright (C) Heuristic and Evolutionary Algorithms Laboratory (HEAL)
5 *
6 * This file is part of HeuristicLab.
7 *
8 * HeuristicLab is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * HeuristicLab is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
20 */
21
22#endregion
23
24using System;
25using System.Collections.Generic;
26using System.Linq;
27using HEAL.Attic;
28using HeuristicLab.Common;
29using HeuristicLab.Core;
30using HeuristicLab.Data;
31using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
32using HeuristicLab.Parameters;
33
34namespace HeuristicLab.Problems.DataAnalysis.Symbolic.Regression.MultiObjective {
35  [Item("Multi Soft Constraints Evaluator",
36    "Calculates the Person R² and the constraints violations of a symbolic regression solution.")]
37  [StorableType("8E9D76B7-ED9C-43E7-9898-01FBD3633880")]
38  public class
39    SymbolicRegressionMultiObjectiveMultiSoftConstraintEvaluator : SymbolicRegressionMultiObjectiveSplittingEvaluator {
40    public const string DimensionsParameterName = "Dimensions";
41
42    public IFixedValueParameter<IntValue> DimensionsParameter => (IFixedValueParameter<IntValue>)Parameters[DimensionsParameterName];
43
44
45    #region Constructors
46    public SymbolicRegressionMultiObjectiveMultiSoftConstraintEvaluator() {
47      Parameters.Add(new FixedValueParameter<IntValue>(DimensionsParameterName, new IntValue(2)));
48    }
49
50    [StorableConstructor]
51    protected SymbolicRegressionMultiObjectiveMultiSoftConstraintEvaluator(StorableConstructorFlag _) : base(_) { }
52
53    protected SymbolicRegressionMultiObjectiveMultiSoftConstraintEvaluator(
54      SymbolicRegressionMultiObjectiveMultiSoftConstraintEvaluator original, Cloner cloner) : base(original, cloner) { }
55
56    #endregion
57
58    [StorableHook(HookType.AfterDeserialization)]
59    private void AfterDeserialization() {
60      if(!Parameters.ContainsKey(DimensionsParameterName))
61        Parameters.Add(new FixedValueParameter<IntValue>(DimensionsParameterName, new IntValue(2)));
62    }
63
64    public override IDeepCloneable Clone(Cloner cloner) {
65      return new SymbolicRegressionMultiObjectiveMultiSoftConstraintEvaluator(this, cloner);
66    }
67
68
69    public override IOperation InstrumentedApply() {
70      var rows                  = GenerateRowsToEvaluate();
71      var solution              = SymbolicExpressionTreeParameter.ActualValue;
72      var problemData           = ProblemDataParameter.ActualValue;
73      var interpreter           = SymbolicDataAnalysisTreeInterpreterParameter.ActualValue;
74      var estimationLimits      = EstimationLimitsParameter.ActualValue;
75      var minIntervalWidth      = MinSplittingWidth;
76      var maxIntervalSplitDepth = MaxSplittingDepth;
77      var applyLinearScaling  = ApplyLinearScalingParameter.ActualValue.Value;
78
79      if (applyLinearScaling) {
80        //Check for interval arithmetic grammar
81        //remove scaling nodes for linear scaling evaluation
82        var                    rootNode  = new ProgramRootSymbol().CreateTreeNode();
83        var                    startNode = new StartSymbol().CreateTreeNode();
84        SymbolicExpressionTree newTree   = null;
85        foreach (var node in solution.IterateNodesPrefix())
86          if (node.Symbol.Name == "Scaling") {
87            for (var i = 0; i < node.SubtreeCount; ++i) startNode.AddSubtree(node.GetSubtree(i));
88            rootNode.AddSubtree(startNode);
89            newTree = new SymbolicExpressionTree(rootNode);
90            break;
91          }
92
93        //calculate alpha and beta for scaling
94        var estimatedValues = interpreter.GetSymbolicExpressionTreeValues(newTree, problemData.Dataset, rows);
95        var targetValues    = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, rows);
96        OnlineLinearScalingParameterCalculator.Calculate(estimatedValues, targetValues, out var alpha, out var beta,
97          out var errorState);
98        //Set alpha and beta to the scaling nodes from ia grammar
99        foreach (var node in solution.IterateNodesPrefix())
100          if (node.Symbol.Name == "Offset") {
101            node.RemoveSubtree(1);
102            var alphaNode = new ConstantTreeNode(new Constant()) {Value = alpha};
103            node.AddSubtree(alphaNode);
104          } else if (node.Symbol.Name == "Scaling") {
105            node.RemoveSubtree(1);
106            var betaNode = new ConstantTreeNode(new Constant()) {Value = beta};
107            node.AddSubtree(betaNode);
108          }
109      }
110
111      if (UseConstantOptimization)
112        SymbolicRegressionConstantOptimizationEvaluator.OptimizeConstants(interpreter, solution, problemData, rows,
113          false,
114          ConstantOptimizationIterations,
115          ConstantOptimizationUpdateVariableWeights,
116          estimationLimits.Lower,
117          estimationLimits.Upper);
118
119      var qualities = Calculate(interpreter, solution, estimationLimits.Lower, estimationLimits.Upper, problemData,
120        rows, UseIntervalSplitting);
121      QualitiesParameter.ActualValue = new DoubleArray(qualities);
122      return base.InstrumentedApply();
123    }
124
125    public override double[] Evaluate(IExecutionContext context, ISymbolicExpressionTree tree,
126                                      IRegressionProblemData problemData,
127                                      IEnumerable<int> rows) {
128      SymbolicDataAnalysisTreeInterpreterParameter.ExecutionContext = context;
129      EstimationLimitsParameter.ExecutionContext                    = context;
130      ApplyLinearScalingParameter.ExecutionContext                  = context;
131
132      var quality = Calculate(SymbolicDataAnalysisTreeInterpreterParameter.ActualValue, tree,
133        EstimationLimitsParameter.ActualValue.Lower, EstimationLimitsParameter.ActualValue.Upper,
134        problemData, rows, UseIntervalSplitting);
135
136      SymbolicDataAnalysisTreeInterpreterParameter.ExecutionContext = null;
137      EstimationLimitsParameter.ExecutionContext                    = null;
138      ApplyLinearScalingParameter.ExecutionContext                  = null;
139
140      return quality;
141    }
142
143
144    public static double[] Calculate(ISymbolicDataAnalysisExpressionTreeInterpreter interpreter,
145                                     ISymbolicExpressionTree solution, double lowerEstimationLimit,
146                                     double upperEstimationLimit,
147                                     IRegressionProblemData problemData, IEnumerable<int> rows, bool splitting) {
148      OnlineCalculatorError errorState;
149      var estimatedValues =
150        interpreter.GetSymbolicExpressionTreeValues(solution, problemData.Dataset, rows);
151      var targetValues = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, rows);
152
153      double nmse;
154
155      var boundedEstimatedValues = estimatedValues.LimitToRange(lowerEstimationLimit, upperEstimationLimit);
156      nmse = OnlineNormalizedMeanSquaredErrorCalculator.Calculate(targetValues, boundedEstimatedValues, out errorState);
157      if (errorState != OnlineCalculatorError.None) nmse = 1.0;
158
159      if (nmse > 1)
160        nmse = 1.0;
161
162      var constraints    = problemData.IntervalConstraints.Constraints.Where(c => c.Enabled);
163      var variableRanges = problemData.VariableRanges.GetReadonlyDictionary();
164
165      var objectives          = new List<double> {nmse};
166      var intervalInterpreter = new IntervalInterpreter(){UseIntervalSplitting = splitting};
167
168      var constraintObjectives = new List<double>();
169      foreach (var c in constraints) {
170        var penalty = ConstraintExceeded(c, intervalInterpreter, variableRanges,
171          solution);
172        var maxP = 0.1;
173
174        if (double.IsNaN(penalty) || double.IsInfinity(penalty) || penalty > maxP)
175          penalty = maxP;
176
177        constraintObjectives.Add(penalty);
178      }
179
180      objectives.AddRange(constraintObjectives);
181
182      return objectives.ToArray();
183    }
184
185    public static double ConstraintExceeded(IntervalConstraint constraint, IntervalInterpreter intervalInterpreter,
186                                            IReadOnlyDictionary<string, Interval> variableRanges,
187                                            ISymbolicExpressionTree solution) {
188      if (constraint.Variable != null && !variableRanges.ContainsKey(constraint.Variable))
189        throw new ArgumentException(
190          $"The given variable {constraint.Variable} in the constraint does not exists in the model.",
191          nameof(IntervalConstraintsParser));
192      Interval resultInterval;
193      if (!constraint.IsDerivative) {
194        resultInterval =
195          intervalInterpreter.GetSymbolicExpressionTreeInterval(solution, variableRanges, 0);
196      }
197      else {
198        var tree = solution;
199        for (var i = 0; i < constraint.NumberOfDerivations; ++i)
200          tree = DerivativeCalculator.Derive(tree, constraint.Variable);
201
202        resultInterval =
203          intervalInterpreter.GetSymbolicExpressionTreeInterval(tree, variableRanges, 0);
204      }
205     
206      //Calculate soft-constraints for intervals
207      if (constraint.Interval.Contains(resultInterval)) return 0;
208      var pLower = 0.0;
209      var pUpper = 0.0;
210      if (constraint.Interval.Contains(resultInterval.LowerBound))
211        pLower = 0;
212      else
213        pLower = constraint.Interval.LowerBound - resultInterval.LowerBound;
214
215      if (constraint.Interval.Contains(resultInterval.UpperBound))
216        pUpper = 0;
217      else
218        pUpper = resultInterval.UpperBound - constraint.Interval.UpperBound;
219      var penalty = Math.Abs(pLower) + Math.Abs(pUpper);
220
221      return penalty;
222    }
223
224    /*
225     * First objective is to maximize the Pearson R² value
226     * All following objectives have to be minimized ==> Constraints
227     */
228    public override IEnumerable<bool> Maximization {
229      get {
230        var objectives = new List<bool> {false};          //First NMSE ==> min
231        objectives.AddRange(Enumerable.Repeat(false, DimensionsParameter.Value.Value)); //Constraints ==> min
232       
233        return objectives;
234      }
235    }
236  }
237}
Note: See TracBrowser for help on using the repository browser.