Free cookie consent management tool by TermsFeed Policy Generator

source: branches/3140_NumberSymbol/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression/3.4/SingleObjective/Evaluators/NMSESingleObjectiveConstraintsEvaluator.cs @ 18113

Last change on this file since 18113 was 18113, checked in by chaider, 2 years ago

#3140

  • Refactored ConstantOptimization ==> ParameterOptimization
File size: 11.5 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 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;
23using System.Collections.Generic;
24using System.Linq;
25using HEAL.Attic;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Data;
29using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
30using HeuristicLab.Parameters;
31
32namespace HeuristicLab.Problems.DataAnalysis.Symbolic.Regression {
33  [Item("NMSE Evaluator with shape-constraints (single-objective)", "Calculates NMSE of a symbolic regression solution and checks constraints. The fitness is a combination of NMSE and constraint violations.")]
34  [StorableType("27473973-DD8D-4375-997D-942E2280AE8E")]
35  public class NMSESingleObjectiveConstraintsEvaluator : SymbolicRegressionSingleObjectiveEvaluator {
36    #region Parameter/Properties
37
38    private const string OptimizeParametersParameterName = "OptimizeParameters";
39    private const string ParameterOptimizationIterationsParameterName = "ParameterOptimizationIterations";
40    private const string UseSoftConstraintsParameterName = "UseSoftConstraintsEvaluation";
41    private const string BoundsEstimatorParameterName = "BoundsEstimator";
42    private const string PenaltyFactorParameterName = "PenaltyFactor";
43
44
45    public IFixedValueParameter<BoolValue> OptimizerParametersParameter =>
46      (IFixedValueParameter<BoolValue>)Parameters[OptimizeParametersParameterName];
47
48    public IFixedValueParameter<IntValue> ParameterOptimizationIterationsParameter =>
49      (IFixedValueParameter<IntValue>)Parameters[ParameterOptimizationIterationsParameterName];
50
51    public IFixedValueParameter<BoolValue> UseSoftConstraintsParameter =>
52      (IFixedValueParameter<BoolValue>)Parameters[UseSoftConstraintsParameterName];
53
54    public IValueParameter<IBoundsEstimator> BoundsEstimatorParameter =>
55      (IValueParameter<IBoundsEstimator>)Parameters[BoundsEstimatorParameterName];
56    public IFixedValueParameter<DoubleValue> PenaltyFactorParameter =>
57      (IFixedValueParameter<DoubleValue>)Parameters[PenaltyFactorParameterName];
58
59    public bool OptimizeParameters {
60      get => OptimizerParametersParameter.Value.Value;
61      set => OptimizerParametersParameter.Value.Value = value;
62    }
63
64    public int ParameterOptimizationIterations {
65      get => ParameterOptimizationIterationsParameter.Value.Value;
66      set => ParameterOptimizationIterationsParameter.Value.Value = value;
67    }
68
69    public bool UseSoftConstraints {
70      get => UseSoftConstraintsParameter.Value.Value;
71      set => UseSoftConstraintsParameter.Value.Value = value;
72    }
73
74    public IBoundsEstimator BoundsEstimator {
75      get => BoundsEstimatorParameter.Value;
76      set => BoundsEstimatorParameter.Value = value;
77    }
78
79    public double PenalityFactor {
80      get => PenaltyFactorParameter.Value.Value;
81      set => PenaltyFactorParameter.Value.Value = value;
82    }
83
84
85    public override bool Maximization => false; // NMSE is minimized
86
87    #endregion
88
89    #region Constructors/Cloning
90
91    [StorableConstructor]
92    protected NMSESingleObjectiveConstraintsEvaluator(StorableConstructorFlag _) : base(_) { }
93
94    protected NMSESingleObjectiveConstraintsEvaluator(
95      NMSESingleObjectiveConstraintsEvaluator original, Cloner cloner) : base(original, cloner) { }
96
97    public NMSESingleObjectiveConstraintsEvaluator() {
98      Parameters.Add(new FixedValueParameter<BoolValue>(OptimizeParametersParameterName,
99        "Define whether optimization of numeric parameters is active or not (default: false).", new BoolValue(false)));
100      Parameters.Add(new FixedValueParameter<IntValue>(ParameterOptimizationIterationsParameterName,
101        "Define how many parameter optimization steps should be performed (default: 10).", new IntValue(10)));
102      Parameters.Add(new FixedValueParameter<BoolValue>(UseSoftConstraintsParameterName,
103        "Define whether the constraints are penalized by soft or hard constraints (default: false).", new BoolValue(false)));
104      Parameters.Add(new ValueParameter<IBoundsEstimator>(BoundsEstimatorParameterName,
105        "The estimator which is used to estimate output ranges of models (default: interval arithmetic).", new IntervalArithBoundsEstimator()));
106      Parameters.Add(new FixedValueParameter<DoubleValue>(PenaltyFactorParameterName,
107        "Punishment factor for constraint violations for soft constraint handling (fitness = NMSE + penaltyFactor * avg(violations)) (default: 1.0)", new DoubleValue(1.0)));
108    }
109
110    [StorableHook(HookType.AfterDeserialization)]
111    private void AfterDeserialization() {
112      if (!Parameters.ContainsKey(ParameterOptimizationIterationsParameterName)) {
113        if (Parameters.ContainsKey("ParameterOptimizationIterations")) {
114          Parameters.Add(new FixedValueParameter<IntValue>(ParameterOptimizationIterationsParameterName, "Define how many parameter optimization steps should be performed (default: 10).", (IntValue)Parameters["ParameterOptimizationIterations"].ActualValue));
115          Parameters.Remove("ParameterOptimizationIterations");
116        } else {
117          Parameters.Add(new FixedValueParameter<IntValue>(ParameterOptimizationIterationsParameterName, "Define how many parameter optimization steps should be performed (default: 10).", new IntValue(10)));
118        }
119      }
120
121    }
122
123    public override IDeepCloneable Clone(Cloner cloner) {
124      return new NMSESingleObjectiveConstraintsEvaluator(this, cloner);
125    }
126
127    #endregion
128
129    public override IOperation InstrumentedApply() {
130      var rows = GenerateRowsToEvaluate();
131      var tree = SymbolicExpressionTreeParameter.ActualValue;
132      var problemData = ProblemDataParameter.ActualValue;
133      var interpreter = SymbolicDataAnalysisTreeInterpreterParameter.ActualValue;
134      var estimationLimits = EstimationLimitsParameter.ActualValue;
135      var applyLinearScaling = ApplyLinearScalingParameter.ActualValue.Value;
136
137      if (OptimizeParameters) {
138        SymbolicRegressionParameterOptimizationEvaluator.OptimizeParameters(interpreter, tree, problemData, rows,
139          false, ParameterOptimizationIterations, true,
140          estimationLimits.Lower, estimationLimits.Upper);
141      } else {
142        if (applyLinearScaling) {
143          var rootNode = new ProgramRootSymbol().CreateTreeNode();
144          var startNode = new StartSymbol().CreateTreeNode();
145          var offset = tree.Root.GetSubtree(0) //Start
146                                .GetSubtree(0); //Offset
147          var scaling = offset.GetSubtree(0);
148
149          //Check if tree contains offset and scaling nodes
150          if (!(offset.Symbol is Addition) || !(scaling.Symbol is Multiplication))
151            throw new ArgumentException($"{ItemName} can only be used with LinearScalingGrammar.");
152
153          var t = (ISymbolicExpressionTreeNode)scaling.GetSubtree(0).Clone();
154          rootNode.AddSubtree(startNode);
155          startNode.AddSubtree(t);
156          var newTree = new SymbolicExpressionTree(rootNode);
157
158          //calculate alpha and beta for scaling
159          var estimatedValues = interpreter.GetSymbolicExpressionTreeValues(newTree, problemData.Dataset, rows);
160
161          var targetValues = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, rows);
162          OnlineLinearScalingParameterCalculator.Calculate(estimatedValues, targetValues, out var alpha, out var beta,
163            out var errorState);
164
165          if (errorState == OnlineCalculatorError.None) {
166            //Set alpha and beta to the scaling nodes from ia grammar
167            var offsetParameter = offset.GetSubtree(1) as NumberTreeNode;
168            offsetParameter.Value = alpha;
169            var scalingParameter = scaling.GetSubtree(1) as NumberTreeNode;
170            scalingParameter.Value = beta;
171          }
172        } // else: alpha and beta are evolved
173      }
174
175      var quality = Calculate(interpreter, tree, estimationLimits.Lower, estimationLimits.Upper, problemData, rows,
176        BoundsEstimator, UseSoftConstraints, PenalityFactor);
177      QualityParameter.ActualValue = new DoubleValue(quality);
178
179      return base.InstrumentedApply();
180    }
181
182    public static double Calculate(
183      ISymbolicDataAnalysisExpressionTreeInterpreter interpreter,
184      ISymbolicExpressionTree tree,
185      double lowerEstimationLimit, double upperEstimationLimit,
186      IRegressionProblemData problemData, IEnumerable<int> rows,
187      IBoundsEstimator estimator,
188      bool useSoftConstraints = false, double penaltyFactor = 1.0) {
189
190      var estimatedValues = interpreter.GetSymbolicExpressionTreeValues(tree, problemData.Dataset, rows);
191      var targetValues = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, rows);
192      var constraints = Enumerable.Empty<ShapeConstraint>();
193      if (problemData is ShapeConstrainedRegressionProblemData scProbData) {
194        constraints = scProbData.ShapeConstraints.EnabledConstraints;
195      }
196      var intervalCollection = problemData.VariableRanges;
197
198      var boundedEstimatedValues = estimatedValues.LimitToRange(lowerEstimationLimit, upperEstimationLimit);
199      var nmse = OnlineNormalizedMeanSquaredErrorCalculator.Calculate(targetValues, boundedEstimatedValues,
200        out var errorState);
201
202      if (errorState != OnlineCalculatorError.None) {
203        return 1.0;
204      }
205
206      var constraintViolations = IntervalUtil.GetConstraintViolations(constraints, estimator, intervalCollection, tree);
207
208      if (constraintViolations.Any(x => double.IsNaN(x) || double.IsInfinity(x))) {
209        return 1.0;
210      }
211
212      if (useSoftConstraints) {
213        if (penaltyFactor < 0.0)
214          throw new ArgumentException("The parameter has to be >= 0.0.", nameof(penaltyFactor));
215
216        var weightedViolationsAvg = constraints
217          .Zip(constraintViolations, (c, v) => c.Weight * v)
218          .Average();
219
220        return Math.Min(nmse, 1.0) + penaltyFactor * weightedViolationsAvg;
221      } else if (constraintViolations.Any(x => x > 0.0)) {
222        return 1.0;
223      }
224
225      return nmse;
226    }
227
228    public override double Evaluate(
229      IExecutionContext context, ISymbolicExpressionTree tree, IRegressionProblemData problemData,
230      IEnumerable<int> rows) {
231      SymbolicDataAnalysisTreeInterpreterParameter.ExecutionContext = context;
232      EstimationLimitsParameter.ExecutionContext = context;
233      ApplyLinearScalingParameter.ExecutionContext = context;
234
235      var nmse = Calculate(SymbolicDataAnalysisTreeInterpreterParameter.ActualValue, tree,
236        EstimationLimitsParameter.ActualValue.Lower, EstimationLimitsParameter.ActualValue.Upper,
237        problemData, rows, BoundsEstimator, UseSoftConstraints, PenalityFactor);
238
239      SymbolicDataAnalysisTreeInterpreterParameter.ExecutionContext = null;
240      EstimationLimitsParameter.ExecutionContext = null;
241      ApplyLinearScalingParameter.ExecutionContext = null;
242
243      return nmse;
244    }
245  }
246}
Note: See TracBrowser for help on using the repository browser.