source: trunk/sources/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression/3.4/SingleObjective/Evaluators/SymbolicRegressionConstantOptimizationEvaluator.cs @ 15448

Last change on this file since 15448 was 15448, checked in by mkommend, 23 months ago

#2852: Added counts of function and gradient evaluations by constants optimization as results.

File size: 19.0 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2016 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 HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Data;
28using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
29using HeuristicLab.Optimization;
30using HeuristicLab.Parameters;
31using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
32
33namespace HeuristicLab.Problems.DataAnalysis.Symbolic.Regression {
34  [Item("Constant Optimization Evaluator", "Calculates Pearson R² of a symbolic regression solution and optimizes the constant used.")]
35  [StorableClass]
36  public class SymbolicRegressionConstantOptimizationEvaluator : SymbolicRegressionSingleObjectiveEvaluator {
37    private const string ConstantOptimizationIterationsParameterName = "ConstantOptimizationIterations";
38    private const string ConstantOptimizationImprovementParameterName = "ConstantOptimizationImprovement";
39    private const string ConstantOptimizationProbabilityParameterName = "ConstantOptimizationProbability";
40    private const string ConstantOptimizationRowsPercentageParameterName = "ConstantOptimizationRowsPercentage";
41    private const string UpdateConstantsInTreeParameterName = "UpdateConstantsInSymbolicExpressionTree";
42    private const string UpdateVariableWeightsParameterName = "Update Variable Weights";
43
44    private const string FunctionEvaluationsResultParameterName = "Constants Optimization Function Evaluations";
45    private const string GradientEvaluationsResultParameterName = "Constants Optimization Gradient Evaluations";
46
47    public IFixedValueParameter<IntValue> ConstantOptimizationIterationsParameter {
48      get { return (IFixedValueParameter<IntValue>)Parameters[ConstantOptimizationIterationsParameterName]; }
49    }
50    public IFixedValueParameter<DoubleValue> ConstantOptimizationImprovementParameter {
51      get { return (IFixedValueParameter<DoubleValue>)Parameters[ConstantOptimizationImprovementParameterName]; }
52    }
53    public IFixedValueParameter<PercentValue> ConstantOptimizationProbabilityParameter {
54      get { return (IFixedValueParameter<PercentValue>)Parameters[ConstantOptimizationProbabilityParameterName]; }
55    }
56    public IFixedValueParameter<PercentValue> ConstantOptimizationRowsPercentageParameter {
57      get { return (IFixedValueParameter<PercentValue>)Parameters[ConstantOptimizationRowsPercentageParameterName]; }
58    }
59    public IFixedValueParameter<BoolValue> UpdateConstantsInTreeParameter {
60      get { return (IFixedValueParameter<BoolValue>)Parameters[UpdateConstantsInTreeParameterName]; }
61    }
62    public IFixedValueParameter<BoolValue> UpdateVariableWeightsParameter {
63      get { return (IFixedValueParameter<BoolValue>)Parameters[UpdateVariableWeightsParameterName]; }
64    }
65
66    public IResultParameter<IntValue> FunctionEvaluationsResultParameter {
67      get { return (IResultParameter<IntValue>)Parameters[FunctionEvaluationsResultParameterName]; }
68    }
69    public IResultParameter<IntValue> GradientEvaluationsResultParameter {
70      get { return (IResultParameter<IntValue>)Parameters[GradientEvaluationsResultParameterName]; }
71    }
72
73
74    public IntValue ConstantOptimizationIterations {
75      get { return ConstantOptimizationIterationsParameter.Value; }
76    }
77    public DoubleValue ConstantOptimizationImprovement {
78      get { return ConstantOptimizationImprovementParameter.Value; }
79    }
80    public PercentValue ConstantOptimizationProbability {
81      get { return ConstantOptimizationProbabilityParameter.Value; }
82    }
83    public PercentValue ConstantOptimizationRowsPercentage {
84      get { return ConstantOptimizationRowsPercentageParameter.Value; }
85    }
86    public bool UpdateConstantsInTree {
87      get { return UpdateConstantsInTreeParameter.Value.Value; }
88      set { UpdateConstantsInTreeParameter.Value.Value = value; }
89    }
90
91    public bool UpdateVariableWeights {
92      get { return UpdateVariableWeightsParameter.Value.Value; }
93      set { UpdateVariableWeightsParameter.Value.Value = value; }
94    }
95
96    public override bool Maximization {
97      get { return true; }
98    }
99
100    [StorableConstructor]
101    protected SymbolicRegressionConstantOptimizationEvaluator(bool deserializing) : base(deserializing) { }
102    protected SymbolicRegressionConstantOptimizationEvaluator(SymbolicRegressionConstantOptimizationEvaluator original, Cloner cloner)
103      : base(original, cloner) {
104    }
105    public SymbolicRegressionConstantOptimizationEvaluator()
106      : base() {
107      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), true));
108      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), true) { Hidden = true });
109      Parameters.Add(new FixedValueParameter<PercentValue>(ConstantOptimizationProbabilityParameterName, "Determines the probability that the constants are optimized", new PercentValue(1), true));
110      Parameters.Add(new FixedValueParameter<PercentValue>(ConstantOptimizationRowsPercentageParameterName, "Determines the percentage of the rows which should be used for constant optimization", new PercentValue(1), true));
111      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 });
112      Parameters.Add(new FixedValueParameter<BoolValue>(UpdateVariableWeightsParameterName, "Determines if the variable weights in the tree should be  optimized.", new BoolValue(true)) { Hidden = true });
113
114      Parameters.Add(new ResultParameter<IntValue>(FunctionEvaluationsResultParameterName, "The number of function evaluations performed by the constants optimization evaluator", "Results", new IntValue()));
115      Parameters.Add(new ResultParameter<IntValue>(GradientEvaluationsResultParameterName, "The number of gradient evaluations performed by the constants optimization evaluator", "Results", new IntValue()));
116    }
117
118    public override IDeepCloneable Clone(Cloner cloner) {
119      return new SymbolicRegressionConstantOptimizationEvaluator(this, cloner);
120    }
121
122    [StorableHook(HookType.AfterDeserialization)]
123    private void AfterDeserialization() {
124      if (!Parameters.ContainsKey(UpdateConstantsInTreeParameterName))
125        Parameters.Add(new FixedValueParameter<BoolValue>(UpdateConstantsInTreeParameterName, "Determines if the constants in the tree should be overwritten by the optimized constants.", new BoolValue(true)));
126      if (!Parameters.ContainsKey(UpdateVariableWeightsParameterName))
127        Parameters.Add(new FixedValueParameter<BoolValue>(UpdateVariableWeightsParameterName, "Determines if the variable weights in the tree should be  optimized.", new BoolValue(true)));
128
129      if (!Parameters.ContainsKey(FunctionEvaluationsResultParameterName))
130        Parameters.Add(new ResultParameter<IntValue>(FunctionEvaluationsResultParameterName, "The number of function evaluations performed by the constants optimization evaluator", "Results", new IntValue()));
131      if (!Parameters.ContainsKey(GradientEvaluationsResultParameterName))
132        Parameters.Add(new ResultParameter<IntValue>(GradientEvaluationsResultParameterName, "The number of gradient evaluations performed by the constants optimization evaluator", "Results", new IntValue()));
133    }
134
135    private static readonly object locker = new object();
136    public override IOperation InstrumentedApply() {
137      var solution = SymbolicExpressionTreeParameter.ActualValue;
138      double quality;
139      if (RandomParameter.ActualValue.NextDouble() < ConstantOptimizationProbability.Value) {
140        IEnumerable<int> constantOptimizationRows = GenerateRowsToEvaluate(ConstantOptimizationRowsPercentage.Value);
141        var counter = new EvaluationsCounter();
142        quality = OptimizeConstants(SymbolicDataAnalysisTreeInterpreterParameter.ActualValue, solution, ProblemDataParameter.ActualValue,
143           constantOptimizationRows, ApplyLinearScalingParameter.ActualValue.Value, ConstantOptimizationIterations.Value, updateVariableWeights: UpdateVariableWeights, lowerEstimationLimit: EstimationLimitsParameter.ActualValue.Lower, upperEstimationLimit: EstimationLimitsParameter.ActualValue.Upper, updateConstantsInTree: UpdateConstantsInTree, counter: counter);
144
145        if (ConstantOptimizationRowsPercentage.Value != RelativeNumberOfEvaluatedSamplesParameter.ActualValue.Value) {
146          var evaluationRows = GenerateRowsToEvaluate();
147          quality = SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator.Calculate(SymbolicDataAnalysisTreeInterpreterParameter.ActualValue, solution, EstimationLimitsParameter.ActualValue.Lower, EstimationLimitsParameter.ActualValue.Upper, ProblemDataParameter.ActualValue, evaluationRows, ApplyLinearScalingParameter.ActualValue.Value);
148        }
149
150        lock (locker) {
151          FunctionEvaluationsResultParameter.ActualValue.Value += counter.FunctionEvaluations;
152          GradientEvaluationsResultParameter.ActualValue.Value += counter.GradientEvaluations;
153        }
154
155      } else {
156        var evaluationRows = GenerateRowsToEvaluate();
157        quality = SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator.Calculate(SymbolicDataAnalysisTreeInterpreterParameter.ActualValue, solution, EstimationLimitsParameter.ActualValue.Lower, EstimationLimitsParameter.ActualValue.Upper, ProblemDataParameter.ActualValue, evaluationRows, ApplyLinearScalingParameter.ActualValue.Value);
158      }
159      QualityParameter.ActualValue = new DoubleValue(quality);
160
161      return base.InstrumentedApply();
162    }
163
164    public override double Evaluate(IExecutionContext context, ISymbolicExpressionTree tree, IRegressionProblemData problemData, IEnumerable<int> rows) {
165      SymbolicDataAnalysisTreeInterpreterParameter.ExecutionContext = context;
166      EstimationLimitsParameter.ExecutionContext = context;
167      ApplyLinearScalingParameter.ExecutionContext = context;
168      FunctionEvaluationsResultParameter.ExecutionContext = context;
169      GradientEvaluationsResultParameter.ExecutionContext = context;
170
171      // Pearson R² evaluator is used on purpose instead of the const-opt evaluator,
172      // because Evaluate() is used to get the quality of evolved models on
173      // different partitions of the dataset (e.g., best validation model)
174      double r2 = SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator.Calculate(SymbolicDataAnalysisTreeInterpreterParameter.ActualValue, tree, EstimationLimitsParameter.ActualValue.Lower, EstimationLimitsParameter.ActualValue.Upper, problemData, rows, ApplyLinearScalingParameter.ActualValue.Value);
175
176      SymbolicDataAnalysisTreeInterpreterParameter.ExecutionContext = null;
177      EstimationLimitsParameter.ExecutionContext = null;
178      ApplyLinearScalingParameter.ExecutionContext = null;
179      FunctionEvaluationsResultParameter.ExecutionContext = null;
180      GradientEvaluationsResultParameter.ExecutionContext = null;
181
182      return r2;
183    }
184
185    public class EvaluationsCounter {
186      public int FunctionEvaluations = 0;
187      public int GradientEvaluations = 0;
188    }
189
190    public static double OptimizeConstants(ISymbolicDataAnalysisExpressionTreeInterpreter interpreter,
191      ISymbolicExpressionTree tree, IRegressionProblemData problemData, IEnumerable<int> rows, bool applyLinearScaling,
192      int maxIterations, bool updateVariableWeights = true,
193      double lowerEstimationLimit = double.MinValue, double upperEstimationLimit = double.MaxValue,
194      bool updateConstantsInTree = true, Action<double[], double, object> iterationCallback = null, EvaluationsCounter counter = null) {
195
196      // numeric constants in the tree become variables for constant opt
197      // variables in the tree become parameters (fixed values) for constant opt
198      // for each parameter (variable in the original tree) we store the
199      // variable name, variable value (for factor vars) and lag as a DataForVariable object.
200      // A dictionary is used to find parameters
201      double[] initialConstants;
202      var parameters = new List<TreeToAutoDiffTermConverter.DataForVariable>();
203
204      TreeToAutoDiffTermConverter.ParametricFunction func;
205      TreeToAutoDiffTermConverter.ParametricFunctionGradient func_grad;
206      if (!TreeToAutoDiffTermConverter.TryConvertToAutoDiff(tree, updateVariableWeights, applyLinearScaling, out parameters, out initialConstants, out func, out func_grad))
207        throw new NotSupportedException("Could not optimize constants of symbolic expression tree due to not supported symbols used in the tree.");
208      if (parameters.Count == 0) return 0.0; // gkronber: constant expressions always have a R² of 0.0
209      var parameterEntries = parameters.ToArray(); // order of entries must be the same for x
210
211      //extract inital constants
212      double[] c;
213      if (applyLinearScaling) {
214        c = new double[initialConstants.Length + 2];
215        {
216          c[0] = 0.0;
217          c[1] = 1.0;
218          Array.Copy(initialConstants, 0, c, 2, initialConstants.Length);
219        }
220      } else {
221        c = (double[])initialConstants.Clone();
222      }
223
224      double originalQuality = SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator.Calculate(interpreter, tree, lowerEstimationLimit, upperEstimationLimit, problemData, rows, applyLinearScaling);
225
226      if (counter == null) counter = new EvaluationsCounter();
227      var rowEvaluationsCounter = new EvaluationsCounter();
228
229      alglib.lsfitstate state;
230      alglib.lsfitreport rep;
231      int retVal;
232
233      IDataset ds = problemData.Dataset;
234      double[,] x = new double[rows.Count(), parameters.Count];
235      int row = 0;
236      foreach (var r in rows) {
237        int col = 0;
238        foreach (var info in parameterEntries) {
239          if (ds.VariableHasType<double>(info.variableName)) {
240            x[row, col] = ds.GetDoubleValue(info.variableName, r + info.lag);
241          } else if (ds.VariableHasType<string>(info.variableName)) {
242            x[row, col] = ds.GetStringValue(info.variableName, r) == info.variableValue ? 1 : 0;
243          } else throw new InvalidProgramException("found a variable of unknown type");
244          col++;
245        }
246        row++;
247      }
248      double[] y = ds.GetDoubleValues(problemData.TargetVariable, rows).ToArray();
249      int n = x.GetLength(0);
250      int m = x.GetLength(1);
251      int k = c.Length;
252
253      alglib.ndimensional_pfunc function_cx_1_func = CreatePFunc(func);
254      alglib.ndimensional_pgrad function_cx_1_grad = CreatePGrad(func_grad);
255      alglib.ndimensional_rep xrep = (p, f, obj) => iterationCallback(p, f, obj);
256
257      try {
258        alglib.lsfitcreatefg(x, y, c, n, m, k, false, out state);
259        alglib.lsfitsetcond(state, 0.0, 0.0, maxIterations);
260        alglib.lsfitsetxrep(state, iterationCallback != null);
261        //alglib.lsfitsetgradientcheck(state, 0.001);
262        alglib.lsfitfit(state, function_cx_1_func, function_cx_1_grad, xrep, rowEvaluationsCounter);
263        alglib.lsfitresults(state, out retVal, out c, out rep);
264      } catch (ArithmeticException) {
265        return originalQuality;
266      } catch (alglib.alglibexception) {
267        return originalQuality;
268      }
269
270      counter.FunctionEvaluations += rowEvaluationsCounter.FunctionEvaluations / n;
271      counter.GradientEvaluations += rowEvaluationsCounter.GradientEvaluations / n;
272
273      //retVal == -7  => constant optimization failed due to wrong gradient
274      if (retVal != -7) {
275        if (applyLinearScaling) UpdateConstants(tree, c.Skip(2).ToArray(), updateVariableWeights);
276        else UpdateConstants(tree, c.ToArray(), updateVariableWeights);
277      }
278      var quality = SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator.Calculate(interpreter, tree, lowerEstimationLimit, upperEstimationLimit, problemData, rows, applyLinearScaling);
279
280      if (!updateConstantsInTree) UpdateConstants(tree, initialConstants.ToArray(), updateVariableWeights);
281
282      if (originalQuality - quality > 0.001 || double.IsNaN(quality)) {
283        UpdateConstants(tree, initialConstants.ToArray(), updateVariableWeights);
284        return originalQuality;
285      }
286      return quality;
287    }
288
289    private static void UpdateConstants(ISymbolicExpressionTree tree, double[] constants, bool updateVariableWeights) {
290      int i = 0;
291      foreach (var node in tree.Root.IterateNodesPrefix().OfType<SymbolicExpressionTreeTerminalNode>()) {
292        ConstantTreeNode constantTreeNode = node as ConstantTreeNode;
293        VariableTreeNodeBase variableTreeNodeBase = node as VariableTreeNodeBase;
294        FactorVariableTreeNode factorVarTreeNode = node as FactorVariableTreeNode;
295        if (constantTreeNode != null)
296          constantTreeNode.Value = constants[i++];
297        else if (updateVariableWeights && variableTreeNodeBase != null)
298          variableTreeNodeBase.Weight = constants[i++];
299        else if (factorVarTreeNode != null) {
300          for (int j = 0; j < factorVarTreeNode.Weights.Length; j++)
301            factorVarTreeNode.Weights[j] = constants[i++];
302        }
303      }
304    }
305
306    private static alglib.ndimensional_pfunc CreatePFunc(TreeToAutoDiffTermConverter.ParametricFunction func) {
307      return (double[] c, double[] x, ref double fx, object o) => {
308        fx = func(c, x);
309        var counter = (EvaluationsCounter)o;
310        counter.FunctionEvaluations++;
311      };
312    }
313
314    private static alglib.ndimensional_pgrad CreatePGrad(TreeToAutoDiffTermConverter.ParametricFunctionGradient func_grad) {
315      return (double[] c, double[] x, ref double fx, double[] grad, object o) => {
316        var tupel = func_grad(c, x);
317        fx = tupel.Item2;
318        Array.Copy(tupel.Item1, grad, grad.Length);
319        var counter = (EvaluationsCounter)o;
320        counter.GradientEvaluations++;
321      };
322    }
323    public static bool CanOptimizeConstants(ISymbolicExpressionTree tree) {
324      return TreeToAutoDiffTermConverter.IsCompatible(tree);
325    }
326  }
327}
Note: See TracBrowser for help on using the repository browser.