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 @ 17794

Last change on this file since 17794 was 17794, checked in by chaider, 3 years ago

#3076 Removed SplittingEvaluator and MultiObjectiveConstraintAnalyzer

File size: 9.5 KB
RevLine 
[17623]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;
[17722]32using HeuristicLab.Parameters;
[17623]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
[17794]39    SymbolicRegressionMultiObjectiveMultiSoftConstraintEvaluator : SymbolicRegressionMultiObjectiveEvaluator
40  {
[17722]41    public const string DimensionsParameterName = "Dimensions";
[17769]42    private const string BoundsEstimatorParameterName = "Bounds estimator";
[17722]43
[17769]44    public IFixedValueParameter<IntValue> DimensionsParameter =>
45      (IFixedValueParameter<IntValue>) Parameters[DimensionsParameterName];
[17722]46
[17769]47    public IValueParameter<IBoundsEstimator> BoundsEstimatorParameter =>
48      (IValueParameter<IBoundsEstimator>) Parameters[BoundsEstimatorParameterName];
[17733]49
[17769]50    public IBoundsEstimator BoundsEstimator {
51      get => BoundsEstimatorParameter.Value;
52      set => BoundsEstimatorParameter.Value = value;
53    }
54
[17623]55    #region Constructors
[17769]56
[17722]57    public SymbolicRegressionMultiObjectiveMultiSoftConstraintEvaluator() {
58      Parameters.Add(new FixedValueParameter<IntValue>(DimensionsParameterName, new IntValue(2)));
[17769]59      Parameters.Add(new ValueParameter<IBoundsEstimator>(BoundsEstimatorParameterName, new IABoundsEstimator()));
[17722]60    }
[17623]61
62    [StorableConstructor]
63    protected SymbolicRegressionMultiObjectiveMultiSoftConstraintEvaluator(StorableConstructorFlag _) : base(_) { }
64
65    protected SymbolicRegressionMultiObjectiveMultiSoftConstraintEvaluator(
66      SymbolicRegressionMultiObjectiveMultiSoftConstraintEvaluator original, Cloner cloner) : base(original, cloner) { }
67
68    #endregion
69
[17722]70    [StorableHook(HookType.AfterDeserialization)]
71    private void AfterDeserialization() {
[17769]72      if (!Parameters.ContainsKey(DimensionsParameterName))
[17722]73        Parameters.Add(new FixedValueParameter<IntValue>(DimensionsParameterName, new IntValue(2)));
[17769]74
75      if (!Parameters.ContainsKey(BoundsEstimatorParameterName))
76        Parameters.Add(new ValueParameter<IBoundsEstimator>(BoundsEstimatorParameterName, new IABoundsEstimator()));
[17722]77    }
78
[17623]79    public override IDeepCloneable Clone(Cloner cloner) {
80      return new SymbolicRegressionMultiObjectiveMultiSoftConstraintEvaluator(this, cloner);
81    }
82
83
84    public override IOperation InstrumentedApply() {
[17769]85      var rows = GenerateRowsToEvaluate();
86      var solution = SymbolicExpressionTreeParameter.ActualValue;
87      var problemData = ProblemDataParameter.ActualValue;
88      var interpreter = SymbolicDataAnalysisTreeInterpreterParameter.ActualValue;
89      var estimationLimits = EstimationLimitsParameter.ActualValue;
90      var applyLinearScaling = ApplyLinearScalingParameter.ActualValue.Value;
[17623]91
[17769]92      if (UseConstantOptimization) {
[17623]93        SymbolicRegressionConstantOptimizationEvaluator.OptimizeConstants(interpreter, solution, problemData, rows,
[17705]94          false,
[17627]95          ConstantOptimizationIterations,
96          ConstantOptimizationUpdateVariableWeights,
97          estimationLimits.Lower,
98          estimationLimits.Upper);
[17769]99      } else {
100        if (applyLinearScaling) {
101          //Check for interval arithmetic grammar
102          //remove scaling nodes for linear scaling evaluation
103          var rootNode = new ProgramRootSymbol().CreateTreeNode();
104          var startNode = new StartSymbol().CreateTreeNode();
105          SymbolicExpressionTree newTree = null;
106          foreach (var node in solution.IterateNodesPrefix())
107            if (node.Symbol.Name == "Scaling") {
108              for (var i = 0; i < node.SubtreeCount; ++i) startNode.AddSubtree(node.GetSubtree(i));
109              rootNode.AddSubtree(startNode);
110              newTree = new SymbolicExpressionTree(rootNode);
111              break;
112            }
[17623]113
[17769]114          //calculate alpha and beta for scaling
115          var estimatedValues = interpreter.GetSymbolicExpressionTreeValues(newTree, problemData.Dataset, rows);
116          var targetValues = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, rows);
117          OnlineLinearScalingParameterCalculator.Calculate(estimatedValues, targetValues, out var alpha, out var beta,
118            out var errorState);
119          //Set alpha and beta to the scaling nodes from ia grammar
120          foreach (var node in solution.IterateNodesPrefix())
121            if (node.Symbol.Name == "Offset") {
122              node.RemoveSubtree(1);
123              var alphaNode = new ConstantTreeNode(new Constant()) {Value = alpha};
124              node.AddSubtree(alphaNode);
125            } else if (node.Symbol.Name == "Scaling") {
126              node.RemoveSubtree(1);
127              var betaNode = new ConstantTreeNode(new Constant()) {Value = beta};
128              node.AddSubtree(betaNode);
129            }
130        }
131      }
132
[17623]133      var qualities = Calculate(interpreter, solution, estimationLimits.Lower, estimationLimits.Upper, problemData,
[17769]134        rows, BoundsEstimator);
[17623]135      QualitiesParameter.ActualValue = new DoubleArray(qualities);
136      return base.InstrumentedApply();
137    }
138
[17769]139    public override double[] Evaluate(
140      IExecutionContext context, ISymbolicExpressionTree tree,
141      IRegressionProblemData problemData,
142      IEnumerable<int> rows) {
[17623]143      SymbolicDataAnalysisTreeInterpreterParameter.ExecutionContext = context;
[17769]144      EstimationLimitsParameter.ExecutionContext = context;
145      ApplyLinearScalingParameter.ExecutionContext = context;
[17623]146
147      var quality = Calculate(SymbolicDataAnalysisTreeInterpreterParameter.ActualValue, tree,
[17627]148        EstimationLimitsParameter.ActualValue.Lower, EstimationLimitsParameter.ActualValue.Upper,
[17769]149        problemData, rows, BoundsEstimator);
[17623]150
151      SymbolicDataAnalysisTreeInterpreterParameter.ExecutionContext = null;
[17769]152      EstimationLimitsParameter.ExecutionContext = null;
153      ApplyLinearScalingParameter.ExecutionContext = null;
[17623]154
155      return quality;
156    }
157
158
[17769]159    public static double[] Calculate(
160      ISymbolicDataAnalysisExpressionTreeInterpreter interpreter,
161      ISymbolicExpressionTree solution, double lowerEstimationLimit,
162      double upperEstimationLimit,
163      IRegressionProblemData problemData, IEnumerable<int> rows, IBoundsEstimator estimator) {
[17623]164      OnlineCalculatorError errorState;
[17769]165      var estimatedValues = interpreter.GetSymbolicExpressionTreeValues(solution, problemData.Dataset, rows);
[17623]166      var targetValues = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, rows);
[17769]167      var constraints = problemData.IntervalConstraints.Constraints.Where(c => c.Enabled);
168      var intervalCollection = problemData.VariableRanges;
[17623]169
170      double nmse;
171
172      var boundedEstimatedValues = estimatedValues.LimitToRange(lowerEstimationLimit, upperEstimationLimit);
173      nmse = OnlineNormalizedMeanSquaredErrorCalculator.Calculate(targetValues, boundedEstimatedValues, out errorState);
[17705]174      if (errorState != OnlineCalculatorError.None) nmse = 1.0;
[17623]175
176      if (nmse > 1)
[17705]177        nmse = 1.0;
[17623]178
179
[17769]180      var objectives = new List<double> {nmse};
181      ////var intervalInterpreter = new IntervalInterpreter() {UseIntervalSplitting = splitting};
[17623]182
[17769]183      //var constraintObjectives = new List<double>();
184      //foreach (var c in constraints) {
185      //  var penalty = ConstraintExceeded(c, intervalInterpreter, variableRanges,
186      //    solution);
187      //  var maxP = 0.1;
[17623]188
[17769]189      //  if (double.IsNaN(penalty) || double.IsInfinity(penalty) || penalty > maxP)
190      //    penalty = maxP;
[17623]191
[17769]192      //  constraintObjectives.Add(penalty);
193      //}
[17623]194
[17769]195      //objectives.AddRange(constraintObjectives);
[17623]196
[17769]197      //return objectives.ToArray();
198
199      var results = IntervalUtil.IntervalConstraintsViolation(constraints, estimator, intervalCollection, solution);
[17774]200      foreach (var result in results) {
201        if (double.IsNaN(result) || double.IsInfinity(result)) {
202          objectives.Add(double.MaxValue);
203        } else {
204          objectives.Add(result);
205        }
206      }
207     
[17623]208      return objectives.ToArray();
209    }
210
211    /*
212     * First objective is to maximize the Pearson R² value
213     * All following objectives have to be minimized ==> Constraints
214     */
[17769]215
[17623]216    public override IEnumerable<bool> Maximization {
217      get {
[17769]218        var objectives = new List<bool> {false}; //First NMSE ==> min
[17722]219        objectives.AddRange(Enumerable.Repeat(false, DimensionsParameter.Value.Value)); //Constraints ==> min
[17769]220
[17623]221        return objectives;
222      }
223    }
224  }
225}
Note: See TracBrowser for help on using the repository browser.