Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2971_named_intervals/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression/3.4/SingleObjective/Evaluators/SymbolicRegressionSingleObjectiveConstraintPearsonRSquaredEvaluator.cs @ 16596

Last change on this file since 16596 was 16596, checked in by chaider, 5 years ago

#2971

  • Extended evaluator with linear scaling
  • Added constructor to IntervalConstraint
File size: 8.7 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2018 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 HeuristicLab.Common;
25using HeuristicLab.Core;
26using HeuristicLab.Data;
27using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
28using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
29
30namespace HeuristicLab.Problems.DataAnalysis.Symbolic.Regression {
31  [Item("Pearson R² Constraint Evaluator", "Calculates the square of the pearson correlation coefficient (also known as coefficient of determination) of a symbolic regression solution.")]
32  [StorableClass]
33  public class SymbolicRegressionSingleObjectiveConstraintPearsonRSquaredEvaluator : SymbolicRegressionSingleObjectiveEvaluator {
34    [StorableConstructor]
35    protected SymbolicRegressionSingleObjectiveConstraintPearsonRSquaredEvaluator(bool deserializing) : base(deserializing) { }
36    protected SymbolicRegressionSingleObjectiveConstraintPearsonRSquaredEvaluator(SymbolicRegressionSingleObjectiveConstraintPearsonRSquaredEvaluator original, Cloner cloner)
37      : base(original, cloner) {
38    }
39    public override IDeepCloneable Clone(Cloner cloner) {
40      return new SymbolicRegressionSingleObjectiveConstraintPearsonRSquaredEvaluator(this, cloner);
41    }
42
43    public SymbolicRegressionSingleObjectiveConstraintPearsonRSquaredEvaluator() : base() { }
44
45    public override bool Maximization { get { return true; } }
46
47    public override IOperation InstrumentedApply() {
48      var solution = SymbolicExpressionTreeParameter.ActualValue;
49      IEnumerable<int> rows = GenerateRowsToEvaluate();
50
51      double quality = Calculate(SymbolicDataAnalysisTreeInterpreterParameter.ActualValue, solution, EstimationLimitsParameter.ActualValue.Lower, EstimationLimitsParameter.ActualValue.Upper, ProblemDataParameter.ActualValue, rows, ApplyLinearScalingParameter.ActualValue.Value);
52      QualityParameter.ActualValue = new DoubleValue(quality);
53      return base.InstrumentedApply();
54    }
55
56    public static double Calculate(ISymbolicDataAnalysisExpressionTreeInterpreter interpreter, ISymbolicExpressionTree solution, double lowerEstimationLimit, double upperEstimationLimit, IRegressionProblemData problemData, IEnumerable<int> rows, bool applyLinearScaling) {
57      IEnumerable<double> estimatedValues = interpreter.GetSymbolicExpressionTreeValues(solution, problemData.Dataset, rows);
58      IEnumerable<double> targetValues = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, rows);
59      OnlineCalculatorError errorState = OnlineCalculatorError.None;
60
61      IntervalConstraintsParser parser = new IntervalConstraintsParser();
62      var constraints = parser.Parse(((RegressionProblemData) problemData).IntervalConstraintsParameter.Value.Value);
63      var intervalInterpreter = new IntervalInterpreter();
64      var variableRanges = ((RegressionProblemData) problemData).VariableRangesParameter.Value.VariableIntervals;
65
66
67      //foreach (var constraint in constraints) {
68      //  if (constraint.Variable != null && !variableRanges.ContainsKey(constraint.Variable))
69      //    throw new ArgumentException($"The given variable {constraint.Variable} in the constraint does not exists in the model.", nameof(IntervalConstraintsParser));
70      //  if (!constraint.IsDerivation) {
71      //    var res = intervalInterpreter.GetSymbolicExressionTreeInterval(solution, variableRanges);
72      //    if (!constraint.Interval.Contains(res, constraint.InclusiveLowerBound,
73      //      constraint.InclusiveUpperBound)) {
74      //      return 0;
75      //    }
76      //  } else {
77      //    var tree = solution;
78      //    for (var i = 0; i < constraint.NumberOfDerivation; ++i) {
79      //      tree = DerivativeCalculator.Derive(tree, constraint.Variable);
80      //    }
81      //    var res = intervalInterpreter.GetSymbolicExressionTreeInterval(tree, variableRanges);
82      //    if (!constraint.Interval.Contains(res, constraint.InclusiveLowerBound,
83      //      constraint.InclusiveUpperBound)) {
84      //      return 0;
85      //    }
86      //  }
87      //}
88      // TODO
89      // m = new SymbolicRegressionModel(...)
90      // m.Scale();
91
92      // var e = m.GetEstimatedValues (TRAINING)
93      // OnlinePearsonCalc.Calculate(e, TARGET_TRAIING)
94     
95      // scaledTree = model.Tree;
96
97      // constraints mit scaledTree berechnen (auch die Ableitungen)
98
99      double r;
100      if (applyLinearScaling) {
101        var rCalculator = new OnlinePearsonsRCalculator();
102        CalculateWithScaling(targetValues, estimatedValues, lowerEstimationLimit, upperEstimationLimit, rCalculator, problemData.Dataset.Rows);
103        var model = new SymbolicRegressionModel(problemData.TargetVariable, solution, interpreter, lowerEstimationLimit, upperEstimationLimit);
104        model.Scale(problemData);
105        var e = model.GetEstimatedValues(problemData.Dataset, problemData.TrainingIndices);
106        var scaledTree = model.SymbolicExpressionTree;
107        errorState = rCalculator.ErrorState;
108        if (CheckConstraintsViolations(constraints, intervalInterpreter, variableRanges, scaledTree, out var val)) {
109          r = val;
110        } else {
111          r = rCalculator.R;
112        }
113      } else {
114        IEnumerable<double> boundedEstimatedValues = estimatedValues.LimitToRange(lowerEstimationLimit, upperEstimationLimit);
115        if (CheckConstraintsViolations(constraints, intervalInterpreter, variableRanges, solution, out var val)) {
116          r = val;
117        } else {
118          r = OnlinePearsonsRCalculator.Calculate(targetValues, boundedEstimatedValues, out errorState);
119        }
120      }
121      if (errorState != OnlineCalculatorError.None) return double.NaN;
122      return r*r;
123    }
124
125
126    public override double Evaluate(IExecutionContext context, ISymbolicExpressionTree tree,
127      IRegressionProblemData problemData, IEnumerable<int> rows) {
128      SymbolicDataAnalysisTreeInterpreterParameter.ExecutionContext = context;
129      EstimationLimitsParameter.ExecutionContext = context;
130      ApplyLinearScalingParameter.ExecutionContext = context;
131
132      double r2 = Calculate(SymbolicDataAnalysisTreeInterpreterParameter.ActualValue, tree,
133        EstimationLimitsParameter.ActualValue.Lower, EstimationLimitsParameter.ActualValue.Upper, problemData, rows,
134        ApplyLinearScalingParameter.ActualValue.Value);
135
136      SymbolicDataAnalysisTreeInterpreterParameter.ExecutionContext = null;
137      EstimationLimitsParameter.ExecutionContext = null;
138      ApplyLinearScalingParameter.ExecutionContext = null;
139
140      return r2;
141    }
142
143    private static bool CheckConstraintsViolations(List<IntervalConstraint> constraints, IntervalInterpreter intervalInterpreter,
144      Dictionary<string, Interval> variableRanges, ISymbolicExpressionTree solution, out double r) {
145      foreach (var constraint in constraints) {
146        if (constraint.Variable != null && !variableRanges.ContainsKey(constraint.Variable))
147          throw new ArgumentException($"The given variable {constraint.Variable} in the constraint does not exists in the model.", nameof(IntervalConstraintsParser));
148        if (!constraint.IsDerivation) {
149          var res = intervalInterpreter.GetSymbolicExressionTreeInterval(solution, variableRanges);
150          if (!constraint.Interval.Contains(res, constraint.InclusiveLowerBound,
151            constraint.InclusiveUpperBound)) {
152            r = 0;
153            return true;
154          }
155        } else {
156          var tree = solution;
157          for (var i = 0; i < constraint.NumberOfDerivation; ++i) {
158            tree = DerivativeCalculator.Derive(tree, constraint.Variable);
159          }
160          var res = intervalInterpreter.GetSymbolicExressionTreeInterval(tree, variableRanges);
161          if (!constraint.Interval.Contains(res, constraint.InclusiveLowerBound,
162            constraint.InclusiveUpperBound)) {
163            r = 0;
164            return true;
165          }
166        }
167      }
168      r = 1;
169      return false;
170    }
171  }
172}
Note: See TracBrowser for help on using the repository browser.