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

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

#3076 Fixed description in MultiSoftConstraintEvaluator

File size: 8.9 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 NMSE and the constraints violations of a symbolic regression solution.")]
37  [StorableType("8E9D76B7-ED9C-43E7-9898-01FBD3633880")]
38  public class
39    SymbolicRegressionMultiObjectiveMultiSoftConstraintEvaluator : SymbolicRegressionMultiObjectiveEvaluator
40  {
41    public const string DimensionsParameterName = "Dimensions";
42    private const string BoundsEstimatorParameterName = "Bounds estimator";
43
44    public IFixedValueParameter<IntValue> DimensionsParameter =>
45      (IFixedValueParameter<IntValue>) Parameters[DimensionsParameterName];
46
47    public IValueParameter<IBoundsEstimator> BoundsEstimatorParameter =>
48      (IValueParameter<IBoundsEstimator>) Parameters[BoundsEstimatorParameterName];
49
50    public IBoundsEstimator BoundsEstimator {
51      get => BoundsEstimatorParameter.Value;
52      set => BoundsEstimatorParameter.Value = value;
53    }
54
55    #region Constructors
56
57    public SymbolicRegressionMultiObjectiveMultiSoftConstraintEvaluator() {
58      Parameters.Add(new FixedValueParameter<IntValue>(DimensionsParameterName, new IntValue(2)));
59      Parameters.Add(new ValueParameter<IBoundsEstimator>(BoundsEstimatorParameterName, new IABoundsEstimator()));
60    }
61
62    [StorableConstructor]
63    protected SymbolicRegressionMultiObjectiveMultiSoftConstraintEvaluator(StorableConstructorFlag _) : base(_) { }
64
65    protected SymbolicRegressionMultiObjectiveMultiSoftConstraintEvaluator(
66      SymbolicRegressionMultiObjectiveMultiSoftConstraintEvaluator original, Cloner cloner) : base(original, cloner) { }
67
68    #endregion
69
70    [StorableHook(HookType.AfterDeserialization)]
71    private void AfterDeserialization() {
72      if (!Parameters.ContainsKey(DimensionsParameterName))
73        Parameters.Add(new FixedValueParameter<IntValue>(DimensionsParameterName, new IntValue(2)));
74
75      if (!Parameters.ContainsKey(BoundsEstimatorParameterName))
76        Parameters.Add(new ValueParameter<IBoundsEstimator>(BoundsEstimatorParameterName, new IABoundsEstimator()));
77    }
78
79    public override IDeepCloneable Clone(Cloner cloner) {
80      return new SymbolicRegressionMultiObjectiveMultiSoftConstraintEvaluator(this, cloner);
81    }
82
83
84    public override IOperation InstrumentedApply() {
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;
91
92      if (UseConstantOptimization) {
93        SymbolicRegressionConstantOptimizationEvaluator.OptimizeConstants(interpreter, solution, problemData, rows,
94          false,
95          ConstantOptimizationIterations,
96          ConstantOptimizationUpdateVariableWeights,
97          estimationLimits.Lower,
98          estimationLimits.Upper);
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            }
113
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
133      var qualities = Calculate(interpreter, solution, estimationLimits.Lower, estimationLimits.Upper, problemData,
134        rows, BoundsEstimator);
135      QualitiesParameter.ActualValue = new DoubleArray(qualities);
136      return base.InstrumentedApply();
137    }
138
139    public override double[] Evaluate(
140      IExecutionContext context, ISymbolicExpressionTree tree,
141      IRegressionProblemData problemData,
142      IEnumerable<int> rows) {
143      SymbolicDataAnalysisTreeInterpreterParameter.ExecutionContext = context;
144      EstimationLimitsParameter.ExecutionContext = context;
145      ApplyLinearScalingParameter.ExecutionContext = context;
146
147      var quality = Calculate(SymbolicDataAnalysisTreeInterpreterParameter.ActualValue, tree,
148        EstimationLimitsParameter.ActualValue.Lower, EstimationLimitsParameter.ActualValue.Upper,
149        problemData, rows, BoundsEstimator);
150
151      SymbolicDataAnalysisTreeInterpreterParameter.ExecutionContext = null;
152      EstimationLimitsParameter.ExecutionContext = null;
153      ApplyLinearScalingParameter.ExecutionContext = null;
154
155      return quality;
156    }
157
158
159    public static double[] Calculate(
160      ISymbolicDataAnalysisExpressionTreeInterpreter interpreter,
161      ISymbolicExpressionTree solution, double lowerEstimationLimit,
162      double upperEstimationLimit,
163      IRegressionProblemData problemData, IEnumerable<int> rows, IBoundsEstimator estimator) {
164      OnlineCalculatorError errorState;
165      var estimatedValues = interpreter.GetSymbolicExpressionTreeValues(solution, problemData.Dataset, rows);
166      var targetValues = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, rows);
167      var constraints = problemData.IntervalConstraints.Constraints.Where(c => c.Enabled);
168      var intervalCollection = problemData.VariableRanges;
169
170      double nmse;
171
172      var boundedEstimatedValues = estimatedValues.LimitToRange(lowerEstimationLimit, upperEstimationLimit);
173      nmse = OnlineNormalizedMeanSquaredErrorCalculator.Calculate(targetValues, boundedEstimatedValues, out errorState);
174      if (errorState != OnlineCalculatorError.None) nmse = 1.0;
175
176      if (nmse > 1)
177        nmse = 1.0;
178
179      var objectives = new List<double> {nmse};
180      var results = IntervalUtil.IntervalConstraintsViolation(constraints, estimator, intervalCollection, solution);
181      foreach (var result in results) {
182        if (double.IsNaN(result) || double.IsInfinity(result)) {
183          objectives.Add(double.MaxValue);
184        } else {
185          objectives.Add(result);
186        }
187      }
188     
189      return objectives.ToArray();
190    }
191
192    /*
193     * First objective is to maximize the Pearson R² value
194     * All following objectives have to be minimized ==> Constraints
195     */
196
197    public override IEnumerable<bool> Maximization {
198      get {
199        var objectives = new List<bool> {false}; //First NMSE ==> min
200        objectives.AddRange(Enumerable.Repeat(false, DimensionsParameter.Value.Value)); //Constraints ==> min
201
202        return objectives;
203      }
204    }
205  }
206}
Note: See TracBrowser for help on using the repository browser.