Free cookie consent management tool by TermsFeed Policy Generator

source: branches/GBT-trunkintegration/HeuristicLab.Algorithms.DataAnalysis/3.4/GradientBoostedTrees/GradientBoostedTreesAlgorithmStatic.cs @ 12697

Last change on this file since 12697 was 12697, checked in by gkronber, 9 years ago

#2261 removed line search closure (binding y.ToArray(), and pred.ToArray())

File size: 7.2 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.Diagnostics.Contracts;
26using System.Linq;
27using HeuristicLab.Problems.DataAnalysis;
28using HeuristicLab.Random;
29
30namespace HeuristicLab.Algorithms.DataAnalysis {
31  public static class GradientBoostedTreesAlgorithmStatic {
32    #region static API
33
34    public interface IGbmState {
35      IRegressionModel GetModel();
36      double GetTrainLoss();
37      double GetTestLoss();
38      IEnumerable<KeyValuePair<string, double>> GetVariableRelevance();
39    }
40
41    // created through factory method
42    // GbmState details are private API users can only use methods from IGbmState
43    private class GbmState : IGbmState {
44      internal IRegressionProblemData problemData { get; set; }
45      internal MersenneTwister random { get; private set; }
46      internal ILossFunction lossFunction { get; set; }
47      internal int maxSize { get; set; }
48      internal double nu { get; set; }
49      internal double r { get; set; }
50      internal double m { get; set; }
51      internal readonly RegressionTreeBuilder treeBuilder;
52
53
54      // array members (allocate only once)
55      internal double[] pred;
56      internal double[] predTest;
57      internal double[] y;
58      internal int[] activeIdx;
59      internal double[] pseudoRes;
60
61      internal IList<IRegressionModel> models;
62      internal IList<double> weights;
63
64      public GbmState(IRegressionProblemData problemData, ILossFunction lossFunction, uint randSeed, int maxSize, double r, double m, double nu) {
65        // default settings for MaxSize, Nu and R
66        this.maxSize = maxSize;
67        this.nu = nu;
68        this.r = r;
69        this.m = m;
70
71        random = new MersenneTwister(randSeed);
72        this.problemData = problemData;
73        this.lossFunction = lossFunction;
74
75        int nRows = problemData.TrainingIndices.Count();
76
77        y = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, problemData.TrainingIndices).ToArray();
78
79        treeBuilder = new RegressionTreeBuilder(problemData, random);
80
81        activeIdx = Enumerable.Range(0, nRows).ToArray();
82
83        var zeros = Enumerable.Repeat(0.0, nRows).ToArray();
84        double f0 = lossFunction.LineSearch(y, zeros, activeIdx, 0, nRows - 1); // initial constant value (mean for squared errors)
85        pred = Enumerable.Repeat(f0, nRows).ToArray();
86        predTest = Enumerable.Repeat(f0, problemData.TestIndices.Count()).ToArray();
87        pseudoRes = new double[nRows];
88
89        models = new List<IRegressionModel>();
90        weights = new List<double>();
91        // add constant model
92        models.Add(new ConstantRegressionModel(f0));
93        weights.Add(1.0);
94      }
95
96      public IRegressionModel GetModel() {
97        return new GradientBoostedTreesModel(models, weights);
98      }
99      public IEnumerable<KeyValuePair<string, double>> GetVariableRelevance() {
100        return treeBuilder.GetVariableRelevance();
101      }
102
103      public double GetTrainLoss() {
104        int nRows = y.Length;
105        return lossFunction.GetLoss(y, pred) / nRows;
106      }
107      public double GetTestLoss() {
108        var yTest = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, problemData.TestIndices);
109        var nRows = problemData.TestIndices.Count();
110        return lossFunction.GetLoss(yTest, predTest) / nRows;
111      }
112    }
113
114    // simple interface
115    public static IRegressionSolution TrainGbm(IRegressionProblemData problemData, ILossFunction lossFunction, int maxSize, double nu, double r, double m, int maxIterations, uint randSeed = 31415) {
116      Contract.Assert(r > 0);
117      Contract.Assert(r <= 1.0);
118      Contract.Assert(nu > 0);
119      Contract.Assert(nu <= 1.0);
120
121      var state = (GbmState)CreateGbmState(problemData, lossFunction, randSeed);
122      state.maxSize = maxSize;
123      state.r = r;
124      state.m = m;
125      state.nu = nu;
126
127      for (int iter = 0; iter < maxIterations; iter++) {
128        MakeStep(state);
129      }
130
131      var model = new GradientBoostedTreesModel(state.models, state.weights);
132      return new RegressionSolution(model, (IRegressionProblemData)problemData.Clone());
133    }
134
135    // for custom stepping & termination
136    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) {
137      return new GbmState(problemData, lossFunction, randSeed, maxSize, r, m, nu);
138    }
139
140    // use default settings for maxDepth, nu, r from state
141    public static void MakeStep(IGbmState state) {
142      var gbmState = state as GbmState;
143      if (gbmState == null) throw new ArgumentException("state");
144
145      MakeStep(gbmState, gbmState.maxSize, gbmState.nu, gbmState.r, gbmState.m);
146    }
147
148    // allow dynamic adaptation of maxDepth, nu and r (even though this is not used)
149    public static void MakeStep(IGbmState state, int maxSize, double nu, double r, double m) {
150      var gbmState = state as GbmState;
151      if (gbmState == null) throw new ArgumentException("state");
152
153      var problemData = gbmState.problemData;
154      var lossFunction = gbmState.lossFunction;
155      var yPred = gbmState.pred;
156      var yPredTest = gbmState.predTest;
157      var treeBuilder = gbmState.treeBuilder;
158      var y = gbmState.y;
159      var activeIdx = gbmState.activeIdx;
160      var pseudoRes = gbmState.pseudoRes;
161
162      // copy output of gradient function to pre-allocated rim array (pseudo-residuals)
163      int rimIdx = 0;
164      foreach (var g in lossFunction.GetLossGradient(y, yPred)) {
165        pseudoRes[rimIdx++] = g;
166      }
167
168      var tree = treeBuilder.CreateRegressionTreeForGradientBoosting(pseudoRes, yPred, maxSize, activeIdx, lossFunction, r, m);
169
170      int i = 0;
171      // TODO: slow because of multiple calls to GetDoubleValue for each row index
172      foreach (var pred in tree.GetEstimatedValues(problemData.Dataset, problemData.TrainingIndices)) {
173        yPred[i] = yPred[i] + nu * pred;
174        i++;
175      }
176      // update predictions for validation set
177      i = 0;
178      foreach (var pred in tree.GetEstimatedValues(problemData.Dataset, problemData.TestIndices)) {
179        yPredTest[i] = yPredTest[i] + nu * pred;
180        i++;
181      }
182
183      gbmState.weights.Add(nu);
184      gbmState.models.Add(tree);
185    }
186    #endregion
187  }
188}
Note: See TracBrowser for help on using the repository browser.