Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/HeuristicLab.Algorithms.DataAnalysis/3.4/GradientBoostedTrees/GradientBoostedTreesAlgorithmStatic.cs @ 17553

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

#2875: Removed years in copyrights

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