Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/HeuristicLab.Algorithms.DataAnalysis/3.4/GBM/GradientBoostingRegressionAlgorithm.cs @ 18079

Last change on this file since 18079 was 17180, checked in by swagner, 5 years ago

#2875: Removed years in copyrights

File size: 22.6 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 * and the BEACON Center for the Study of Evolution in Action.
5 *
6 * This file is part of HeuristicLab.
7 *
8 * HeuristicLab is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * HeuristicLab is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
20 */
21#endregion
22
23using System;
24using System.Collections.Generic;
25using System.Linq;
26using System.Threading;
27using HeuristicLab.Analysis;
28using HeuristicLab.Common;
29using HeuristicLab.Core;
30using HeuristicLab.Data;
31using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
32using HeuristicLab.Optimization;
33using HeuristicLab.Parameters;
34using HEAL.Attic;
35using HeuristicLab.Problems.DataAnalysis;
36using HeuristicLab.Problems.DataAnalysis.Symbolic;
37using HeuristicLab.Problems.DataAnalysis.Symbolic.Regression;
38using HeuristicLab.Random;
39using HeuristicLab.Selection;
40
41namespace HeuristicLab.Algorithms.DataAnalysis.MctsSymbolicRegression {
42  [Item("Gradient Boosting Machine Regression (GBM)",
43    "Gradient boosting for any regression base learner (e.g. MCTS symbolic regression)")]
44  [StorableType("98B340D7-DB23-40F9-A9CC-C3E652E92671")]
45  [Creatable(CreatableAttribute.Categories.DataAnalysisRegression, Priority = 350)]
46  public class GradientBoostingRegressionAlgorithm : FixedDataAnalysisAlgorithm<IRegressionProblem> {
47
48    #region ParameterNames
49
50    private const string IterationsParameterName = "Iterations";
51    private const string NuParameterName = "Nu";
52    private const string MParameterName = "M";
53    private const string RParameterName = "R";
54    private const string RegressionAlgorithmParameterName = "RegressionAlgorithm";
55    private const string SeedParameterName = "Seed";
56    private const string SetSeedRandomlyParameterName = "SetSeedRandomly";
57    private const string CreateSolutionParameterName = "CreateSolution";
58    private const string StoreRunsParameterName = "StoreRuns";
59    private const string RegressionAlgorithmSolutionResultParameterName = "RegressionAlgorithmResult";
60
61    #endregion
62
63    #region ParameterProperties
64
65    public IFixedValueParameter<IntValue> IterationsParameter {
66      get { return (IFixedValueParameter<IntValue>)Parameters[IterationsParameterName]; }
67    }
68
69    public IFixedValueParameter<DoubleValue> NuParameter {
70      get { return (IFixedValueParameter<DoubleValue>)Parameters[NuParameterName]; }
71    }
72
73    public IFixedValueParameter<DoubleValue> RParameter {
74      get { return (IFixedValueParameter<DoubleValue>)Parameters[RParameterName]; }
75    }
76
77    public IFixedValueParameter<DoubleValue> MParameter {
78      get { return (IFixedValueParameter<DoubleValue>)Parameters[MParameterName]; }
79    }
80
81    // regression algorithms are currently: DataAnalysisAlgorithms, BasicAlgorithms and engine algorithms with no common interface
82    public IConstrainedValueParameter<IAlgorithm> RegressionAlgorithmParameter {
83      get { return (IConstrainedValueParameter<IAlgorithm>)Parameters[RegressionAlgorithmParameterName]; }
84    }
85
86    public IFixedValueParameter<StringValue> RegressionAlgorithmSolutionResultParameter {
87      get { return (IFixedValueParameter<StringValue>)Parameters[RegressionAlgorithmSolutionResultParameterName]; }
88    }
89
90    public IFixedValueParameter<IntValue> SeedParameter {
91      get { return (IFixedValueParameter<IntValue>)Parameters[SeedParameterName]; }
92    }
93
94    public FixedValueParameter<BoolValue> SetSeedRandomlyParameter {
95      get { return (FixedValueParameter<BoolValue>)Parameters[SetSeedRandomlyParameterName]; }
96    }
97
98    public IFixedValueParameter<BoolValue> CreateSolutionParameter {
99      get { return (IFixedValueParameter<BoolValue>)Parameters[CreateSolutionParameterName]; }
100    }
101    public IFixedValueParameter<BoolValue> StoreRunsParameter {
102      get { return (IFixedValueParameter<BoolValue>)Parameters[StoreRunsParameterName]; }
103    }
104
105    #endregion
106
107    #region Properties
108
109    public int Iterations {
110      get { return IterationsParameter.Value.Value; }
111      set { IterationsParameter.Value.Value = value; }
112    }
113
114    public int Seed {
115      get { return SeedParameter.Value.Value; }
116      set { SeedParameter.Value.Value = value; }
117    }
118
119    public bool SetSeedRandomly {
120      get { return SetSeedRandomlyParameter.Value.Value; }
121      set { SetSeedRandomlyParameter.Value.Value = value; }
122    }
123
124    public double Nu {
125      get { return NuParameter.Value.Value; }
126      set { NuParameter.Value.Value = value; }
127    }
128
129    public double R {
130      get { return RParameter.Value.Value; }
131      set { RParameter.Value.Value = value; }
132    }
133
134    public double M {
135      get { return MParameter.Value.Value; }
136      set { MParameter.Value.Value = value; }
137    }
138
139    public bool CreateSolution {
140      get { return CreateSolutionParameter.Value.Value; }
141      set { CreateSolutionParameter.Value.Value = value; }
142    }
143
144    public bool StoreRuns {
145      get { return StoreRunsParameter.Value.Value; }
146      set { StoreRunsParameter.Value.Value = value; }
147    }
148
149    public IAlgorithm RegressionAlgorithm {
150      get { return RegressionAlgorithmParameter.Value; }
151    }
152
153    public string RegressionAlgorithmResult {
154      get { return RegressionAlgorithmSolutionResultParameter.Value.Value; }
155      set { RegressionAlgorithmSolutionResultParameter.Value.Value = value; }
156    }
157
158    #endregion
159
160    [StorableConstructor]
161    protected GradientBoostingRegressionAlgorithm(StorableConstructorFlag _) : base(_) {
162    }
163
164    protected GradientBoostingRegressionAlgorithm(GradientBoostingRegressionAlgorithm original, Cloner cloner)
165      : base(original, cloner) {
166    }
167
168    public override IDeepCloneable Clone(Cloner cloner) {
169      return new GradientBoostingRegressionAlgorithm(this, cloner);
170    }
171
172    public GradientBoostingRegressionAlgorithm() {
173      Problem = new RegressionProblem(); // default problem
174      var osgp = CreateOSGP();
175      var regressionAlgs = new ItemSet<IAlgorithm>(new IAlgorithm[] {
176        new RandomForestRegression(),
177        osgp,
178      });
179      foreach (var alg in regressionAlgs) alg.Prepare();
180
181
182      Parameters.Add(new FixedValueParameter<IntValue>(IterationsParameterName,
183        "Number of iterations", new IntValue(100)));
184      Parameters.Add(new FixedValueParameter<IntValue>(SeedParameterName,
185        "The random seed used to initialize the new pseudo random number generator.", new IntValue(0)));
186      Parameters.Add(new FixedValueParameter<BoolValue>(SetSeedRandomlyParameterName,
187        "True if the random seed should be set to a random value, otherwise false.", new BoolValue(true)));
188      Parameters.Add(new FixedValueParameter<DoubleValue>(NuParameterName,
189        "The learning rate nu when updating predictions in GBM (0 < nu <= 1)", new DoubleValue(0.5)));
190      Parameters.Add(new FixedValueParameter<DoubleValue>(RParameterName,
191        "The fraction of rows that are sampled randomly for the base learner in each iteration (0 < r <= 1)",
192        new DoubleValue(1)));
193      Parameters.Add(new FixedValueParameter<DoubleValue>(MParameterName,
194        "The fraction of variables that are sampled randomly for the base learner in each iteration (0 < m <= 1)",
195        new DoubleValue(0.5)));
196      Parameters.Add(new ConstrainedValueParameter<IAlgorithm>(RegressionAlgorithmParameterName,
197        "The regression algorithm to use as a base learner", regressionAlgs, osgp));
198      Parameters.Add(new FixedValueParameter<StringValue>(RegressionAlgorithmSolutionResultParameterName,
199        "The name of the solution produced by the regression algorithm", new StringValue("Solution")));
200      Parameters[RegressionAlgorithmSolutionResultParameterName].Hidden = true;
201      Parameters.Add(new FixedValueParameter<BoolValue>(CreateSolutionParameterName,
202        "Flag that indicates if a solution should be produced at the end of the run", new BoolValue(true)));
203      Parameters[CreateSolutionParameterName].Hidden = true;
204      Parameters.Add(new FixedValueParameter<BoolValue>(StoreRunsParameterName,
205        "Flag that indicates if the results of the individual runs should be stored for detailed analysis", new BoolValue(false)));
206      Parameters[StoreRunsParameterName].Hidden = true;
207    }
208
209    protected override void Run(CancellationToken cancellationToken) {
210      // Set up the algorithm
211      if (SetSeedRandomly) Seed = RandomSeedGenerator.GetSeed();
212      var rand = new MersenneTwister((uint)Seed);
213
214      // Set up the results display
215      var iterations = new IntValue(0);
216      Results.Add(new Result("Iterations", iterations));
217
218      var table = new DataTable("Qualities");
219      table.Rows.Add(new DataRow("R² (train)"));
220      table.Rows.Add(new DataRow("R² (test)"));
221      Results.Add(new Result("Qualities", table));
222      var curLoss = new DoubleValue();
223      var curTestLoss = new DoubleValue();
224      Results.Add(new Result("R² (train)", curLoss));
225      Results.Add(new Result("R² (test)", curTestLoss));
226      var runCollection = new RunCollection();
227      if (StoreRuns)
228        Results.Add(new Result("Runs", runCollection));
229
230      // init
231      var problemData = Problem.ProblemData;
232      var targetVarName = problemData.TargetVariable;
233      var activeVariables = problemData.AllowedInputVariables.Concat(new string[] { problemData.TargetVariable });
234      var modifiableDataset = new ModifiableDataset(
235        activeVariables,
236        activeVariables.Select(v => problemData.Dataset.GetDoubleValues(v).ToList()));
237
238      var trainingRows = problemData.TrainingIndices;
239      var testRows = problemData.TestIndices;
240      var yPred = new double[trainingRows.Count()];
241      var yPredTest = new double[testRows.Count()];
242      var y = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, problemData.TrainingIndices).ToArray();
243      var curY = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, problemData.TrainingIndices).ToArray();
244
245      var yTest = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, problemData.TestIndices).ToArray();
246      var curYTest = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, problemData.TestIndices).ToArray();
247      var nu = Nu;
248      var mVars = (int)Math.Ceiling(M * problemData.AllowedInputVariables.Count());
249      var rRows = (int)Math.Ceiling(R * problemData.TrainingIndices.Count());
250      var alg = RegressionAlgorithm;
251      List<IRegressionModel> models = new List<IRegressionModel>();
252      try {
253
254        // Loop until iteration limit reached or canceled.
255        for (int i = 0; i < Iterations; i++) {
256          cancellationToken.ThrowIfCancellationRequested();
257
258          modifiableDataset.RemoveVariable(targetVarName);
259          modifiableDataset.AddVariable(targetVarName, curY.Concat(curYTest).ToList());
260
261          SampleTrainingData(rand, modifiableDataset, rRows, problemData.Dataset, curY, problemData.TargetVariable, problemData.TrainingIndices); // all training indices from the original problem data are allowed
262          var modifiableProblemData = new RegressionProblemData(modifiableDataset,
263            problemData.AllowedInputVariables.SampleRandomWithoutRepetition(rand, mVars),
264            problemData.TargetVariable);
265          modifiableProblemData.TrainingPartition.Start = 0;
266          modifiableProblemData.TrainingPartition.End = rRows;
267          modifiableProblemData.TestPartition.Start = problemData.TestPartition.Start;
268          modifiableProblemData.TestPartition.End = problemData.TestPartition.End;
269
270          if (!TrySetProblemData(alg, modifiableProblemData))
271            throw new NotSupportedException("The algorithm cannot be used with GBM.");
272
273          IRegressionModel model;
274          IRun run;
275
276          // try to find a model. The algorithm might fail to produce a model. In this case we just retry until the iterations are exhausted
277          if (TryExecute(alg, rand.Next(), RegressionAlgorithmResult, out model, out run)) {
278            int row = 0;
279            // update predictions for training and test
280            // update new targets (in the case of squared error loss we simply use negative residuals)
281            foreach (var pred in model.GetEstimatedValues(problemData.Dataset, trainingRows)) {
282              yPred[row] = yPred[row] + nu * pred;
283              curY[row] = y[row] - yPred[row];
284              row++;
285            }
286            row = 0;
287            foreach (var pred in model.GetEstimatedValues(problemData.Dataset, testRows)) {
288              yPredTest[row] = yPredTest[row] + nu * pred;
289              curYTest[row] = yTest[row] - yPredTest[row];
290              row++;
291            }
292            // determine quality
293            OnlineCalculatorError error;
294            var trainR = OnlinePearsonsRCalculator.Calculate(yPred, y, out error);
295            var testR = OnlinePearsonsRCalculator.Calculate(yPredTest, yTest, out error);
296
297            // iteration results
298            curLoss.Value = error == OnlineCalculatorError.None ? trainR * trainR : 0.0;
299            curTestLoss.Value = error == OnlineCalculatorError.None ? testR * testR : 0.0;
300
301            models.Add(model);
302
303
304          }
305
306          if (StoreRuns)
307            runCollection.Add(run);
308          table.Rows["R² (train)"].Values.Add(curLoss.Value);
309          table.Rows["R² (test)"].Values.Add(curTestLoss.Value);
310          iterations.Value = i + 1;
311        }
312
313        // produce solution
314        if (CreateSolution) {
315          // when all our models are symbolic models we can easily combine them to a single model
316          if (models.All(m => m is ISymbolicRegressionModel)) {
317            Results.Add(new Result("Solution", CreateSymbolicSolution(models, Nu, (IRegressionProblemData)problemData.Clone())));
318          }
319          // just produce an ensemble solution for now (TODO: correct scaling or linear regression for ensemble model weights)
320
321          var ensembleSolution = CreateEnsembleSolution(models, (IRegressionProblemData)problemData.Clone());
322          Results.Add(new Result("EnsembleSolution", ensembleSolution));
323        }
324      }
325      finally {
326        // reset everything
327        alg.Prepare(true);
328      }
329    }
330
331    private static IRegressionEnsembleSolution CreateEnsembleSolution(List<IRegressionModel> models,
332      IRegressionProblemData problemData) {
333      var rows = problemData.TrainingPartition.Size;
334      var features = models.Count;
335      double[,] inputMatrix = new double[rows, features + 1];
336      //add model estimates
337      for (int m = 0; m < models.Count; m++) {
338        var model = models[m];
339        var estimates = model.GetEstimatedValues(problemData.Dataset, problemData.TrainingIndices);
340        int estimatesCounter = 0;
341        foreach (var estimate in estimates) {
342          inputMatrix[estimatesCounter, m] = estimate;
343          estimatesCounter++;
344        }
345      }
346
347      //add target
348      var targets = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, problemData.TrainingIndices);
349      int targetCounter = 0;
350      foreach (var target in targets) {
351        inputMatrix[targetCounter, models.Count] = target;
352        targetCounter++;
353      }
354
355      alglib.linearmodel lm = new alglib.linearmodel();
356      alglib.lrreport ar = new alglib.lrreport();
357      double[] coefficients;
358      int retVal = 1;
359      alglib.lrbuildz(inputMatrix, rows, features, out retVal, out lm, out ar);
360      if (retVal != 1) throw new ArgumentException("Error in calculation of linear regression solution");
361
362      alglib.lrunpack(lm, out coefficients, out features);
363
364      var ensembleModel = new RegressionEnsembleModel(models, coefficients.Take(models.Count)) { AverageModelEstimates = false };
365      var ensembleSolution = (IRegressionEnsembleSolution)ensembleModel.CreateRegressionSolution(problemData);
366      return ensembleSolution;
367    }
368
369
370    private IAlgorithm CreateOSGP() {
371      // configure strict osgp
372      var alg = new OffspringSelectionGeneticAlgorithm.OffspringSelectionGeneticAlgorithm();
373      var prob = new SymbolicRegressionSingleObjectiveProblem();
374      prob.MaximumSymbolicExpressionTreeDepth.Value = 7;
375      prob.MaximumSymbolicExpressionTreeLength.Value = 15;
376      alg.Problem = prob;
377      alg.SuccessRatio.Value = 1.0;
378      alg.ComparisonFactorLowerBound.Value = 1.0;
379      alg.ComparisonFactorUpperBound.Value = 1.0;
380      alg.MutationProbability.Value = 0.15;
381      alg.PopulationSize.Value = 200;
382      alg.MaximumSelectionPressure.Value = 100;
383      alg.MaximumEvaluatedSolutions.Value = 20000;
384      alg.SelectorParameter.Value = alg.SelectorParameter.ValidValues.OfType<GenderSpecificSelector>().First();
385      alg.MutatorParameter.Value = alg.MutatorParameter.ValidValues.OfType<MultiSymbolicExpressionTreeManipulator>().First();
386      alg.StoreAlgorithmInEachRun = false;
387      return alg;
388    }
389
390    private void SampleTrainingData(MersenneTwister rand, ModifiableDataset ds, int rRows,
391      IDataset sourceDs, double[] curTarget, string targetVarName, IEnumerable<int> trainingIndices) {
392      var selectedRows = trainingIndices.SampleRandomWithoutRepetition(rand, rRows).ToArray();
393      int t = 0;
394      object[] srcRow = new object[ds.Columns];
395      var varNames = ds.DoubleVariables.ToArray();
396      foreach (var r in selectedRows) {
397        // take all values from the original dataset
398        for (int c = 0; c < srcRow.Length; c++) {
399          var col = sourceDs.GetReadOnlyDoubleValues(varNames[c]);
400          srcRow[c] = col[r];
401        }
402        ds.ReplaceRow(t, srcRow);
403        // but use the updated target values
404        ds.SetVariableValue(curTarget[r], targetVarName, t);
405        t++;
406      }
407    }
408
409    private static ISymbolicRegressionSolution CreateSymbolicSolution(List<IRegressionModel> models, double nu, IRegressionProblemData problemData) {
410      var symbModels = models.OfType<ISymbolicRegressionModel>();
411      var lowerLimit = symbModels.Min(m => m.LowerEstimationLimit);
412      var upperLimit = symbModels.Max(m => m.UpperEstimationLimit);
413      var interpreter = new SymbolicDataAnalysisExpressionTreeLinearInterpreter();
414      var progRootNode = new ProgramRootSymbol().CreateTreeNode();
415      var startNode = new StartSymbol().CreateTreeNode();
416
417      var addNode = new Addition().CreateTreeNode();
418      var mulNode = new Multiplication().CreateTreeNode();
419      var scaleNode = (ConstantTreeNode)new Constant().CreateTreeNode(); // all models are scaled using the same nu
420      scaleNode.Value = nu;
421
422      foreach (var m in symbModels) {
423        var relevantPart = m.SymbolicExpressionTree.Root.GetSubtree(0).GetSubtree(0); // skip root and start
424        addNode.AddSubtree((ISymbolicExpressionTreeNode)relevantPart.Clone());
425      }
426
427      mulNode.AddSubtree(addNode);
428      mulNode.AddSubtree(scaleNode);
429      startNode.AddSubtree(mulNode);
430      progRootNode.AddSubtree(startNode);
431      var t = new SymbolicExpressionTree(progRootNode);
432      var combinedModel = new SymbolicRegressionModel(problemData.TargetVariable, t, interpreter, lowerLimit, upperLimit);
433      var sol = new SymbolicRegressionSolution(combinedModel, problemData);
434      return sol;
435    }
436
437    private static bool TrySetProblemData(IAlgorithm alg, IRegressionProblemData problemData) {
438      var prob = alg.Problem as IRegressionProblem;
439      // there is already a problem and it is compatible -> just set problem data
440      if (prob != null) {
441        prob.ProblemDataParameter.Value = problemData;
442        return true;
443      } else return false;
444    }
445
446    private static bool TryExecute(IAlgorithm alg, int seed, string regressionAlgorithmResultName, out IRegressionModel model, out IRun run) {
447      model = null;
448      SetSeed(alg, seed);
449      using (var wh = new AutoResetEvent(false)) {
450        Exception ex = null;
451        EventHandler<EventArgs<Exception>> handler = (sender, args) => {
452          ex = args.Value;
453          wh.Set();
454        };
455        EventHandler handler2 = (sender, args) => wh.Set();
456        alg.ExceptionOccurred += handler;
457        alg.Stopped += handler2;
458        try {
459          alg.Prepare();
460          alg.Start();
461          wh.WaitOne();
462
463          if (ex != null) throw new AggregateException(ex);
464          run = alg.Runs.Last();
465          alg.Runs.Clear();
466          var sols = alg.Results.Select(r => r.Value).OfType<IRegressionSolution>();
467          if (!sols.Any()) return false;
468          var sol = sols.First();
469          if (sols.Skip(1).Any()) {
470            // more than one solution => use regressionAlgorithmResult
471            if (alg.Results.ContainsKey(regressionAlgorithmResultName)) {
472              sol = (IRegressionSolution)alg.Results[regressionAlgorithmResultName].Value;
473            }
474          }
475          var symbRegSol = sol as SymbolicRegressionSolution;
476          // only accept symb reg solutions that do not hit the estimation limits
477          // NaN evaluations would not be critical but are problematic if we want to combine all symbolic models into a single symbolic model
478          if (symbRegSol == null ||
479            (symbRegSol.TrainingLowerEstimationLimitHits == 0 && symbRegSol.TrainingUpperEstimationLimitHits == 0 &&
480             symbRegSol.TestLowerEstimationLimitHits == 0 && symbRegSol.TestUpperEstimationLimitHits == 0) &&
481            symbRegSol.TrainingNaNEvaluations == 0 && symbRegSol.TestNaNEvaluations == 0) {
482            model = sol.Model;
483          }
484        }
485        finally {
486          alg.ExceptionOccurred -= handler;
487          alg.Stopped -= handler2;
488        }
489      }
490      return model != null;
491    }
492
493    private static void SetSeed(IAlgorithm alg, int seed) {
494      // no common interface for algs that use a PRNG -> use naming convention to set seed
495      var paramItem = alg as IParameterizedItem;
496
497      if (paramItem.Parameters.ContainsKey("SetSeedRandomly")) {
498        ((BoolValue)paramItem.Parameters["SetSeedRandomly"].ActualValue).Value = false;
499        ((IntValue)paramItem.Parameters["Seed"].ActualValue).Value = seed;
500      } else {
501        throw new ArgumentException("Base learner does not have a seed parameter (algorithm {0})", alg.Name);
502      }
503
504    }
505  }
506}
Note: See TracBrowser for help on using the repository browser.