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

Last change on this file since 13653 was 13653, checked in by gkronber, 5 years ago

#1795: added OSGP for gradient boosting meta-learner

File size: 19.8 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2015 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.Algorithms.OffspringSelectionGeneticAlgorithm;
29using HeuristicLab.Common;
30using HeuristicLab.Core;
31using HeuristicLab.Data;
32using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
33using HeuristicLab.Optimization;
34using HeuristicLab.Parameters;
35using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
36using HeuristicLab.Problems.DataAnalysis;
37using HeuristicLab.Problems.DataAnalysis.Symbolic;
38using HeuristicLab.Problems.DataAnalysis.Symbolic.Regression;
39using HeuristicLab.Random;
40using HeuristicLab.Selection;
41
42namespace HeuristicLab.Algorithms.DataAnalysis.MctsSymbolicRegression {
43  [Item("Gradient Boosting Machine Regression (GBM)",
44    "Gradient boosting for any regression base learner (e.g. MCTS symbolic regression)")]
45  [StorableClass]
46  [Creatable(CreatableAttribute.Categories.DataAnalysisRegression, Priority = 350)]
47  public class GradientBoostingRegressionAlgorithm : BasicAlgorithm {
48    public override Type ProblemType {
49      get { return typeof(IRegressionProblem); }
50    }
51
52    public new IRegressionProblem Problem {
53      get { return (IRegressionProblem)base.Problem; }
54      set { base.Problem = value; }
55    }
56
57    #region ParameterNames
58
59    private const string IterationsParameterName = "Iterations";
60    private const string NuParameterName = "Nu";
61    private const string MParameterName = "M";
62    private const string RParameterName = "R";
63    private const string RegressionAlgorithmParameterName = "RegressionAlgorithm";
64    private const string SeedParameterName = "Seed";
65    private const string SetSeedRandomlyParameterName = "SetSeedRandomly";
66    private const string CreateSolutionParameterName = "CreateSolution";
67    private const string RegressionAlgorithmSolutionResultParameterName = "RegressionAlgorithmResult";
68
69    #endregion
70
71    #region ParameterProperties
72
73    public IFixedValueParameter<IntValue> IterationsParameter {
74      get { return (IFixedValueParameter<IntValue>)Parameters[IterationsParameterName]; }
75    }
76
77    public IFixedValueParameter<DoubleValue> NuParameter {
78      get { return (IFixedValueParameter<DoubleValue>)Parameters[NuParameterName]; }
79    }
80
81    public IFixedValueParameter<DoubleValue> RParameter {
82      get { return (IFixedValueParameter<DoubleValue>)Parameters[RParameterName]; }
83    }
84
85    public IFixedValueParameter<DoubleValue> MParameter {
86      get { return (IFixedValueParameter<DoubleValue>)Parameters[MParameterName]; }
87    }
88
89    // regression algorithms are currently: DataAnalysisAlgorithms, BasicAlgorithms and engine algorithms with no common interface
90    public IConstrainedValueParameter<IAlgorithm> RegressionAlgorithmParameter {
91      get { return (IConstrainedValueParameter<IAlgorithm>)Parameters[RegressionAlgorithmParameterName]; }
92    }
93
94    public IFixedValueParameter<StringValue> RegressionAlgorithmSolutionResultParameter {
95      get { return (IFixedValueParameter<StringValue>)Parameters[RegressionAlgorithmSolutionResultParameterName]; }
96    }
97
98    public IFixedValueParameter<IntValue> SeedParameter {
99      get { return (IFixedValueParameter<IntValue>)Parameters[SeedParameterName]; }
100    }
101
102    public FixedValueParameter<BoolValue> SetSeedRandomlyParameter {
103      get { return (FixedValueParameter<BoolValue>)Parameters[SetSeedRandomlyParameterName]; }
104    }
105
106    public IFixedValueParameter<BoolValue> CreateSolutionParameter {
107      get { return (IFixedValueParameter<BoolValue>)Parameters[CreateSolutionParameterName]; }
108    }
109
110    #endregion
111
112    #region Properties
113
114    public int Iterations {
115      get { return IterationsParameter.Value.Value; }
116      set { IterationsParameter.Value.Value = value; }
117    }
118
119    public int Seed {
120      get { return SeedParameter.Value.Value; }
121      set { SeedParameter.Value.Value = value; }
122    }
123
124    public bool SetSeedRandomly {
125      get { return SetSeedRandomlyParameter.Value.Value; }
126      set { SetSeedRandomlyParameter.Value.Value = value; }
127    }
128
129    public double Nu {
130      get { return NuParameter.Value.Value; }
131      set { NuParameter.Value.Value = value; }
132    }
133
134    public double R {
135      get { return RParameter.Value.Value; }
136      set { RParameter.Value.Value = value; }
137    }
138
139    public double M {
140      get { return MParameter.Value.Value; }
141      set { MParameter.Value.Value = value; }
142    }
143
144    public bool CreateSolution {
145      get { return CreateSolutionParameter.Value.Value; }
146      set { CreateSolutionParameter.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(bool deserializing)
162      : base(deserializing) {
163    }
164
165    protected GradientBoostingRegressionAlgorithm(GradientBoostingRegressionAlgorithm original, Cloner cloner)
166      : base(original, cloner) {
167    }
168
169    public override IDeepCloneable Clone(Cloner cloner) {
170      return new GradientBoostingRegressionAlgorithm(this, cloner);
171    }
172
173    public GradientBoostingRegressionAlgorithm() {
174      Problem = new RegressionProblem(); // default problem
175      var mctsSymbReg = new MctsSymbolicRegressionAlgorithm();
176      mctsSymbReg.Iterations = 10000;
177      mctsSymbReg.StoreAlgorithmInEachRun = false;
178      var sgp = CreateOSGP();
179      var regressionAlgs = new ItemSet<IAlgorithm>(new IAlgorithm[] {
180        new RandomForestRegression(),
181        sgp,
182        mctsSymbReg
183      });
184      foreach (var alg in regressionAlgs) alg.Prepare();
185
186
187      Parameters.Add(new FixedValueParameter<IntValue>(IterationsParameterName,
188        "Number of iterations", new IntValue(100)));
189      Parameters.Add(new FixedValueParameter<IntValue>(SeedParameterName,
190        "The random seed used to initialize the new pseudo random number generator.", new IntValue(0)));
191      Parameters.Add(new FixedValueParameter<BoolValue>(SetSeedRandomlyParameterName,
192        "True if the random seed should be set to a random value, otherwise false.", new BoolValue(true)));
193      Parameters.Add(new FixedValueParameter<DoubleValue>(NuParameterName,
194        "The learning rate nu when updating predictions in GBM (0 < nu <= 1)", new DoubleValue(0.5)));
195      Parameters.Add(new FixedValueParameter<DoubleValue>(RParameterName,
196        "The fraction of rows that are sampled randomly for the base learner in each iteration (0 < r <= 1)",
197        new DoubleValue(1)));
198      Parameters.Add(new FixedValueParameter<DoubleValue>(MParameterName,
199        "The fraction of variables that are sampled randomly for the base learner in each iteration (0 < m <= 1)",
200        new DoubleValue(0.5)));
201      Parameters.Add(new ConstrainedValueParameter<IAlgorithm>(RegressionAlgorithmParameterName,
202        "The regression algorithm to use as a base learner", regressionAlgs, mctsSymbReg));
203      Parameters.Add(new FixedValueParameter<StringValue>(RegressionAlgorithmSolutionResultParameterName,
204        "The name of the solution produced by the regression algorithm", new StringValue("Solution")));
205      Parameters[RegressionAlgorithmSolutionResultParameterName].Hidden = true;
206      Parameters.Add(new FixedValueParameter<BoolValue>(CreateSolutionParameterName,
207        "Flag that indicates if a solution should be produced at the end of the run", new BoolValue(true)));
208      Parameters[CreateSolutionParameterName].Hidden = true;
209    }
210
211    protected override void Run(CancellationToken cancellationToken) {
212      // Set up the algorithm
213      if (SetSeedRandomly) Seed = new System.Random().Next();
214      var rand = new MersenneTwister((uint)Seed);
215
216      // Set up the results display
217      var iterations = new IntValue(0);
218      Results.Add(new Result("Iterations", iterations));
219
220      var table = new DataTable("Qualities");
221      table.Rows.Add(new DataRow("Loss (train)"));
222      table.Rows.Add(new DataRow("Loss (test)"));
223      Results.Add(new Result("Qualities", table));
224      var curLoss = new DoubleValue();
225      var curTestLoss = new DoubleValue();
226      Results.Add(new Result("Loss (train)", curLoss));
227      Results.Add(new Result("Loss (test)", curTestLoss));
228      var runCollection = new RunCollection();
229      Results.Add(new Result("Runs", runCollection));
230
231      // init
232      var problemData = Problem.ProblemData;
233      var targetVarName = Problem.ProblemData.TargetVariable;
234      var modifiableDataset = new ModifiableDataset(
235        problemData.Dataset.VariableNames,
236        problemData.Dataset.VariableNames.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));
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          // try to find a model. The algorithm might fail to produce a model. In this case we just retry until the iterations are exhausted
276          if (TryExecute(alg, RegressionAlgorithmResult, out model, out run)) {
277            int row = 0;
278            // update predictions for training and test
279            // update new targets (in the case of squared error loss we simply use negative residuals)
280            foreach (var pred in model.GetEstimatedValues(problemData.Dataset, trainingRows)) {
281              yPred[row] = yPred[row] + nu * pred;
282              curY[row] = y[row] - yPred[row];
283              row++;
284            }
285            row = 0;
286            foreach (var pred in model.GetEstimatedValues(problemData.Dataset, testRows)) {
287              yPredTest[row] = yPredTest[row] + nu * pred;
288              curYTest[row] = yTest[row] - yPredTest[row];
289              row++;
290            }
291            // determine quality
292            OnlineCalculatorError error;
293            var trainR = OnlinePearsonsRCalculator.Calculate(yPred, y, out error);
294            var testR = OnlinePearsonsRCalculator.Calculate(yPredTest, yTest, out error);
295
296            // iteration results
297            curLoss.Value = error == OnlineCalculatorError.None ? trainR * trainR : 0.0;
298            curTestLoss.Value = error == OnlineCalculatorError.None ? testR * testR : 0.0;
299
300            models.Add(model);
301
302
303          }
304
305          runCollection.Add(run);
306          table.Rows["Loss (train)"].Values.Add(curLoss.Value);
307          table.Rows["Loss (test)"].Values.Add(curTestLoss.Value);
308          iterations.Value = i + 1;
309        }
310
311        // produce solution
312        if (CreateSolution) {
313          // when all our models are symbolic models we can easily combine them to a single model
314          if (models.All(m => m is ISymbolicRegressionModel)) {
315            Results.Add(new Result("Solution", CreateSymbolicSolution(models, Nu, (IRegressionProblemData)problemData.Clone())));
316          }
317          // just produce an ensemble solution for now (TODO: correct scaling or linear regression for ensemble model weights)
318          Results.Add(new Result("EnsembleSolution", new RegressionEnsembleSolution(models, (IRegressionProblemData)problemData.Clone())));
319        }
320      } finally {
321        // reset everything
322        alg.Prepare(true);
323      }
324    }
325
326
327    private IAlgorithm CreateOSGP() {
328      // configure strict osgp
329      var alg = new OffspringSelectionGeneticAlgorithm.OffspringSelectionGeneticAlgorithm();
330      var prob = new SymbolicRegressionSingleObjectiveProblem();
331      prob.MaximumSymbolicExpressionTreeDepth.Value = 7;
332      prob.MaximumSymbolicExpressionTreeLength.Value = 15;
333      alg.Problem = prob;
334      alg.SuccessRatio.Value = 1.0;
335      alg.ComparisonFactorLowerBound.Value = 1.0;
336      alg.ComparisonFactorUpperBound.Value = 1.0;
337      alg.MutationProbability.Value = 0.15;
338      alg.PopulationSize.Value = 200;
339      alg.MaximumSelectionPressure.Value = 100;
340      alg.MaximumEvaluatedSolutions.Value = 20000;
341      alg.SelectorParameter.Value = alg.SelectorParameter.ValidValues.OfType<GenderSpecificSelector>().First();
342      alg.MutatorParameter.Value = alg.MutatorParameter.ValidValues.OfType<MultiSymbolicExpressionTreeManipulator>().First();
343      alg.StoreAlgorithmInEachRun = false;
344      return alg;
345    }
346
347    private void SampleTrainingData(MersenneTwister rand, ModifiableDataset ds, int rRows,
348      IDataset sourceDs, double[] curTarget, string targetVarName, IEnumerable<int> trainingIndices) {
349      var selectedRows = trainingIndices.SampleRandomWithoutRepetition(rand, rRows).ToArray();
350      int t = 0;
351      object[] srcRow = new object[ds.Columns];
352      var varNames = ds.DoubleVariables.ToArray();
353      foreach (var r in selectedRows) {
354        // take all values from the original dataset
355        for (int c = 0; c < srcRow.Length; c++) {
356          var col = sourceDs.GetReadOnlyDoubleValues(varNames[c]);
357          srcRow[c] = col[r];
358        }
359        ds.ReplaceRow(t, srcRow);
360        // but use the updated target values
361        ds.SetVariableValue(curTarget[r], targetVarName, t);
362        t++;
363      }
364    }
365
366    private static ISymbolicRegressionSolution CreateSymbolicSolution(List<IRegressionModel> models, double nu, IRegressionProblemData problemData) {
367      var symbModels = models.OfType<ISymbolicRegressionModel>();
368      var lowerLimit = symbModels.Min(m => m.LowerEstimationLimit);
369      var upperLimit = symbModels.Max(m => m.UpperEstimationLimit);
370      var interpreter = new SymbolicDataAnalysisExpressionTreeLinearInterpreter();
371      var progRootNode = new ProgramRootSymbol().CreateTreeNode();
372      var startNode = new StartSymbol().CreateTreeNode();
373
374      var addNode = new Addition().CreateTreeNode();
375      var mulNode = new Multiplication().CreateTreeNode();
376      var scaleNode = (ConstantTreeNode)new Constant().CreateTreeNode(); // all models are scaled using the same nu
377      scaleNode.Value = nu;
378
379      foreach (var m in symbModels) {
380        var relevantPart = m.SymbolicExpressionTree.Root.GetSubtree(0).GetSubtree(0); // skip root and start
381        addNode.AddSubtree((ISymbolicExpressionTreeNode)relevantPart.Clone());
382      }
383
384      mulNode.AddSubtree(addNode);
385      mulNode.AddSubtree(scaleNode);
386      startNode.AddSubtree(mulNode);
387      progRootNode.AddSubtree(startNode);
388      var t = new SymbolicExpressionTree(progRootNode);
389      var combinedModel = new SymbolicRegressionModel(t, interpreter, lowerLimit, upperLimit);
390      var sol = new SymbolicRegressionSolution(combinedModel, problemData);
391      return sol;
392    }
393
394    private static bool TrySetProblemData(IAlgorithm alg, IRegressionProblemData problemData) {
395      var prob = alg.Problem as IRegressionProblem;
396      // there is already a problem and it is compatible -> just set problem data
397      if (prob != null) {
398        prob.ProblemDataParameter.Value = problemData;
399        return true;
400      } else return false;
401    }
402
403    private static bool TryExecute(IAlgorithm alg, string regressionAlgorithmResultName, out IRegressionModel model, out IRun run) {
404      model = null;
405      using (var wh = new AutoResetEvent(false)) {
406        EventHandler<EventArgs<Exception>> handler = (sender, args) => wh.Set();
407        EventHandler handler2 = (sender, args) => wh.Set();
408        alg.ExceptionOccurred += handler;
409        alg.Stopped += handler2;
410        try {
411          alg.Prepare();
412          alg.Start();
413          wh.WaitOne();
414
415          run = alg.Runs.Last();
416          var sols = alg.Results.Select(r => r.Value).OfType<IRegressionSolution>();
417          if (!sols.Any()) return false;
418          var sol = sols.First();
419          if (sols.Skip(1).Any()) {
420            // more than one solution => use regressionAlgorithmResult
421            if (alg.Results.ContainsKey(regressionAlgorithmResultName)) {
422              sol = (IRegressionSolution)alg.Results[regressionAlgorithmResultName].Value;
423            }
424          }
425          var symbRegSol = sol as SymbolicRegressionSolution;
426          // only accept symb reg solutions that do not hit the estimation limits
427          // NaN evaluations would not be critical but are problematic if we want to combine all symbolic models into a single symbolic model
428          if (symbRegSol == null ||
429            (symbRegSol.TrainingLowerEstimationLimitHits == 0 && symbRegSol.TrainingUpperEstimationLimitHits == 0 &&
430             symbRegSol.TestLowerEstimationLimitHits == 0 && symbRegSol.TestUpperEstimationLimitHits == 0) &&
431            symbRegSol.TrainingNaNEvaluations == 0 && symbRegSol.TestNaNEvaluations == 0) {
432            model = sol.Model;
433          }
434        } finally {
435          alg.ExceptionOccurred -= handler;
436          alg.Stopped -= handler2;
437        }
438      }
439      return model != null;
440    }
441  }
442}
Note: See TracBrowser for help on using the repository browser.