Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression/3.4/SingleObjective/Evaluators/NMSEConstraintsEvaluator.cs @ 17928

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

#3073 Fixed check for scaling nodes in ConstraintsEvaluators

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