Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2695_dataset-ids/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression/3.4/SingleObjective/Evaluators/SymbolicRegressionConstantOptimizationEvaluator.cs @ 15648

Last change on this file since 15648 was 14951, checked in by mkommend, 8 years ago

#2686: Code clean up in ConstantOptimization.

File size: 15.7 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) {
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, 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 = new double[initialConstants.Length + 2];
178      {
179        c[0] = 0.0;
180        c[1] = 1.0;
181        Array.Copy(initialConstants, 0, c, 2, initialConstants.Length);
182      }
183      double[] originalConstants = (double[])c.Clone();
184      double originalQuality = SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator.Calculate(interpreter, tree, lowerEstimationLimit, upperEstimationLimit, problemData, rows, applyLinearScaling);
185
186      alglib.lsfitstate state;
187      alglib.lsfitreport rep;
188      int retVal;
189
190      IDataset ds = problemData.Dataset;
191      double[,] x = new double[rows.Count(), parameters.Count];
192      int row = 0;
193      foreach (var r in rows) {
194        int col = 0;
195        foreach (var info in parameterEntries) {
196          if (ds.VariableHasType<double>(info.variableName)) {
197            x[row, col] = ds.GetDoubleValue(info.variableName, r + info.lag);
198          } else if (ds.VariableHasType<string>(info.variableName)) {
199            x[row, col] = ds.GetStringValue(info.variableName, r) == info.variableValue ? 1 : 0;
200          } else throw new InvalidProgramException("found a variable of unknown type");
201          col++;
202        }
203        row++;
204      }
205      double[] y = ds.GetDoubleValues(problemData.TargetVariable, rows).ToArray();
206      int n = x.GetLength(0);
207      int m = x.GetLength(1);
208      int k = c.Length;
209
210      alglib.ndimensional_pfunc function_cx_1_func = CreatePFunc(func);
211      alglib.ndimensional_pgrad function_cx_1_grad = CreatePGrad(func_grad);
212
213      try {
214        alglib.lsfitcreatefg(x, y, c, n, m, k, false, out state);
215        alglib.lsfitsetcond(state, 0.0, 0.0, maxIterations);
216        //alglib.lsfitsetgradientcheck(state, 0.001);
217        alglib.lsfitfit(state, function_cx_1_func, function_cx_1_grad, null, null);
218        alglib.lsfitresults(state, out retVal, out c, out rep);
219      }
220      catch (ArithmeticException) {
221        return originalQuality;
222      }
223      catch (alglib.alglibexception) {
224        return originalQuality;
225      }
226
227      //retVal == -7  => constant optimization failed due to wrong gradient
228      if (retVal != -7) UpdateConstants(tree, c.Skip(2).ToArray(), updateVariableWeights);
229      var quality = SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator.Calculate(interpreter, tree, lowerEstimationLimit, upperEstimationLimit, problemData, rows, applyLinearScaling);
230
231      if (!updateConstantsInTree) UpdateConstants(tree, originalConstants.Skip(2).ToArray(), updateVariableWeights);
232      if (originalQuality - quality > 0.001 || double.IsNaN(quality)) {
233        UpdateConstants(tree, originalConstants.Skip(2).ToArray(), updateVariableWeights);
234        return originalQuality;
235      }
236      return quality;
237    }
238
239    private static void UpdateConstants(ISymbolicExpressionTree tree, double[] constants, bool updateVariableWeights) {
240      int i = 0;
241      foreach (var node in tree.Root.IterateNodesPrefix().OfType<SymbolicExpressionTreeTerminalNode>()) {
242        ConstantTreeNode constantTreeNode = node as ConstantTreeNode;
243        VariableTreeNodeBase variableTreeNodeBase = node as VariableTreeNodeBase;
244        FactorVariableTreeNode factorVarTreeNode = node as FactorVariableTreeNode;
245        if (constantTreeNode != null)
246          constantTreeNode.Value = constants[i++];
247        else if (updateVariableWeights && variableTreeNodeBase != null)
248          variableTreeNodeBase.Weight = constants[i++];
249        else if (factorVarTreeNode != null) {
250          for (int j = 0; j < factorVarTreeNode.Weights.Length; j++)
251            factorVarTreeNode.Weights[j] = constants[i++];
252        }
253      }
254    }
255
256    private static alglib.ndimensional_pfunc CreatePFunc(TreeToAutoDiffTermConverter.ParametricFunction func) {
257      return (double[] c, double[] x, ref double fx, object o) => {
258        fx = func(c, x);
259      };
260    }
261
262    private static alglib.ndimensional_pgrad CreatePGrad(TreeToAutoDiffTermConverter.ParametricFunctionGradient func_grad) {
263      return (double[] c, double[] x, ref double fx, double[] grad, object o) => {
264        var tupel = func_grad(c, x);
265        fx = tupel.Item2;
266        Array.Copy(tupel.Item1, grad, grad.Length);
267      };
268    }
269    public static bool CanOptimizeConstants(ISymbolicExpressionTree tree) {
270      return TreeToAutoDiffTermConverter.IsCompatible(tree);
271    }
272  }
273}
Note: See TracBrowser for help on using the repository browser.