Free cookie consent management tool by TermsFeed Policy Generator

source: branches/PersistenceOverhaul/HeuristicLab.Algorithms.DataAnalysis/3.4/GradientBoostedTrees/GradientBoostedTreesAlgorithmStatic.cs @ 18242

Last change on this file since 18242 was 14712, checked in by gkronber, 8 years ago

#2520 added GUIDs for (almost) all interface types (probably still too many) also added newlines at end of all files

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