Free cookie consent management tool by TermsFeed Policy Generator

source: branches/MathNetNumerics-Exploration-2789/HeuristicLab.Algorithms.DataAnalysis.Experimental/SymbolicRegressionConstantOptimizationEvaluator.cs @ 15311

Last change on this file since 15311 was 15311, checked in by gkronber, 7 years ago

#2789 exploration of alglib solver for non-linear optimization with non-linear constraints

File size: 19.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 System.Runtime.Remoting.Channels;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Data;
29using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
30using HeuristicLab.Parameters;
31using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
32using HeuristicLab.Problems.DataAnalysis;
33using HeuristicLab.Problems.DataAnalysis.Symbolic;
34using HeuristicLab.Problems.DataAnalysis.Symbolic.Regression;
35
36namespace HeuristicLab.Algorithms.DataAnalysis.Experimental {
37  [Item("Constant Optimization Evaluator with Constraints", "")]
38  [StorableClass]
39  public class SymbolicRegressionConstantOptimizationEvaluator : SymbolicRegressionSingleObjectiveEvaluator {
40    private const string ConstantOptimizationIterationsParameterName = "ConstantOptimizationIterations";
41    private const string ConstantOptimizationImprovementParameterName = "ConstantOptimizationImprovement";
42    private const string ConstantOptimizationProbabilityParameterName = "ConstantOptimizationProbability";
43    private const string ConstantOptimizationRowsPercentageParameterName = "ConstantOptimizationRowsPercentage";
44    private const string UpdateConstantsInTreeParameterName = "UpdateConstantsInSymbolicExpressionTree";
45    private const string UpdateVariableWeightsParameterName = "Update Variable Weights";
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
67    public IntValue ConstantOptimizationIterations {
68      get { return ConstantOptimizationIterationsParameter.Value; }
69    }
70    public DoubleValue ConstantOptimizationImprovement {
71      get { return ConstantOptimizationImprovementParameter.Value; }
72    }
73    public PercentValue ConstantOptimizationProbability {
74      get { return ConstantOptimizationProbabilityParameter.Value; }
75    }
76    public PercentValue ConstantOptimizationRowsPercentage {
77      get { return ConstantOptimizationRowsPercentageParameter.Value; }
78    }
79    public bool UpdateConstantsInTree {
80      get { return UpdateConstantsInTreeParameter.Value.Value; }
81      set { UpdateConstantsInTreeParameter.Value.Value = value; }
82    }
83
84    public bool UpdateVariableWeights {
85      get { return UpdateVariableWeightsParameter.Value.Value; }
86      set { UpdateVariableWeightsParameter.Value.Value = value; }
87    }
88
89    public override bool Maximization {
90      get { return true; }
91    }
92
93    [StorableConstructor]
94    protected SymbolicRegressionConstantOptimizationEvaluator(bool deserializing) : base(deserializing) { }
95    protected SymbolicRegressionConstantOptimizationEvaluator(SymbolicRegressionConstantOptimizationEvaluator original, Cloner cloner)
96      : base(original, cloner) {
97    }
98    public SymbolicRegressionConstantOptimizationEvaluator()
99      : base() {
100      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));
101      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 });
102      Parameters.Add(new FixedValueParameter<PercentValue>(ConstantOptimizationProbabilityParameterName, "Determines the probability that the constants are optimized", new PercentValue(1), true));
103      Parameters.Add(new FixedValueParameter<PercentValue>(ConstantOptimizationRowsPercentageParameterName, "Determines the percentage of the rows which should be used for constant optimization", new PercentValue(1), true));
104      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 });
105      Parameters.Add(new FixedValueParameter<BoolValue>(UpdateVariableWeightsParameterName, "Determines if the variable weights in the tree should be  optimized.", new BoolValue(true)) { Hidden = true });
106    }
107
108    public override IDeepCloneable Clone(Cloner cloner) {
109      return new SymbolicRegressionConstantOptimizationEvaluator(this, cloner);
110    }
111
112    [StorableHook(HookType.AfterDeserialization)]
113    private void AfterDeserialization() {
114      if (!Parameters.ContainsKey(UpdateConstantsInTreeParameterName))
115        Parameters.Add(new FixedValueParameter<BoolValue>(UpdateConstantsInTreeParameterName, "Determines if the constants in the tree should be overwritten by the optimized constants.", new BoolValue(true)));
116      if (!Parameters.ContainsKey(UpdateVariableWeightsParameterName))
117        Parameters.Add(new FixedValueParameter<BoolValue>(UpdateVariableWeightsParameterName, "Determines if the variable weights in the tree should be  optimized.", new BoolValue(true)));
118    }
119
120    public override IOperation InstrumentedApply() {
121      var solution = SymbolicExpressionTreeParameter.ActualValue;
122      double quality;
123      if (RandomParameter.ActualValue.NextDouble() < ConstantOptimizationProbability.Value) {
124        IEnumerable<int> constantOptimizationRows = GenerateRowsToEvaluate(ConstantOptimizationRowsPercentage.Value);
125        quality = OptimizeConstants(SymbolicDataAnalysisTreeInterpreterParameter.ActualValue, solution, ProblemDataParameter.ActualValue,
126           constantOptimizationRows, ApplyLinearScalingParameter.ActualValue.Value, ConstantOptimizationIterations.Value, updateVariableWeights: UpdateVariableWeights, lowerEstimationLimit: EstimationLimitsParameter.ActualValue.Lower, upperEstimationLimit: EstimationLimitsParameter.ActualValue.Upper, updateConstantsInTree: UpdateConstantsInTree);
127
128        if (ConstantOptimizationRowsPercentage.Value != RelativeNumberOfEvaluatedSamplesParameter.ActualValue.Value) {
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      } else {
133        var evaluationRows = GenerateRowsToEvaluate();
134        quality = SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator.Calculate(SymbolicDataAnalysisTreeInterpreterParameter.ActualValue, solution, EstimationLimitsParameter.ActualValue.Lower, EstimationLimitsParameter.ActualValue.Upper, ProblemDataParameter.ActualValue, evaluationRows, ApplyLinearScalingParameter.ActualValue.Value);
135      }
136      QualityParameter.ActualValue = new DoubleValue(quality);
137
138      return base.InstrumentedApply();
139    }
140
141    public override double Evaluate(IExecutionContext context, ISymbolicExpressionTree tree, IRegressionProblemData problemData, IEnumerable<int> rows) {
142      SymbolicDataAnalysisTreeInterpreterParameter.ExecutionContext = context;
143      EstimationLimitsParameter.ExecutionContext = context;
144      ApplyLinearScalingParameter.ExecutionContext = context;
145
146      // Pearson R² evaluator is used on purpose instead of the const-opt evaluator,
147      // because Evaluate() is used to get the quality of evolved models on
148      // different partitions of the dataset (e.g., best validation model)
149      double r2 = SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator.Calculate(SymbolicDataAnalysisTreeInterpreterParameter.ActualValue, tree, EstimationLimitsParameter.ActualValue.Lower, EstimationLimitsParameter.ActualValue.Upper, problemData, rows, ApplyLinearScalingParameter.ActualValue.Value);
150
151      SymbolicDataAnalysisTreeInterpreterParameter.ExecutionContext = null;
152      EstimationLimitsParameter.ExecutionContext = null;
153      ApplyLinearScalingParameter.ExecutionContext = null;
154
155      return r2;
156    }
157
158    public static double OptimizeConstants(ISymbolicDataAnalysisExpressionTreeInterpreter interpreter,
159      ISymbolicExpressionTree tree, IRegressionProblemData problemData, IEnumerable<int> rows, bool applyLinearScaling,
160      int maxIterations, bool updateVariableWeights = true,
161      double lowerEstimationLimit = double.MinValue, double upperEstimationLimit = double.MaxValue,
162      bool updateConstantsInTree = true) {
163
164      // numeric constants in the tree become variables for constant opt
165      // variables in the tree become parameters (fixed values) for constant opt
166      // for each parameter (variable in the original tree) we store the
167      // variable name, variable value (for factor vars) and lag as a DataForVariable object.
168      // A dictionary is used to find parameters
169      double[] initialConstants;
170      var parameters = new List<TreeToAutoDiffTermConverter.DataForVariable>();
171
172      TreeToAutoDiffTermConverter.ParametricFunction func;
173      TreeToAutoDiffTermConverter.ParametricFunctionGradient func_grad;
174      TreeToAutoDiffTermConverter.ParametricFunctionGradient func_grad_for_vars;
175      if (!TreeToAutoDiffTermConverter.TryConvertToAutoDiff(tree, updateVariableWeights, out parameters, out initialConstants,
176        out func, out func_grad, out func_grad_for_vars))
177        throw new NotSupportedException("Could not optimize constants of symbolic expression tree due to not supported symbols used in the tree.");
178      if (parameters.Count == 0) return 0.0; // gkronber: constant expressions always have a R² of 0.0
179
180      var parameterEntries = parameters.ToArray(); // order of entries must be the same for x
181
182      // extract inital constants
183      double[] c = new double[initialConstants.Length + 2];
184      {
185        c[0] = 0.0;
186        c[1] = 1.0;
187        Array.Copy(initialConstants, 0, c, 2, initialConstants.Length);
188      }
189      double[] originalConstants = (double[])c.Clone();
190      double originalQuality = SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator.Calculate(interpreter, tree, lowerEstimationLimit, upperEstimationLimit, problemData, rows, applyLinearScaling);
191
192      alglib.minnlcstate state;
193      alglib.minnlcreport rep;
194
195      IDataset ds = problemData.Dataset;
196      double[,] x = new double[rows.Count(), parameters.Count];
197      double[,] constraints = new double[rows.Count(), parameters.Count + 1]; // +1 for constraint for f(x)
198      string[,] comp = string[rows.Count(), parameters.Count + 1];
199      int row = 0;
200      foreach (var r in rows) {
201        int col = 0;
202        foreach (var info in parameterEntries) {
203          if (ds.VariableHasType<double>(info.variableName)) {
204            x[row, col] = ds.GetDoubleValue(info.variableName, r + info.lag);
205          } else if (ds.VariableHasType<string>(info.variableName)) {
206            x[row, col] = ds.GetStringValue(info.variableName, r) == info.variableValue ? 1 : 0;
207          } else throw new InvalidProgramException("found a variable of unknown type");
208
209          // find the matching df/dx column
210          var colName = string.Format("df/d({0})", info.variableName);
211          constraints[row, col] = ds.GetDoubleValue(colName, r);
212
213          var compColName = string.Format("df/d({0}) constraint-type")
214          comp[row, col] = ds.GetStringValue(compColName, r);
215          col++;
216        }
217        constraints[row, col] = ds.GetDoubleValue("f(x)", r);
218        comp[row, col] = ds.GetStringValue("f(x) constraint-type", r);
219        row++;
220      }
221      double[] y = ds.GetDoubleValues(problemData.TargetVariable, rows).ToArray();
222      int n = x.GetLength(0);
223      int m = x.GetLength(1);
224      int k = c.Length;
225
226      // alglib.ndimensional_pfunc function_cx_1_func = CreatePFunc(func);
227      // alglib.ndimensional_pgrad function_cx_1_grad = CreatePGrad(func_grad);
228      alglib.ndimensional_jac jac = CreateJac(x, y, constraints, comp, func, func_grad, func_grad_for_vars);
229      double[] s = c.Select(ci=>Math.Max(Math.Abs(ci), 1E-6)).ToArray(); // use absolute value of variables as scale
230      double rho = 1000;
231      int outeriters = 3;
232      int updateFreq = 10;
233      try {
234        // alglib.lsfitcreatefg(x, y, c, n, m, k, false, out state);
235        // alglib.lsfitsetcond(state, 0.0, maxIterations);
236        // //alglib.lsfitsetgradientcheck(state, 0.001);
237        // alglib.lsfitfit(state, function_cx_1_func, function_cx_1_grad, null, null);
238        // alglib.lsfitresults(state, out retVal, out c, out rep);
239        alglib.minnlccreate(c, out state);
240        alglib.minnlcsetalgoaul(state, rho, outeriters);
241        alglib.minnlcsetcond(state, 0.0, 0.0, 0.0, maxIterations);
242        alglib.minnlcsetscale(state, s);
243        alglib.minnlcsetprecexactlowrank(state, updateFreq);
244        // TODO set constraints;
245        alglib.minnlcsetnlc(state, 0, 2);
246        alglib.minnlcoptimize(state, jac, null, null);
247        alglib.minnlcresults(state, out c, out rep);
248      } catch (ArithmeticException) {
249        return originalQuality;
250      } catch (alglib.alglibexception) {
251        return originalQuality;
252      }
253
254      //  -7  => constant optimization failed due to wrong gradient
255      //  -8  => integrity check failed (e.g. gradient NaN
256      if (rep.terminationtype != -7 && rep.terminationtype != -8)
257        UpdateConstants(tree, c.Skip(2).ToArray(), updateVariableWeights);
258      var quality = SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator.Calculate(interpreter, tree, lowerEstimationLimit, upperEstimationLimit, problemData, rows, applyLinearScaling);
259
260      if (!updateConstantsInTree) UpdateConstants(tree, originalConstants.Skip(2).ToArray(), updateVariableWeights);
261      if (originalQuality - quality > 0.001 || double.IsNaN(quality)) {
262        UpdateConstants(tree, originalConstants.Skip(2).ToArray(), updateVariableWeights);
263        return originalQuality;
264      }
265      return quality;
266    }
267
268    private static void UpdateConstants(ISymbolicExpressionTree tree, double[] constants, bool updateVariableWeights) {
269      int i = 0;
270      foreach (var node in tree.Root.IterateNodesPrefix().OfType<SymbolicExpressionTreeTerminalNode>()) {
271        ConstantTreeNode constantTreeNode = node as ConstantTreeNode;
272        VariableTreeNodeBase variableTreeNodeBase = node as VariableTreeNodeBase;
273        FactorVariableTreeNode factorVarTreeNode = node as FactorVariableTreeNode;
274        if (constantTreeNode != null)
275          constantTreeNode.Value = constants[i++];
276        else if (updateVariableWeights && variableTreeNodeBase != null)
277          variableTreeNodeBase.Weight = constants[i++];
278        else if (factorVarTreeNode != null) {
279          for (int j = 0; j < factorVarTreeNode.Weights.Length; j++)
280            factorVarTreeNode.Weights[j] = constants[i++];
281        }
282      }
283    }
284
285    private static alglib.ndimensional_jac CreateJac(
286      double[,] x, // x longer than y
287      double[] y, // only targets
288      string[,] comparison, // {LEQ, GEQ, EQ }
289      double[,] constraints, // df/d(xi), same order as for x
290      TreeToAutoDiffTermConverter.ParametricFunction func,
291      TreeToAutoDiffTermConverter.ParametricFunctionGradient func_grad,
292      TreeToAutoDiffTermConverter.ParametricFunctionGradient func_grad_for_vars) {
293      return (double[] c, double[] fi, double[,] jac, object o) => {
294        // objective function is sum of squared errors
295        int nRows = y.Length;
296        int nParams = x.GetLength(1);
297        // zero fi and jac
298        Array.Clear(fi, 0, fi.Length);
299        Array.Clear(jac, 0, jac.Length);
300        double[] xi = new double[nParams];
301        for (int rowIdx = 0; rowIdx < nRows; rowIdx++) {
302          // copy row
303          for (int cIdx = 0; cIdx < nParams; cIdx++)
304            xi[cIdx] = x[rowIdx, cIdx];
305          var fg = func_grad(c, xi);
306          double f = fg.Item2;
307          double[] g = fg.Item1;
308          var e = y[rowIdx] - f;
309          fi[0] += e * e;
310          // update gradient
311          for (int colIdx = 0; colIdx < c.Length; colIdx++) {
312            jac[0, colIdx] += -2 * e * g[colIdx];
313          }
314        }
315
316        // constraints
317        var nConstraintPoints = constraints.GetLength(0);
318
319        // TODO: AutoDiff for gradients d/d(c) d/d(xi) f(xi,c) for all xi
320        // converter should produce the differentials for all variables as functions which can be differentiated wrt the parameters c
321
322      };
323    }
324
325    // private static alglib.ndimensional_pfunc CreatePFunc(TreeToAutoDiffTermConverter.ParametricFunction func) {
326    //   return (double[] c, double[] x, ref double fx, object o) => {
327    //     fx = func(c, x);
328    //   };
329    // }
330    //
331    // private static alglib.ndimensional_pgrad CreatePGrad(TreeToAutoDiffTermConverter.ParametricFunctionGradient func_grad) {
332    //   return (double[] c, double[] x, ref double fx, double[] grad, object o) => {
333    //     var tupel = func_grad(c, x);
334    //     fx = tupel.Item2;
335    //     Array.Copy(tupel.Item1, grad, grad.Length);
336    //   };
337    // }
338    public static bool CanOptimizeConstants(ISymbolicExpressionTree tree) {
339      return TreeToAutoDiffTermConverter.IsCompatible(tree);
340    }
341  }
342}
Note: See TracBrowser for help on using the repository browser.