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

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

#2852: Adapted constants optimization and auto diff converter to not add linear scaling terms.

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