source: stable/HeuristicLab.Algorithms.DataAnalysis/3.4/MctsSymbolicRegression/MctsSymbolicRegressionStatic.cs @ 15060

Last change on this file since 15060 was 15060, checked in by gkronber, 2 years ago

#2581: merged r13645,r13648,r13650,r13651,r13652,r13654,r13657,r13658,r13659,r13661,r13662,r13669,r13708,r14142 from trunk to stable (to be deleted in the next commit)

File size: 19.1 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2015 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.Diagnostics.Contracts;
25using System.Linq;
26using HeuristicLab.Algorithms.DataAnalysis.MctsSymbolicRegression.Policies;
27using HeuristicLab.Common;
28using HeuristicLab.Core;
29using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
30using HeuristicLab.Problems.DataAnalysis;
31using HeuristicLab.Problems.DataAnalysis.Symbolic;
32using HeuristicLab.Problems.DataAnalysis.Symbolic.Regression;
33using HeuristicLab.Random;
34
35namespace HeuristicLab.Algorithms.DataAnalysis.MctsSymbolicRegression {
36  public static class MctsSymbolicRegressionStatic {
37    // TODO: SGD with adagrad instead of lbfgs?
38    // TODO: check Taylor expansion capabilities (ln(x), sqrt(x), exp(x)) in combination with GBT
39    // TODO: optimize for 3 targets concurrently (y, 1/y, exp(y), and log(y))? Would simplify the number of possible expressions again
40    #region static API
41
42    public interface IState {
43      bool Done { get; }
44      ISymbolicRegressionModel BestModel { get; }
45      double BestSolutionTrainingQuality { get; }
46      double BestSolutionTestQuality { get; }
47      int TotalRollouts { get; }
48      int EffectiveRollouts { get; }
49      int FuncEvaluations { get; }
50      int GradEvaluations { get; } // number of gradient evaluations (* num parameters) to get a value representative of the effort comparable to the number of function evaluations
51      // TODO other stats on LM optimizer might be interesting here
52    }
53
54    // created through factory method
55    private class State : IState {
56      private const int MaxParams = 100;
57
58      // state variables used by MCTS
59      internal readonly Automaton automaton;
60      internal IRandom random { get; private set; }
61      internal readonly Tree tree;
62      internal readonly Func<byte[], int, double> evalFun;
63      internal readonly IPolicy treePolicy;
64      // MCTS might get stuck. Track statistics on the number of effective rollouts
65      internal int totalRollouts;
66      internal int effectiveRollouts;
67
68
69      // state variables used only internally (for eval function)
70      private readonly IRegressionProblemData problemData;
71      private readonly double[][] x;
72      private readonly double[] y;
73      private readonly double[][] testX;
74      private readonly double[] testY;
75      private readonly double[] scalingFactor;
76      private readonly double[] scalingOffset;
77      private readonly int constOptIterations;
78      private readonly double lowerEstimationLimit, upperEstimationLimit;
79
80      private readonly ExpressionEvaluator evaluator, testEvaluator;
81
82      // values for best solution
83      private double bestRSq;
84      private byte[] bestCode;
85      private int bestNParams;
86      private double[] bestConsts;
87
88      // stats
89      private int funcEvaluations;
90      private int gradEvaluations;
91
92      // buffers
93      private readonly double[] ones; // vector of ones (as default params)
94      private readonly double[] constsBuf;
95      private readonly double[] predBuf, testPredBuf;
96      private readonly double[][] gradBuf;
97
98      public State(IRegressionProblemData problemData, uint randSeed, int maxVariables, bool scaleVariables, int constOptIterations,
99        IPolicy treePolicy = null,
100        double lowerEstimationLimit = double.MinValue, double upperEstimationLimit = double.MaxValue,
101        bool allowProdOfVars = true,
102        bool allowExp = true,
103        bool allowLog = true,
104        bool allowInv = true,
105        bool allowMultipleTerms = false) {
106
107        this.problemData = problemData;
108        this.constOptIterations = constOptIterations;
109        this.evalFun = this.Eval;
110        this.lowerEstimationLimit = lowerEstimationLimit;
111        this.upperEstimationLimit = upperEstimationLimit;
112
113        random = new MersenneTwister(randSeed);
114
115        // prepare data for evaluation
116        double[][] x;
117        double[] y;
118        double[][] testX;
119        double[] testY;
120        double[] scalingFactor;
121        double[] scalingOffset;
122        // get training and test datasets (scale linearly based on training set if required)
123        GenerateData(problemData, scaleVariables, problemData.TrainingIndices, out x, out y, out scalingFactor, out scalingOffset);
124        GenerateData(problemData, problemData.TestIndices, scalingFactor, scalingOffset, out testX, out testY);
125        this.x = x;
126        this.y = y;
127        this.testX = testX;
128        this.testY = testY;
129        this.scalingFactor = scalingFactor;
130        this.scalingOffset = scalingOffset;
131        this.evaluator = new ExpressionEvaluator(y.Length, lowerEstimationLimit, upperEstimationLimit);
132        // we need a separate evaluator because the vector length for the test dataset might differ
133        this.testEvaluator = new ExpressionEvaluator(testY.Length, lowerEstimationLimit, upperEstimationLimit);
134
135        this.automaton = new Automaton(x, maxVariables, allowProdOfVars, allowExp, allowLog, allowInv, allowMultipleTerms);
136        this.treePolicy = treePolicy ?? new Ucb();
137        this.tree = new Tree() { state = automaton.CurrentState, actionStatistics = treePolicy.CreateActionStatistics() };
138
139        // reset best solution
140        this.bestRSq = 0;
141        // code for default solution (constant model)
142        this.bestCode = new byte[] { (byte)OpCodes.LoadConst0, (byte)OpCodes.Exit };
143        this.bestNParams = 0;
144        this.bestConsts = null;
145
146        // init buffers
147        this.ones = Enumerable.Repeat(1.0, MaxParams).ToArray();
148        constsBuf = new double[MaxParams];
149        this.predBuf = new double[y.Length];
150        this.testPredBuf = new double[testY.Length];
151
152        this.gradBuf = Enumerable.Range(0, MaxParams).Select(_ => new double[y.Length]).ToArray();
153      }
154
155      #region IState inferface
156      public bool Done { get { return tree != null && tree.Done; } }
157
158      public double BestSolutionTrainingQuality {
159        get {
160          evaluator.Exec(bestCode, x, bestConsts, predBuf);
161          return RSq(y, predBuf);
162        }
163      }
164
165      public double BestSolutionTestQuality {
166        get {
167          testEvaluator.Exec(bestCode, testX, bestConsts, testPredBuf);
168          return RSq(testY, testPredBuf);
169        }
170      }
171
172      // takes the code of the best solution and creates and equivalent symbolic regression model
173      public ISymbolicRegressionModel BestModel {
174        get {
175          var treeGen = new SymbolicExpressionTreeGenerator(problemData.AllowedInputVariables.ToArray());
176          var interpreter = new SymbolicDataAnalysisExpressionTreeLinearInterpreter();
177
178          var t = new SymbolicExpressionTree(treeGen.Exec(bestCode, bestConsts, bestNParams, scalingFactor, scalingOffset));
179          var model = new SymbolicRegressionModel(t, interpreter, lowerEstimationLimit, upperEstimationLimit);
180
181          // model has already been scaled linearly in Eval
182          return model;
183        }
184      }
185
186      public int TotalRollouts { get { return totalRollouts; } }
187      public int EffectiveRollouts { get { return effectiveRollouts; } }
188      public int FuncEvaluations { get { return funcEvaluations; } }
189      public int GradEvaluations { get { return gradEvaluations; } } // number of gradient evaluations (* num parameters) to get a value representative of the effort comparable to the number of function evaluations
190
191      #endregion
192
193      private double Eval(byte[] code, int nParams) {
194        double[] optConsts;
195        double q;
196        Eval(code, nParams, out q, out optConsts);
197
198        if (q > bestRSq) {
199          bestRSq = q;
200          bestNParams = nParams;
201          this.bestCode = new byte[code.Length];
202          this.bestConsts = new double[bestNParams];
203
204          Array.Copy(code, bestCode, code.Length);
205          Array.Copy(optConsts, bestConsts, bestNParams);
206        }
207
208        return q;
209      }
210
211      private void Eval(byte[] code, int nParams, out double rsq, out double[] optConsts) {
212        // we make a first pass to determine a valid starting configuration for all constants
213        // constant c in log(c + f(x)) is adjusted to guarantee that x is positive (see expression evaluator)
214        // scale and offset are set to optimal starting configuration
215        // assumes scale is the first param and offset is the last param
216        double alpha;
217        double beta;
218
219        // reset constants
220        Array.Copy(ones, constsBuf, nParams);
221        evaluator.Exec(code, x, constsBuf, predBuf, adjustOffsetForLogAndExp: true);
222        funcEvaluations++;
223
224        // calc opt scaling (alpha*f(x) + beta)
225        OnlineCalculatorError error;
226        OnlineLinearScalingParameterCalculator.Calculate(predBuf, y, out alpha, out beta, out error);
227        if (error == OnlineCalculatorError.None) {
228          constsBuf[0] *= beta;
229          constsBuf[nParams - 1] = constsBuf[nParams - 1] * beta + alpha;
230        }
231        if (nParams <= 2 || constOptIterations <= 0) {
232          // if we don't need to optimize parameters then we are done
233          // changing scale and offset does not influence r²
234          rsq = RSq(y, predBuf);
235          optConsts = constsBuf;
236        } else {
237          // optimize constants using the starting point calculated above
238          OptimizeConstsLm(code, constsBuf, nParams, 0.0, nIters: constOptIterations);
239
240          evaluator.Exec(code, x, constsBuf, predBuf);
241          funcEvaluations++;
242
243          rsq = RSq(y, predBuf);
244          optConsts = constsBuf;
245        }
246      }
247
248
249
250      #region helpers
251      private static double RSq(IEnumerable<double> x, IEnumerable<double> y) {
252        OnlineCalculatorError error;
253        double r = OnlinePearsonsRCalculator.Calculate(x, y, out error);
254        return error == OnlineCalculatorError.None ? r * r : 0.0;
255      }
256
257
258      private void OptimizeConstsLm(byte[] code, double[] consts, int nParams, double epsF = 0.0, int nIters = 100) {
259        double[] optConsts = new double[nParams]; // allocate a smaller buffer for constants opt (TODO perf?)
260        Array.Copy(consts, optConsts, nParams);
261
262        alglib.minlmstate state;
263        alglib.minlmreport rep = null;
264        alglib.minlmcreatevj(y.Length, optConsts, out state);
265        alglib.minlmsetcond(state, 0.0, epsF, 0.0, nIters);
266        //alglib.minlmsetgradientcheck(state, 0.000001);
267        alglib.minlmoptimize(state, Func, FuncAndJacobian, null, code);
268        alglib.minlmresults(state, out optConsts, out rep);
269        funcEvaluations += rep.nfunc;
270        gradEvaluations += rep.njac * nParams;
271
272        if (rep.terminationtype < 0) throw new ArgumentException("lm failed: termination type = " + rep.terminationtype);
273
274        // only use optimized constants if successful
275        if (rep.terminationtype >= 0) {
276          Array.Copy(optConsts, consts, optConsts.Length);
277        }
278      }
279
280      private void Func(double[] arg, double[] fi, object obj) {
281        var code = (byte[])obj;
282        evaluator.Exec(code, x, arg, predBuf); // gradients are nParams x vLen
283        for (int r = 0; r < predBuf.Length; r++) {
284          var res = predBuf[r] - y[r];
285          fi[r] = res;
286        }
287      }
288      private void FuncAndJacobian(double[] arg, double[] fi, double[,] jac, object obj) {
289        int nParams = arg.Length;
290        var code = (byte[])obj;
291        evaluator.ExecGradient(code, x, arg, predBuf, gradBuf); // gradients are nParams x vLen
292        for (int r = 0; r < predBuf.Length; r++) {
293          var res = predBuf[r] - y[r];
294          fi[r] = res;
295
296          for (int k = 0; k < nParams; k++) {
297            jac[r, k] = gradBuf[k][r];
298          }
299        }
300      }
301      #endregion
302    }
303
304    public static IState CreateState(IRegressionProblemData problemData, uint randSeed, int maxVariables = 3,
305      bool scaleVariables = true, int constOptIterations = 0,
306      IPolicy policy = null,
307      double lowerEstimationLimit = double.MinValue, double upperEstimationLimit = double.MaxValue,
308      bool allowProdOfVars = true,
309      bool allowExp = true,
310      bool allowLog = true,
311      bool allowInv = true,
312      bool allowMultipleTerms = false
313      ) {
314      return new State(problemData, randSeed, maxVariables, scaleVariables, constOptIterations,
315        policy,
316        lowerEstimationLimit, upperEstimationLimit,
317        allowProdOfVars, allowExp, allowLog, allowInv, allowMultipleTerms);
318    }
319
320    // returns the quality of the evaluated solution
321    public static double MakeStep(IState state) {
322      var mctsState = state as State;
323      if (mctsState == null) throw new ArgumentException("state");
324      if (mctsState.Done) throw new NotSupportedException("The tree search has enumerated all possible solutions.");
325
326      return TreeSearch(mctsState);
327    }
328    #endregion
329
330    private static double TreeSearch(State mctsState) {
331      var automaton = mctsState.automaton;
332      var tree = mctsState.tree;
333      var eval = mctsState.evalFun;
334      var rand = mctsState.random;
335      var treePolicy = mctsState.treePolicy;
336      double q = 0;
337      bool success = false;
338      do {
339        automaton.Reset();
340        success = TryTreeSearchRec(rand, tree, automaton, eval, treePolicy, out q);
341        mctsState.totalRollouts++;
342      } while (!success && !tree.Done);
343      mctsState.effectiveRollouts++;
344      return q;
345    }
346
347    // tree search might fail because of constraints for expressions
348    // in this case we get stuck we just restart
349    // see ConstraintHandler.cs for more info
350    private static bool TryTreeSearchRec(IRandom rand, Tree tree, Automaton automaton, Func<byte[], int, double> eval, IPolicy treePolicy,
351      out double q) {
352      Tree selectedChild = null;
353      Contract.Assert(tree.state == automaton.CurrentState);
354      Contract.Assert(!tree.Done);
355      if (tree.children == null) {
356        if (automaton.IsFinalState(tree.state)) {
357          // final state
358          tree.Done = true;
359
360          // EVALUATE
361          byte[] code; int nParams;
362          automaton.GetCode(out code, out nParams);
363          q = eval(code, nParams);
364
365          treePolicy.Update(tree.actionStatistics, q);
366          return true; // we reached a final state
367        } else {
368          // EXPAND
369          int[] possibleFollowStates;
370          int nFs;
371          automaton.FollowStates(automaton.CurrentState, out possibleFollowStates, out nFs);
372          if (nFs == 0) {
373            // stuck in a dead end (no final state and no allowed follow states)
374            q = 0;
375            tree.Done = true;
376            tree.children = null;
377            return false;
378          }
379          tree.children = new Tree[nFs];
380          for (int i = 0; i < tree.children.Length; i++)
381            tree.children[i] = new Tree() { children = null, state = possibleFollowStates[i], actionStatistics = treePolicy.CreateActionStatistics() };
382
383          selectedChild = nFs > 1 ? SelectFinalOrRandom(automaton, tree, rand) : tree.children[0];
384        }
385      } else {
386        // tree.children != null
387        // UCT selection within tree
388        int selectedIdx = 0;
389        if (tree.children.Length > 1) {
390          selectedIdx = treePolicy.Select(tree.children.Select(ch => ch.actionStatistics), rand);
391        }
392        selectedChild = tree.children[selectedIdx];
393      }
394      // make selected step and recurse
395      automaton.Goto(selectedChild.state);
396      var success = TryTreeSearchRec(rand, selectedChild, automaton, eval, treePolicy, out q);
397      if (success) {
398        // only update if successful
399        treePolicy.Update(tree.actionStatistics, q);
400      }
401
402      tree.Done = tree.children.All(ch => ch.Done);
403      if (tree.Done) {
404        tree.children = null; // cut off the sub-branch if it has been fully explored
405      }
406      return success;
407    }
408
409    private static Tree SelectFinalOrRandom(Automaton automaton, Tree tree, IRandom rand) {
410      // if one of the new children leads to a final state then go there
411      // otherwise choose a random child
412      int selectedChildIdx = -1;
413      // find first final state if there is one
414      for (int i = 0; i < tree.children.Length; i++) {
415        if (automaton.IsFinalState(tree.children[i].state)) {
416          selectedChildIdx = i;
417          break;
418        }
419      }
420      // no final state -> select a the first child
421      if (selectedChildIdx == -1) {
422        selectedChildIdx = 0;
423      }
424      return tree.children[selectedChildIdx];
425    }
426
427    // scales data and extracts values from dataset into arrays
428    private static void GenerateData(IRegressionProblemData problemData, bool scaleVariables, IEnumerable<int> rows,
429      out double[][] xs, out double[] y, out double[] scalingFactor, out double[] scalingOffset) {
430      xs = new double[problemData.AllowedInputVariables.Count()][];
431
432      var i = 0;
433      if (scaleVariables) {
434        scalingFactor = new double[xs.Length];
435        scalingOffset = new double[xs.Length];
436      } else {
437        scalingFactor = null;
438        scalingOffset = null;
439      }
440      foreach (var var in problemData.AllowedInputVariables) {
441        if (scaleVariables) {
442          var minX = problemData.Dataset.GetDoubleValues(var, rows).Min();
443          var maxX = problemData.Dataset.GetDoubleValues(var, rows).Max();
444          var range = maxX - minX;
445
446          // scaledX = (x - min) / range
447          var sf = 1.0 / range;
448          var offset = -minX / range;
449          scalingFactor[i] = sf;
450          scalingOffset[i] = offset;
451          i++;
452        }
453      }
454
455      GenerateData(problemData, rows, scalingFactor, scalingOffset, out xs, out y);
456    }
457
458    // extract values from dataset into arrays
459    private static void GenerateData(IRegressionProblemData problemData, IEnumerable<int> rows, double[] scalingFactor, double[] scalingOffset,
460     out double[][] xs, out double[] y) {
461      xs = new double[problemData.AllowedInputVariables.Count()][];
462
463      int i = 0;
464      foreach (var var in problemData.AllowedInputVariables) {
465        var sf = scalingFactor == null ? 1.0 : scalingFactor[i];
466        var offset = scalingFactor == null ? 0.0 : scalingOffset[i];
467        xs[i++] =
468          problemData.Dataset.GetDoubleValues(var, rows).Select(xi => xi * sf + offset).ToArray();
469      }
470
471      y = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, rows).ToArray();
472    }
473  }
474}
Note: See TracBrowser for help on using the repository browser.