1 | #region License Information
|
---|
2 | /* HeuristicLab
|
---|
3 | * Copyright (C) 2002-2016 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 |
|
---|
23 | using System;
|
---|
24 | using System.Collections.Generic;
|
---|
25 | using System.Diagnostics.Contracts;
|
---|
26 | using System.Linq;
|
---|
27 | using HeuristicLab.Problems.DataAnalysis;
|
---|
28 | using HeuristicLab.Random;
|
---|
29 | using HeuristicLab.Persistence;
|
---|
30 |
|
---|
31 | namespace HeuristicLab.Algorithms.DataAnalysis {
|
---|
32 | public static class GradientBoostedTreesAlgorithmStatic {
|
---|
33 | #region static API
|
---|
34 |
|
---|
35 | [StorableType("26b9feb6-93ec-4003-a53a-f852df71c27e")]
|
---|
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
|
---|
44 | // GbmState details are private API users can only use methods from IGbmState
|
---|
45 | private class GbmState : IGbmState {
|
---|
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; }
|
---|
52 | internal int[] trainingRows { get; private set; }
|
---|
53 | internal int[] testRows { get; private set; }
|
---|
54 | internal RegressionTreeBuilder treeBuilder { get; private set; }
|
---|
55 |
|
---|
56 | private readonly uint randSeed;
|
---|
57 | private MersenneTwister random { get; set; }
|
---|
58 |
|
---|
59 | // array members (allocate only once)
|
---|
60 | internal double[] pred;
|
---|
61 | internal double[] predTest;
|
---|
62 | internal double[] y;
|
---|
63 | internal int[] activeIdx;
|
---|
64 | internal double[] pseudoRes;
|
---|
65 |
|
---|
66 | private readonly IList<IRegressionModel> models;
|
---|
67 | private readonly IList<double> weights;
|
---|
68 |
|
---|
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;
|
---|
72 | this.nu = nu;
|
---|
73 | this.r = r;
|
---|
74 | this.m = m;
|
---|
75 |
|
---|
76 | this.randSeed = randSeed;
|
---|
77 | random = new MersenneTwister(randSeed);
|
---|
78 | this.problemData = problemData;
|
---|
79 | this.trainingRows = problemData.TrainingIndices.ToArray();
|
---|
80 | this.testRows = problemData.TestIndices.ToArray();
|
---|
81 | this.lossFunction = lossFunction;
|
---|
82 |
|
---|
83 | int nRows = trainingRows.Length;
|
---|
84 |
|
---|
85 | y = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, trainingRows).ToArray();
|
---|
86 |
|
---|
87 | treeBuilder = new RegressionTreeBuilder(problemData, random);
|
---|
88 |
|
---|
89 | activeIdx = Enumerable.Range(0, nRows).ToArray();
|
---|
90 |
|
---|
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)
|
---|
93 | pred = Enumerable.Repeat(f0, nRows).ToArray();
|
---|
94 | predTest = Enumerable.Repeat(f0, testRows.Length).ToArray();
|
---|
95 | pseudoRes = new double[nRows];
|
---|
96 |
|
---|
97 | models = new List<IRegressionModel>();
|
---|
98 | weights = new List<double>();
|
---|
99 | // add constant model
|
---|
100 | models.Add(new ConstantModel(f0, problemData.TargetVariable));
|
---|
101 | weights.Add(1.0);
|
---|
102 | }
|
---|
103 |
|
---|
104 | public IRegressionModel GetModel() {
|
---|
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);
|
---|
112 | }
|
---|
113 | public IEnumerable<KeyValuePair<string, double>> GetVariableRelevance() {
|
---|
114 | return treeBuilder.GetVariableRelevance();
|
---|
115 | }
|
---|
116 |
|
---|
117 | public double GetTrainLoss() {
|
---|
118 | int nRows = y.Length;
|
---|
119 | return lossFunction.GetLoss(y, pred) / nRows;
|
---|
120 | }
|
---|
121 | public double GetTestLoss() {
|
---|
122 | var yTest = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, testRows);
|
---|
123 | var nRows = testRows.Length;
|
---|
124 | return lossFunction.GetLoss(yTest, predTest) / nRows;
|
---|
125 | }
|
---|
126 |
|
---|
127 | internal void AddModel(IRegressionModel m, double weight) {
|
---|
128 | models.Add(m);
|
---|
129 | weights.Add(weight);
|
---|
130 | }
|
---|
131 | }
|
---|
132 |
|
---|
133 | // simple interface
|
---|
134 | public static GradientBoostedTreesSolution TrainGbm(IRegressionProblemData problemData, ILossFunction lossFunction, int maxSize, double nu, double r, double m, int maxIterations, uint randSeed = 31415) {
|
---|
135 | Contract.Assert(r > 0);
|
---|
136 | Contract.Assert(r <= 1.0);
|
---|
137 | Contract.Assert(nu > 0);
|
---|
138 | Contract.Assert(nu <= 1.0);
|
---|
139 |
|
---|
140 | var state = (GbmState)CreateGbmState(problemData, lossFunction, randSeed, maxSize, r, m, nu);
|
---|
141 |
|
---|
142 | for (int iter = 0; iter < maxIterations; iter++) {
|
---|
143 | MakeStep(state);
|
---|
144 | }
|
---|
145 |
|
---|
146 | var model = state.GetModel();
|
---|
147 | return new GradientBoostedTreesSolution(model, (IRegressionProblemData)problemData.Clone());
|
---|
148 | }
|
---|
149 |
|
---|
150 | // for custom stepping & termination
|
---|
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) {
|
---|
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 |
|
---|
158 | return new GbmState(problemData, lossFunction, randSeed, maxSize, r, m, nu);
|
---|
159 | }
|
---|
160 |
|
---|
161 | // use default settings for maxSize, nu, r from state
|
---|
162 | public static void MakeStep(IGbmState state) {
|
---|
163 | var gbmState = state as GbmState;
|
---|
164 | if (gbmState == null) throw new ArgumentException("state");
|
---|
165 |
|
---|
166 | MakeStep(gbmState, gbmState.maxSize, gbmState.nu, gbmState.r, gbmState.m);
|
---|
167 | }
|
---|
168 |
|
---|
169 | // allow dynamic adaptation of maxSize, nu and r (even though this is not used)
|
---|
170 | public static void MakeStep(IGbmState state, int maxSize, double nu, double r, double m) {
|
---|
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;
|
---|
181 | var pseudoRes = gbmState.pseudoRes;
|
---|
182 | var trainingRows = gbmState.trainingRows;
|
---|
183 | var testRows = gbmState.testRows;
|
---|
184 |
|
---|
185 | // copy output of gradient function to pre-allocated rim array (pseudo-residual per row and model)
|
---|
186 | int rimIdx = 0;
|
---|
187 | foreach (var g in lossFunction.GetLossGradient(y, yPred)) {
|
---|
188 | pseudoRes[rimIdx++] = g;
|
---|
189 | }
|
---|
190 |
|
---|
191 | var tree = treeBuilder.CreateRegressionTreeForGradientBoosting(pseudoRes, yPred, maxSize, activeIdx, lossFunction, r, m);
|
---|
192 |
|
---|
193 | int i = 0;
|
---|
194 | foreach (var pred in tree.GetEstimatedValues(problemData.Dataset, trainingRows)) {
|
---|
195 | yPred[i] = yPred[i] + nu * pred;
|
---|
196 | i++;
|
---|
197 | }
|
---|
198 | // update predictions for validation set
|
---|
199 | i = 0;
|
---|
200 | foreach (var pred in tree.GetEstimatedValues(problemData.Dataset, testRows)) {
|
---|
201 | yPredTest[i] = yPredTest[i] + nu * pred;
|
---|
202 | i++;
|
---|
203 | }
|
---|
204 |
|
---|
205 | gbmState.AddModel(tree, nu);
|
---|
206 | }
|
---|
207 | #endregion
|
---|
208 | }
|
---|
209 | }
|
---|