Free cookie consent management tool by TermsFeed Policy Generator

source: branches/PersistenceReintegration/HeuristicLab.Algorithms.DataAnalysis/3.4/GradientBoostedTrees/GradientBoostedTreesAlgorithmStatic.cs @ 16300

Last change on this file since 16300 was 14929, checked in by gkronber, 8 years ago

#2520 fixed unit tests for new persistence: loading & storing all samples

File size: 8.5 KB
RevLine 
[12332]1#region License Information
2/* HeuristicLab
[14185]3 * Copyright (C) 2002-2016 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[12332]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.Diagnostics.Contracts;
26using System.Linq;
27using HeuristicLab.Problems.DataAnalysis;
28using HeuristicLab.Random;
[14929]29using HeuristicLab.Persistence;
[12332]30
31namespace HeuristicLab.Algorithms.DataAnalysis {
32  public static class GradientBoostedTreesAlgorithmStatic {
33    #region static API
34
[14929]35    [StorableType("26b9feb6-93ec-4003-a53a-f852df71c27e")]
[12332]36    public interface IGbmState {
37      IRegressionModel GetModel();
38      double GetTrainLoss();
39      double GetTestLoss();
40      IEnumerable<KeyValuePair<string, double>> GetVariableRelevance();
41    }
42
43    // created through factory method
[12590]44    // GbmState details are private API users can only use methods from IGbmState
[12332]45    private class GbmState : IGbmState {
[12698]46      internal IRegressionProblemData problemData { get; private set; }
47      internal ILossFunction lossFunction { get; private set; }
48      internal int maxSize { get; private set; }
49      internal double nu { get; private set; }
50      internal double r { get; private set; }
51      internal double m { get; private set; }
[12710]52      internal int[] trainingRows { get; private set; }
53      internal int[] testRows { get; private set; }
[12698]54      internal RegressionTreeBuilder treeBuilder { get; private set; }
[12332]55
[13065]56      private readonly uint randSeed;
[12698]57      private MersenneTwister random { get; set; }
[12332]58
59      // array members (allocate only once)
60      internal double[] pred;
61      internal double[] predTest;
62      internal double[] y;
63      internal int[] activeIdx;
[12597]64      internal double[] pseudoRes;
[12332]65
[12698]66      private readonly IList<IRegressionModel> models;
67      private readonly IList<double> weights;
[12332]68
[12632]69      public GbmState(IRegressionProblemData problemData, ILossFunction lossFunction, uint randSeed, int maxSize, double r, double m, double nu) {
70        // default settings for MaxSize, Nu and R
71        this.maxSize = maxSize;
[12332]72        this.nu = nu;
73        this.r = r;
74        this.m = m;
75
[13065]76        this.randSeed = randSeed;
[12332]77        random = new MersenneTwister(randSeed);
78        this.problemData = problemData;
[12710]79        this.trainingRows = problemData.TrainingIndices.ToArray();
80        this.testRows = problemData.TestIndices.ToArray();
[12332]81        this.lossFunction = lossFunction;
82
[12710]83        int nRows = trainingRows.Length;
[12332]84
[12710]85        y = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, trainingRows).ToArray();
[12332]86
87        treeBuilder = new RegressionTreeBuilder(problemData, random);
88
[12371]89        activeIdx = Enumerable.Range(0, nRows).ToArray();
[12332]90
[12697]91        var zeros = Enumerable.Repeat(0.0, nRows).ToArray();
92        double f0 = lossFunction.LineSearch(y, zeros, activeIdx, 0, nRows - 1); // initial constant value (mean for squared errors)
[12332]93        pred = Enumerable.Repeat(f0, nRows).ToArray();
[12710]94        predTest = Enumerable.Repeat(f0, testRows.Length).ToArray();
[12597]95        pseudoRes = new double[nRows];
[12332]96
97        models = new List<IRegressionModel>();
98        weights = new List<double>();
99        // add constant model
[14000]100        models.Add(new ConstantModel(f0, problemData.TargetVariable));
[12332]101        weights.Add(1.0);
102      }
103
104      public IRegressionModel GetModel() {
[13065]105#pragma warning disable 618
106        var model = new GradientBoostedTreesModel(models, weights);
107#pragma warning restore 618
108        // we don't know the number of iterations here but the number of weights is equal
109        // to the number of iterations + 1 (for the constant model)
110        // wrap the actual model in a surrogate that enables persistence and lazy recalculation of the model if necessary
111        return new GradientBoostedTreesModelSurrogate(problemData, randSeed, lossFunction, weights.Count - 1, maxSize, r, m, nu, model);
[12332]112      }
113      public IEnumerable<KeyValuePair<string, double>> GetVariableRelevance() {
114        return treeBuilder.GetVariableRelevance();
115      }
116
117      public double GetTrainLoss() {
118        int nRows = y.Length;
[12696]119        return lossFunction.GetLoss(y, pred) / nRows;
[12332]120      }
121      public double GetTestLoss() {
[12710]122        var yTest = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, testRows);
123        var nRows = testRows.Length;
[12696]124        return lossFunction.GetLoss(yTest, predTest) / nRows;
[12332]125      }
[12698]126
127      internal void AddModel(IRegressionModel m, double weight) {
128        models.Add(m);
129        weights.Add(weight);
130      }
[12332]131    }
132
133    // simple interface
[13157]134    public static GradientBoostedTreesSolution TrainGbm(IRegressionProblemData problemData, ILossFunction lossFunction, int maxSize, double nu, double r, double m, int maxIterations, uint randSeed = 31415) {
[12332]135      Contract.Assert(r > 0);
136      Contract.Assert(r <= 1.0);
137      Contract.Assert(nu > 0);
138      Contract.Assert(nu <= 1.0);
139
[12698]140      var state = (GbmState)CreateGbmState(problemData, lossFunction, randSeed, maxSize, r, m, nu);
[12332]141
142      for (int iter = 0; iter < maxIterations; iter++) {
143        MakeStep(state);
144      }
145
[12698]146      var model = state.GetModel();
[13157]147      return new GradientBoostedTreesSolution(model, (IRegressionProblemData)problemData.Clone());
[12332]148    }
149
150    // for custom stepping & termination
[12632]151    public static IGbmState CreateGbmState(IRegressionProblemData problemData, ILossFunction lossFunction, uint randSeed, int maxSize = 3, double r = 0.66, double m = 0.5, double nu = 0.01) {
[14826]152      // check input variables. Only double variables are allowed.
153      var invalidInputs =
154        problemData.AllowedInputVariables.Where(name => !problemData.Dataset.VariableHasType<double>(name));
155      if (invalidInputs.Any())
156        throw new NotSupportedException("Gradient tree boosting only supports real-valued variables. Unsupported inputs: " + string.Join(", ", invalidInputs));
157
[12632]158      return new GbmState(problemData, lossFunction, randSeed, maxSize, r, m, nu);
[12332]159    }
160
[12698]161    // use default settings for maxSize, nu, r from state
[12332]162    public static void MakeStep(IGbmState state) {
163      var gbmState = state as GbmState;
164      if (gbmState == null) throw new ArgumentException("state");
165
[12632]166      MakeStep(gbmState, gbmState.maxSize, gbmState.nu, gbmState.r, gbmState.m);
[12332]167    }
168
[12698]169    // allow dynamic adaptation of maxSize, nu and r (even though this is not used)
[12632]170    public static void MakeStep(IGbmState state, int maxSize, double nu, double r, double m) {
[12332]171      var gbmState = state as GbmState;
172      if (gbmState == null) throw new ArgumentException("state");
173
174      var problemData = gbmState.problemData;
175      var lossFunction = gbmState.lossFunction;
176      var yPred = gbmState.pred;
177      var yPredTest = gbmState.predTest;
178      var treeBuilder = gbmState.treeBuilder;
179      var y = gbmState.y;
180      var activeIdx = gbmState.activeIdx;
[12597]181      var pseudoRes = gbmState.pseudoRes;
[12710]182      var trainingRows = gbmState.trainingRows;
183      var testRows = gbmState.testRows;
[12332]184
[12698]185      // copy output of gradient function to pre-allocated rim array (pseudo-residual per row and model)
[12332]186      int rimIdx = 0;
[12696]187      foreach (var g in lossFunction.GetLossGradient(y, yPred)) {
[12597]188        pseudoRes[rimIdx++] = g;
[12332]189      }
190
[12697]191      var tree = treeBuilder.CreateRegressionTreeForGradientBoosting(pseudoRes, yPred, maxSize, activeIdx, lossFunction, r, m);
[12332]192
193      int i = 0;
[12710]194      foreach (var pred in tree.GetEstimatedValues(problemData.Dataset, trainingRows)) {
[12332]195        yPred[i] = yPred[i] + nu * pred;
196        i++;
197      }
198      // update predictions for validation set
199      i = 0;
[12710]200      foreach (var pred in tree.GetEstimatedValues(problemData.Dataset, testRows)) {
[12332]201        yPredTest[i] = yPredTest[i] + nu * pred;
202        i++;
203      }
204
[12698]205      gbmState.AddModel(tree, nu);
[12332]206    }
207    #endregion
208  }
209}
Note: See TracBrowser for help on using the repository browser.