source: branches/3136_Structural_GP/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression/3.4/SingleObjective/Evaluators/SymbolicRegressionConstantOptimizationEvaluator.cs @ 18099

Last change on this file since 18099 was 18099, checked in by dpiringe, 8 months ago

#3136

  • set the default template to f(_) when loading a new problem data
  • fixed a bug which caused the drawing of uncolored SubFunctionTreeNodes after using the window splitter
  • implemented a method to paint nodes of SubFunctionTreeNode as colored nodes for ISymbolicDataAnalysisModel
File size: 22.2 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.Optimization;
31using HeuristicLab.Parameters;
32using HeuristicLab.Random;
33
34namespace HeuristicLab.Problems.DataAnalysis.Symbolic.Regression {
35  [Item("Constant Optimization Evaluator", "Calculates Pearson R² of a symbolic regression solution and optimizes the constant used.")]
36  [StorableType("24B68851-036D-4446-BD6F-3823E9028FF4")]
37  public class SymbolicRegressionConstantOptimizationEvaluator : SymbolicRegressionSingleObjectiveEvaluator {
38    private const string ConstantOptimizationIterationsParameterName = "ConstantOptimizationIterations";
39    private const string ConstantOptimizationImprovementParameterName = "ConstantOptimizationImprovement";
40    private const string ConstantOptimizationProbabilityParameterName = "ConstantOptimizationProbability";
41    private const string ConstantOptimizationRowsPercentageParameterName = "ConstantOptimizationRowsPercentage";
42    private const string UpdateConstantsInTreeParameterName = "UpdateConstantsInSymbolicExpressionTree";
43    private const string UpdateVariableWeightsParameterName = "Update Variable Weights";
44
45    private const string FunctionEvaluationsResultParameterName = "Constants Optimization Function Evaluations";
46    private const string GradientEvaluationsResultParameterName = "Constants Optimization Gradient Evaluations";
47    private const string CountEvaluationsParameterName = "Count Function and Gradient Evaluations";
48
49    public IFixedValueParameter<IntValue> ConstantOptimizationIterationsParameter {
50      get { return (IFixedValueParameter<IntValue>)Parameters[ConstantOptimizationIterationsParameterName]; }
51    }
52    public IFixedValueParameter<DoubleValue> ConstantOptimizationImprovementParameter {
53      get { return (IFixedValueParameter<DoubleValue>)Parameters[ConstantOptimizationImprovementParameterName]; }
54    }
55    public IFixedValueParameter<PercentValue> ConstantOptimizationProbabilityParameter {
56      get { return (IFixedValueParameter<PercentValue>)Parameters[ConstantOptimizationProbabilityParameterName]; }
57    }
58    public IFixedValueParameter<PercentValue> ConstantOptimizationRowsPercentageParameter {
59      get { return (IFixedValueParameter<PercentValue>)Parameters[ConstantOptimizationRowsPercentageParameterName]; }
60    }
61    public IFixedValueParameter<BoolValue> UpdateConstantsInTreeParameter {
62      get { return (IFixedValueParameter<BoolValue>)Parameters[UpdateConstantsInTreeParameterName]; }
63    }
64    public IFixedValueParameter<BoolValue> UpdateVariableWeightsParameter {
65      get { return (IFixedValueParameter<BoolValue>)Parameters[UpdateVariableWeightsParameterName]; }
66    }
67
68    public IResultParameter<IntValue> FunctionEvaluationsResultParameter {
69      get { return (IResultParameter<IntValue>)Parameters[FunctionEvaluationsResultParameterName]; }
70    }
71    public IResultParameter<IntValue> GradientEvaluationsResultParameter {
72      get { return (IResultParameter<IntValue>)Parameters[GradientEvaluationsResultParameterName]; }
73    }
74    public IFixedValueParameter<BoolValue> CountEvaluationsParameter {
75      get { return (IFixedValueParameter<BoolValue>)Parameters[CountEvaluationsParameterName]; }
76    }
77
78
79    public IntValue ConstantOptimizationIterations {
80      get { return ConstantOptimizationIterationsParameter.Value; }
81    }
82    public DoubleValue ConstantOptimizationImprovement {
83      get { return ConstantOptimizationImprovementParameter.Value; }
84    }
85    public PercentValue ConstantOptimizationProbability {
86      get { return ConstantOptimizationProbabilityParameter.Value; }
87    }
88    public PercentValue ConstantOptimizationRowsPercentage {
89      get { return ConstantOptimizationRowsPercentageParameter.Value; }
90    }
91    public bool UpdateConstantsInTree {
92      get { return UpdateConstantsInTreeParameter.Value.Value; }
93      set { UpdateConstantsInTreeParameter.Value.Value = value; }
94    }
95
96    public bool UpdateVariableWeights {
97      get { return UpdateVariableWeightsParameter.Value.Value; }
98      set { UpdateVariableWeightsParameter.Value.Value = value; }
99    }
100
101    public bool CountEvaluations {
102      get { return CountEvaluationsParameter.Value.Value; }
103      set { CountEvaluationsParameter.Value.Value = value; }
104    }
105
106    public override bool Maximization {
107      get { return true; }
108    }
109
110    [StorableConstructor]
111    protected SymbolicRegressionConstantOptimizationEvaluator(StorableConstructorFlag _) : base(_) { }
112    protected SymbolicRegressionConstantOptimizationEvaluator(SymbolicRegressionConstantOptimizationEvaluator original, Cloner cloner)
113      : base(original, cloner) {
114    }
115    public SymbolicRegressionConstantOptimizationEvaluator()
116      : base() {
117      Parameters.Add(new FixedValueParameter<IntValue>(ConstantOptimizationIterationsParameterName, "Determines how many iterations should be calculated while optimizing the constant of a symbolic expression tree (0 indicates other or default stopping criterion).", new IntValue(10)));
118      Parameters.Add(new FixedValueParameter<DoubleValue>(ConstantOptimizationImprovementParameterName, "Determines the relative improvement which must be achieved in the constant optimization to continue with it (0 indicates other or default stopping criterion).", new DoubleValue(0)) { Hidden = true });
119      Parameters.Add(new FixedValueParameter<PercentValue>(ConstantOptimizationProbabilityParameterName, "Determines the probability that the constants are optimized", new PercentValue(1)));
120      Parameters.Add(new FixedValueParameter<PercentValue>(ConstantOptimizationRowsPercentageParameterName, "Determines the percentage of the rows which should be used for constant optimization", new PercentValue(1)));
121      Parameters.Add(new FixedValueParameter<BoolValue>(UpdateConstantsInTreeParameterName, "Determines if the constants in the tree should be overwritten by the optimized constants.", new BoolValue(true)) { Hidden = true });
122      Parameters.Add(new FixedValueParameter<BoolValue>(UpdateVariableWeightsParameterName, "Determines if the variable weights in the tree should be  optimized.", new BoolValue(true)) { Hidden = true });
123
124      Parameters.Add(new FixedValueParameter<BoolValue>(CountEvaluationsParameterName, "Determines if function and gradient evaluation should be counted.", new BoolValue(false)));
125      Parameters.Add(new ResultParameter<IntValue>(FunctionEvaluationsResultParameterName, "The number of function evaluations performed by the constants optimization evaluator", "Results", new IntValue()));
126      Parameters.Add(new ResultParameter<IntValue>(GradientEvaluationsResultParameterName, "The number of gradient evaluations performed by the constants optimization evaluator", "Results", new IntValue()));
127    }
128
129    public override IDeepCloneable Clone(Cloner cloner) {
130      return new SymbolicRegressionConstantOptimizationEvaluator(this, cloner);
131    }
132
133    [StorableHook(HookType.AfterDeserialization)]
134    private void AfterDeserialization() {
135      if (!Parameters.ContainsKey(UpdateConstantsInTreeParameterName))
136        Parameters.Add(new FixedValueParameter<BoolValue>(UpdateConstantsInTreeParameterName, "Determines if the constants in the tree should be overwritten by the optimized constants.", new BoolValue(true)));
137      if (!Parameters.ContainsKey(UpdateVariableWeightsParameterName))
138        Parameters.Add(new FixedValueParameter<BoolValue>(UpdateVariableWeightsParameterName, "Determines if the variable weights in the tree should be  optimized.", new BoolValue(true)));
139
140      if (!Parameters.ContainsKey(CountEvaluationsParameterName))
141        Parameters.Add(new FixedValueParameter<BoolValue>(CountEvaluationsParameterName, "Determines if function and gradient evaluation should be counted.", new BoolValue(false)));
142
143      if (!Parameters.ContainsKey(FunctionEvaluationsResultParameterName))
144        Parameters.Add(new ResultParameter<IntValue>(FunctionEvaluationsResultParameterName, "The number of function evaluations performed by the constants optimization evaluator", "Results", new IntValue()));
145      if (!Parameters.ContainsKey(GradientEvaluationsResultParameterName))
146        Parameters.Add(new ResultParameter<IntValue>(GradientEvaluationsResultParameterName, "The number of gradient evaluations performed by the constants optimization evaluator", "Results", new IntValue()));
147    }
148
149    private static readonly object locker = new object();
150    public override IOperation InstrumentedApply() {
151      var solution = SymbolicExpressionTreeParameter.ActualValue;
152      double quality;
153      if (RandomParameter.ActualValue.NextDouble() < ConstantOptimizationProbability.Value) {
154        IEnumerable<int> constantOptimizationRows = GenerateRowsToEvaluate(ConstantOptimizationRowsPercentage.Value);
155        var counter = new EvaluationsCounter();
156        quality = OptimizeConstants(SymbolicDataAnalysisTreeInterpreterParameter.ActualValue, solution, ProblemDataParameter.ActualValue,
157           constantOptimizationRows, ApplyLinearScalingParameter.ActualValue.Value, ConstantOptimizationIterations.Value, updateVariableWeights: UpdateVariableWeights, lowerEstimationLimit: EstimationLimitsParameter.ActualValue.Lower, upperEstimationLimit: EstimationLimitsParameter.ActualValue.Upper, updateConstantsInTree: UpdateConstantsInTree, counter: counter);
158
159        if (ConstantOptimizationRowsPercentage.Value != RelativeNumberOfEvaluatedSamplesParameter.ActualValue.Value) {
160          var evaluationRows = GenerateRowsToEvaluate();
161          quality = SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator.Calculate(SymbolicDataAnalysisTreeInterpreterParameter.ActualValue, solution, EstimationLimitsParameter.ActualValue.Lower, EstimationLimitsParameter.ActualValue.Upper, ProblemDataParameter.ActualValue, evaluationRows, ApplyLinearScalingParameter.ActualValue.Value);
162        }
163
164        if (CountEvaluations) {
165          lock (locker) {
166            FunctionEvaluationsResultParameter.ActualValue.Value += counter.FunctionEvaluations;
167            GradientEvaluationsResultParameter.ActualValue.Value += counter.GradientEvaluations;
168          }
169        }
170
171      } else {
172        var evaluationRows = GenerateRowsToEvaluate();
173        quality = SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator.Calculate(SymbolicDataAnalysisTreeInterpreterParameter.ActualValue, solution, EstimationLimitsParameter.ActualValue.Lower, EstimationLimitsParameter.ActualValue.Upper, ProblemDataParameter.ActualValue, evaluationRows, ApplyLinearScalingParameter.ActualValue.Value);
174      }
175      QualityParameter.ActualValue = new DoubleValue(quality);
176
177      return base.InstrumentedApply();
178    }
179
180    public override double Evaluate(IRegressionProblemData problemData,
181      ISymbolicExpressionTree solution,
182      ISymbolicDataAnalysisExpressionTreeInterpreter interpreter,
183      IEnumerable<int> rows = null,
184      bool applyLinearScaling = true,
185      double lowerEstimationLimit = double.MinValue,
186      double upperEstimationLimit = double.MaxValue) {
187
188
189      var random = RandomParameter?.Value ?? new MersenneTwister((uint)DateTime.Now.Millisecond);
190      double quality;
191
192      var propability = random.NextDouble();
193      if (propability < ConstantOptimizationProbability.Value) {
194        var counter = new EvaluationsCounter();
195        quality = OptimizeConstants(
196          interpreter,
197          solution,
198          problemData,
199          rows ?? problemData.TrainingIndices,
200          applyLinearScaling,
201          ConstantOptimizationIterations.Value,
202          updateVariableWeights: UpdateVariableWeights,
203          lowerEstimationLimit: lowerEstimationLimit,
204          upperEstimationLimit: upperEstimationLimit,
205          updateConstantsInTree: UpdateConstantsInTree,
206          counter: counter);
207
208        if (ConstantOptimizationRowsPercentage.Value != RelativeNumberOfEvaluatedSamplesParameter.ActualValue.Value) { //TODO: remove this?
209          var evaluationRows = GenerateRowsToEvaluate();
210          quality = SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator.Calculate(
211            interpreter,
212            solution,
213            lowerEstimationLimit,
214            upperEstimationLimit,
215            problemData,
216            evaluationRows,
217            applyLinearScaling);
218        }
219
220      } else {
221        var evaluationRows = GenerateRowsToEvaluate();
222        quality = SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator.Calculate(
223          interpreter,
224          solution,
225          lowerEstimationLimit,
226          upperEstimationLimit,
227          problemData,
228          evaluationRows,
229          applyLinearScaling);
230      }
231      return quality;
232    }
233
234    public override double Evaluate(IExecutionContext context, ISymbolicExpressionTree tree, IRegressionProblemData problemData, IEnumerable<int> rows) {
235      SymbolicDataAnalysisTreeInterpreterParameter.ExecutionContext = context;
236      EstimationLimitsParameter.ExecutionContext = context;
237      ApplyLinearScalingParameter.ExecutionContext = context;
238      FunctionEvaluationsResultParameter.ExecutionContext = context;
239      GradientEvaluationsResultParameter.ExecutionContext = context;
240
241      // Pearson R² evaluator is used on purpose instead of the const-opt evaluator,
242      // because Evaluate() is used to get the quality of evolved models on
243      // different partitions of the dataset (e.g., best validation model)
244      double r2 = SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator.Calculate(SymbolicDataAnalysisTreeInterpreterParameter.ActualValue, tree, EstimationLimitsParameter.ActualValue.Lower, EstimationLimitsParameter.ActualValue.Upper, problemData, rows, ApplyLinearScalingParameter.ActualValue.Value);
245
246      SymbolicDataAnalysisTreeInterpreterParameter.ExecutionContext = null;
247      EstimationLimitsParameter.ExecutionContext = null;
248      ApplyLinearScalingParameter.ExecutionContext = null;
249      FunctionEvaluationsResultParameter.ExecutionContext = null;
250      GradientEvaluationsResultParameter.ExecutionContext = null;
251
252      return r2;
253    }
254
255    public class EvaluationsCounter {
256      public int FunctionEvaluations = 0;
257      public int GradientEvaluations = 0;
258    }
259
260    public static double OptimizeConstants(ISymbolicDataAnalysisExpressionTreeInterpreter interpreter,
261      ISymbolicExpressionTree tree, IRegressionProblemData problemData, IEnumerable<int> rows, bool applyLinearScaling,
262      int maxIterations, bool updateVariableWeights = true,
263      double lowerEstimationLimit = double.MinValue, double upperEstimationLimit = double.MaxValue,
264      bool updateConstantsInTree = true, Action<double[], double, object> iterationCallback = null, EvaluationsCounter counter = null) {
265
266      // Numeric constants in the tree become variables for parameter optimization.
267      // Variables in the tree become parameters (fixed values) for parameter optimization.
268      // For each parameter (variable in the original tree) we store the
269      // variable name, variable value (for factor vars) and lag as a DataForVariable object.
270      // A dictionary is used to find parameters
271      double[] initialConstants;
272      var parameters = new List<TreeToAutoDiffTermConverter.DataForVariable>();
273
274      TreeToAutoDiffTermConverter.ParametricFunction func;
275      TreeToAutoDiffTermConverter.ParametricFunctionGradient func_grad;
276      if (!TreeToAutoDiffTermConverter.TryConvertToAutoDiff(tree, updateVariableWeights, applyLinearScaling, out parameters, out initialConstants, out func, out func_grad))
277        throw new NotSupportedException("Could not optimize constants of symbolic expression tree due to not supported symbols used in the tree.");
278      if (parameters.Count == 0) return 0.0; // constant expressions always have a R² of 0.0
279      var parameterEntries = parameters.ToArray(); // order of entries must be the same for x
280
281      // extract inital constants
282      double[] c;
283      if (applyLinearScaling) {
284        c = new double[initialConstants.Length + 2];
285        c[0] = 0.0;
286        c[1] = 1.0;
287        Array.Copy(initialConstants, 0, c, 2, initialConstants.Length);
288      } else {
289        c = (double[])initialConstants.Clone();
290      }
291
292      double originalQuality = SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator.Calculate(interpreter, tree, lowerEstimationLimit, upperEstimationLimit, problemData, rows, applyLinearScaling);
293
294      if (counter == null) counter = new EvaluationsCounter();
295      var rowEvaluationsCounter = new EvaluationsCounter();
296
297      alglib.lsfitstate state;
298      alglib.lsfitreport rep;
299      int retVal;
300
301      IDataset ds = problemData.Dataset;
302      double[,] x = new double[rows.Count(), parameters.Count];
303      int row = 0;
304      foreach (var r in rows) {
305        int col = 0;
306        foreach (var info in parameterEntries) {
307          if (ds.VariableHasType<double>(info.variableName)) {
308            x[row, col] = ds.GetDoubleValue(info.variableName, r + info.lag);
309          } else if (ds.VariableHasType<string>(info.variableName)) {
310            x[row, col] = ds.GetStringValue(info.variableName, r) == info.variableValue ? 1 : 0;
311          } else throw new InvalidProgramException("found a variable of unknown type");
312          col++;
313        }
314        row++;
315      }
316      double[] y = ds.GetDoubleValues(problemData.TargetVariable, rows).ToArray();
317      int n = x.GetLength(0);
318      int m = x.GetLength(1);
319      int k = c.Length;
320
321      alglib.ndimensional_pfunc function_cx_1_func = CreatePFunc(func);
322      alglib.ndimensional_pgrad function_cx_1_grad = CreatePGrad(func_grad);
323      alglib.ndimensional_rep xrep = (p, f, obj) => iterationCallback(p, f, obj);
324
325      try {
326        alglib.lsfitcreatefg(x, y, c, n, m, k, false, out state);
327        alglib.lsfitsetcond(state, 0.0, maxIterations);
328        alglib.lsfitsetxrep(state, iterationCallback != null);
329        alglib.lsfitfit(state, function_cx_1_func, function_cx_1_grad, xrep, rowEvaluationsCounter);
330        alglib.lsfitresults(state, out retVal, out c, out rep);
331      } catch (ArithmeticException) {
332        return originalQuality;
333      } catch (alglib.alglibexception) {
334        return originalQuality;
335      }
336
337      counter.FunctionEvaluations += rowEvaluationsCounter.FunctionEvaluations / n;
338      counter.GradientEvaluations += rowEvaluationsCounter.GradientEvaluations / n;
339
340      //retVal == -7  => constant optimization failed due to wrong gradient
341      //          -8  => optimizer detected  NAN / INF  in  the target
342      //                 function and/ or gradient
343      if (retVal != -7 && retVal != -8) {
344        if (applyLinearScaling) {
345          var tmp = new double[c.Length - 2];
346          Array.Copy(c, 2, tmp, 0, tmp.Length);
347          UpdateConstants(tree, tmp, updateVariableWeights);
348        } else UpdateConstants(tree, c, updateVariableWeights);
349      }
350      var quality = SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator.Calculate(interpreter, tree, lowerEstimationLimit, upperEstimationLimit, problemData, rows, applyLinearScaling);
351
352      if (!updateConstantsInTree) UpdateConstants(tree, initialConstants, updateVariableWeights);
353
354      if (originalQuality - quality > 0.001 || double.IsNaN(quality)) {
355        UpdateConstants(tree, initialConstants, updateVariableWeights);
356        return originalQuality;
357      }
358      return quality;
359    }
360
361    private static void UpdateConstants(ISymbolicExpressionTree tree, double[] constants, bool updateVariableWeights) {
362      int i = 0;
363      foreach (var node in tree.Root.IterateNodesPrefix().OfType<SymbolicExpressionTreeTerminalNode>()) {
364        ConstantTreeNode constantTreeNode = node as ConstantTreeNode;
365        VariableTreeNodeBase variableTreeNodeBase = node as VariableTreeNodeBase;
366        FactorVariableTreeNode factorVarTreeNode = node as FactorVariableTreeNode;
367        if (constantTreeNode != null) {
368          if (constantTreeNode.Parent.Symbol is Power
369              && constantTreeNode.Parent.GetSubtree(1) == constantTreeNode) continue; // exponents in powers are not optimizated (see TreeToAutoDiffTermConverter)
370          constantTreeNode.Value = constants[i++];
371        } else if (updateVariableWeights && variableTreeNodeBase != null)
372          variableTreeNodeBase.Weight = constants[i++];
373        else if (factorVarTreeNode != null) {
374          for (int j = 0; j < factorVarTreeNode.Weights.Length; j++)
375            factorVarTreeNode.Weights[j] = constants[i++];
376        }
377      }
378    }
379
380    private static alglib.ndimensional_pfunc CreatePFunc(TreeToAutoDiffTermConverter.ParametricFunction func) {
381      return (double[] c, double[] x, ref double fx, object o) => {
382        fx = func(c, x);
383        var counter = (EvaluationsCounter)o;
384        counter.FunctionEvaluations++;
385      };
386    }
387
388    private static alglib.ndimensional_pgrad CreatePGrad(TreeToAutoDiffTermConverter.ParametricFunctionGradient func_grad) {
389      return (double[] c, double[] x, ref double fx, double[] grad, object o) => {
390        var tuple = func_grad(c, x);
391        fx = tuple.Item2;
392        Array.Copy(tuple.Item1, grad, grad.Length);
393        var counter = (EvaluationsCounter)o;
394        counter.GradientEvaluations++;
395      };
396    }
397    public static bool CanOptimizeConstants(ISymbolicExpressionTree tree) {
398      return TreeToAutoDiffTermConverter.IsCompatible(tree);
399    }
400  }
401}
Note: See TracBrowser for help on using the repository browser.