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.Linq;
|
---|
25 | using System.Threading;
|
---|
26 | using HeuristicLab.Analysis;
|
---|
27 | using HeuristicLab.Common;
|
---|
28 | using HeuristicLab.Core;
|
---|
29 | using HeuristicLab.Data;
|
---|
30 | using HeuristicLab.Optimization;
|
---|
31 | using HeuristicLab.Parameters;
|
---|
32 | using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
|
---|
33 | using HeuristicLab.PluginInfrastructure;
|
---|
34 | using HeuristicLab.Problems.DataAnalysis;
|
---|
35 |
|
---|
36 | namespace HeuristicLab.Algorithms.DataAnalysis {
|
---|
37 | [Item("Gradient Boosted Trees (GBT)", "Gradient boosted trees algorithm. Specific implementation of gradient boosting for regression trees. Friedman, J. \"Greedy Function Approximation: A Gradient Boosting Machine\", IMS 1999 Reitz Lecture.")]
|
---|
38 | [StorableClass]
|
---|
39 | [Creatable(CreatableAttribute.Categories.DataAnalysisRegression, Priority = 125)]
|
---|
40 | public class GradientBoostedTreesAlgorithm : FixedDataAnalysisAlgorithm<IRegressionProblem> {
|
---|
41 | #region ParameterNames
|
---|
42 | private const string IterationsParameterName = "Iterations";
|
---|
43 | private const string MaxSizeParameterName = "Maximum Tree Size";
|
---|
44 | private const string NuParameterName = "Nu";
|
---|
45 | private const string RParameterName = "R";
|
---|
46 | private const string MParameterName = "M";
|
---|
47 | private const string SeedParameterName = "Seed";
|
---|
48 | private const string SetSeedRandomlyParameterName = "SetSeedRandomly";
|
---|
49 | private const string LossFunctionParameterName = "LossFunction";
|
---|
50 | private const string UpdateIntervalParameterName = "UpdateInterval";
|
---|
51 | private const string CreateSolutionParameterName = "CreateSolution";
|
---|
52 | #endregion
|
---|
53 |
|
---|
54 | #region ParameterProperties
|
---|
55 | public IFixedValueParameter<IntValue> IterationsParameter {
|
---|
56 | get { return (IFixedValueParameter<IntValue>)Parameters[IterationsParameterName]; }
|
---|
57 | }
|
---|
58 | public IFixedValueParameter<IntValue> MaxSizeParameter {
|
---|
59 | get { return (IFixedValueParameter<IntValue>)Parameters[MaxSizeParameterName]; }
|
---|
60 | }
|
---|
61 | public IFixedValueParameter<DoubleValue> NuParameter {
|
---|
62 | get { return (IFixedValueParameter<DoubleValue>)Parameters[NuParameterName]; }
|
---|
63 | }
|
---|
64 | public IFixedValueParameter<DoubleValue> RParameter {
|
---|
65 | get { return (IFixedValueParameter<DoubleValue>)Parameters[RParameterName]; }
|
---|
66 | }
|
---|
67 | public IFixedValueParameter<DoubleValue> MParameter {
|
---|
68 | get { return (IFixedValueParameter<DoubleValue>)Parameters[MParameterName]; }
|
---|
69 | }
|
---|
70 | public IFixedValueParameter<IntValue> SeedParameter {
|
---|
71 | get { return (IFixedValueParameter<IntValue>)Parameters[SeedParameterName]; }
|
---|
72 | }
|
---|
73 | public FixedValueParameter<BoolValue> SetSeedRandomlyParameter {
|
---|
74 | get { return (FixedValueParameter<BoolValue>)Parameters[SetSeedRandomlyParameterName]; }
|
---|
75 | }
|
---|
76 | public IConstrainedValueParameter<ILossFunction> LossFunctionParameter {
|
---|
77 | get { return (IConstrainedValueParameter<ILossFunction>)Parameters[LossFunctionParameterName]; }
|
---|
78 | }
|
---|
79 | public IFixedValueParameter<IntValue> UpdateIntervalParameter {
|
---|
80 | get { return (IFixedValueParameter<IntValue>)Parameters[UpdateIntervalParameterName]; }
|
---|
81 | }
|
---|
82 | public IFixedValueParameter<BoolValue> CreateSolutionParameter {
|
---|
83 | get { return (IFixedValueParameter<BoolValue>)Parameters[CreateSolutionParameterName]; }
|
---|
84 | }
|
---|
85 | #endregion
|
---|
86 |
|
---|
87 | #region Properties
|
---|
88 | public int Iterations {
|
---|
89 | get { return IterationsParameter.Value.Value; }
|
---|
90 | set { IterationsParameter.Value.Value = value; }
|
---|
91 | }
|
---|
92 | public int Seed {
|
---|
93 | get { return SeedParameter.Value.Value; }
|
---|
94 | set { SeedParameter.Value.Value = value; }
|
---|
95 | }
|
---|
96 | public bool SetSeedRandomly {
|
---|
97 | get { return SetSeedRandomlyParameter.Value.Value; }
|
---|
98 | set { SetSeedRandomlyParameter.Value.Value = value; }
|
---|
99 | }
|
---|
100 | public int MaxSize {
|
---|
101 | get { return MaxSizeParameter.Value.Value; }
|
---|
102 | set { MaxSizeParameter.Value.Value = value; }
|
---|
103 | }
|
---|
104 | public double Nu {
|
---|
105 | get { return NuParameter.Value.Value; }
|
---|
106 | set { NuParameter.Value.Value = value; }
|
---|
107 | }
|
---|
108 | public double R {
|
---|
109 | get { return RParameter.Value.Value; }
|
---|
110 | set { RParameter.Value.Value = value; }
|
---|
111 | }
|
---|
112 | public double M {
|
---|
113 | get { return MParameter.Value.Value; }
|
---|
114 | set { MParameter.Value.Value = value; }
|
---|
115 | }
|
---|
116 | public bool CreateSolution {
|
---|
117 | get { return CreateSolutionParameter.Value.Value; }
|
---|
118 | set { CreateSolutionParameter.Value.Value = value; }
|
---|
119 | }
|
---|
120 | #endregion
|
---|
121 |
|
---|
122 | #region ResultsProperties
|
---|
123 | private double ResultsBestQuality {
|
---|
124 | get { return ((DoubleValue)Results["Best Quality"].Value).Value; }
|
---|
125 | set { ((DoubleValue)Results["Best Quality"].Value).Value = value; }
|
---|
126 | }
|
---|
127 | private DataTable ResultsQualities {
|
---|
128 | get { return ((DataTable)Results["Qualities"].Value); }
|
---|
129 | }
|
---|
130 | #endregion
|
---|
131 |
|
---|
132 | [StorableConstructor]
|
---|
133 | protected GradientBoostedTreesAlgorithm(bool deserializing) : base(deserializing) { }
|
---|
134 |
|
---|
135 | protected GradientBoostedTreesAlgorithm(GradientBoostedTreesAlgorithm original, Cloner cloner)
|
---|
136 | : base(original, cloner) {
|
---|
137 | }
|
---|
138 |
|
---|
139 | public override IDeepCloneable Clone(Cloner cloner) {
|
---|
140 | return new GradientBoostedTreesAlgorithm(this, cloner);
|
---|
141 | }
|
---|
142 |
|
---|
143 | public GradientBoostedTreesAlgorithm() {
|
---|
144 | Problem = new RegressionProblem(); // default problem
|
---|
145 |
|
---|
146 | Parameters.Add(new FixedValueParameter<IntValue>(IterationsParameterName, "Number of iterations (set as high as possible, adjust in combination with nu, when increasing iterations also decrease nu)", new IntValue(1000)));
|
---|
147 | Parameters.Add(new FixedValueParameter<IntValue>(SeedParameterName, "The random seed used to initialize the new pseudo random number generator.", new IntValue(0)));
|
---|
148 | Parameters.Add(new FixedValueParameter<BoolValue>(SetSeedRandomlyParameterName, "True if the random seed should be set to a random value, otherwise false.", new BoolValue(true)));
|
---|
149 | Parameters.Add(new FixedValueParameter<IntValue>(MaxSizeParameterName, "Maximal size of the tree learned in each step (prefer smaller sizes if possible)", new IntValue(10)));
|
---|
150 | Parameters.Add(new FixedValueParameter<DoubleValue>(RParameterName, "Ratio of training rows selected randomly in each step (0 < R <= 1)", new DoubleValue(0.5)));
|
---|
151 | Parameters.Add(new FixedValueParameter<DoubleValue>(MParameterName, "Ratio of variables selected randomly in each step (0 < M <= 1)", new DoubleValue(0.5)));
|
---|
152 | Parameters.Add(new FixedValueParameter<DoubleValue>(NuParameterName, "Learning rate nu (step size for the gradient update, should be small 0 < nu < 0.1)", new DoubleValue(0.002)));
|
---|
153 | Parameters.Add(new FixedValueParameter<IntValue>(UpdateIntervalParameterName, "", new IntValue(100)));
|
---|
154 | Parameters[UpdateIntervalParameterName].Hidden = true;
|
---|
155 | Parameters.Add(new FixedValueParameter<BoolValue>(CreateSolutionParameterName, "Flag that indicates if a solution should be produced at the end of the run", new BoolValue(true)));
|
---|
156 | Parameters[CreateSolutionParameterName].Hidden = true;
|
---|
157 |
|
---|
158 | var lossFunctions = ApplicationManager.Manager.GetInstances<ILossFunction>();
|
---|
159 | Parameters.Add(new ConstrainedValueParameter<ILossFunction>(LossFunctionParameterName, "The loss function", new ItemSet<ILossFunction>(lossFunctions)));
|
---|
160 | LossFunctionParameter.Value = LossFunctionParameter.ValidValues.First(f => f.ToString().Contains("Squared")); // squared error loss is the default
|
---|
161 | }
|
---|
162 |
|
---|
163 | [StorableHook(HookType.AfterDeserialization)]
|
---|
164 | private void AfterDeserialization() {
|
---|
165 | // BackwardsCompatibility3.4
|
---|
166 | #region Backwards compatible code, remove with 3.5
|
---|
167 | // parameter type has been changed
|
---|
168 | var lossFunctionParam = Parameters[LossFunctionParameterName] as ConstrainedValueParameter<StringValue>;
|
---|
169 | if (lossFunctionParam != null) {
|
---|
170 | Parameters.Remove(LossFunctionParameterName);
|
---|
171 | var selectedValue = lossFunctionParam.Value; // to be restored below
|
---|
172 |
|
---|
173 | var lossFunctions = ApplicationManager.Manager.GetInstances<ILossFunction>();
|
---|
174 | Parameters.Add(new ConstrainedValueParameter<ILossFunction>(LossFunctionParameterName, "The loss function", new ItemSet<ILossFunction>(lossFunctions)));
|
---|
175 | // try to restore selected value
|
---|
176 | var selectedLossFunction =
|
---|
177 | LossFunctionParameter.ValidValues.FirstOrDefault(f => f.ToString() == selectedValue.Value);
|
---|
178 | if (selectedLossFunction != null) {
|
---|
179 | LossFunctionParameter.Value = selectedLossFunction;
|
---|
180 | } else {
|
---|
181 | LossFunctionParameter.Value = LossFunctionParameter.ValidValues.First(f => f.ToString().Contains("Squared")); // default: SE
|
---|
182 | }
|
---|
183 | }
|
---|
184 | #endregion
|
---|
185 | }
|
---|
186 |
|
---|
187 | protected override void Run(CancellationToken cancellationToken) {
|
---|
188 | // Set up the algorithm
|
---|
189 | if (SetSeedRandomly) Seed = new System.Random().Next();
|
---|
190 |
|
---|
191 | // Set up the results display
|
---|
192 | var iterations = new IntValue(0);
|
---|
193 | Results.Add(new Result("Iterations", iterations));
|
---|
194 |
|
---|
195 | var table = new DataTable("Qualities");
|
---|
196 | table.Rows.Add(new DataRow("Loss (train)"));
|
---|
197 | table.Rows.Add(new DataRow("Loss (test)"));
|
---|
198 | Results.Add(new Result("Qualities", table));
|
---|
199 | var curLoss = new DoubleValue();
|
---|
200 | Results.Add(new Result("Loss (train)", curLoss));
|
---|
201 |
|
---|
202 | // init
|
---|
203 | var problemData = (IRegressionProblemData)Problem.ProblemData.Clone();
|
---|
204 | var lossFunction = LossFunctionParameter.Value;
|
---|
205 | var state = GradientBoostedTreesAlgorithmStatic.CreateGbmState(problemData, lossFunction, (uint)Seed, MaxSize, R, M, Nu);
|
---|
206 |
|
---|
207 | var updateInterval = UpdateIntervalParameter.Value.Value;
|
---|
208 | // Loop until iteration limit reached or canceled.
|
---|
209 | for (int i = 0; i < Iterations; i++) {
|
---|
210 | cancellationToken.ThrowIfCancellationRequested();
|
---|
211 |
|
---|
212 | GradientBoostedTreesAlgorithmStatic.MakeStep(state);
|
---|
213 |
|
---|
214 | // iteration results
|
---|
215 | if (i % updateInterval == 0) {
|
---|
216 | curLoss.Value = state.GetTrainLoss();
|
---|
217 | table.Rows["Loss (train)"].Values.Add(curLoss.Value);
|
---|
218 | table.Rows["Loss (test)"].Values.Add(state.GetTestLoss());
|
---|
219 | iterations.Value = i;
|
---|
220 | }
|
---|
221 | }
|
---|
222 |
|
---|
223 | // final results
|
---|
224 | iterations.Value = Iterations;
|
---|
225 | curLoss.Value = state.GetTrainLoss();
|
---|
226 | table.Rows["Loss (train)"].Values.Add(curLoss.Value);
|
---|
227 | table.Rows["Loss (test)"].Values.Add(state.GetTestLoss());
|
---|
228 |
|
---|
229 | // produce variable relevance
|
---|
230 | var orderedImpacts = state.GetVariableRelevance().Select(t => new { name = t.Key, impact = t.Value }).ToList();
|
---|
231 |
|
---|
232 | var impacts = new DoubleMatrix();
|
---|
233 | var matrix = impacts as IStringConvertibleMatrix;
|
---|
234 | matrix.Rows = orderedImpacts.Count;
|
---|
235 | matrix.RowNames = orderedImpacts.Select(x => x.name);
|
---|
236 | matrix.Columns = 1;
|
---|
237 | matrix.ColumnNames = new string[] { "Relative variable relevance" };
|
---|
238 |
|
---|
239 | int rowIdx = 0;
|
---|
240 | foreach (var p in orderedImpacts) {
|
---|
241 | matrix.SetValue(string.Format("{0:N2}", p.impact), rowIdx++, 0);
|
---|
242 | }
|
---|
243 |
|
---|
244 | Results.Add(new Result("Variable relevance", impacts));
|
---|
245 | Results.Add(new Result("Loss (test)", new DoubleValue(state.GetTestLoss())));
|
---|
246 |
|
---|
247 | // produce solution
|
---|
248 | if (CreateSolution) {
|
---|
249 | var model = state.GetModel();
|
---|
250 |
|
---|
251 | // for logistic regression we produce a classification solution
|
---|
252 | if (lossFunction is LogisticRegressionLoss) {
|
---|
253 | var classificationModel = new DiscriminantFunctionClassificationModel(model,
|
---|
254 | new AccuracyMaximizationThresholdCalculator());
|
---|
255 | var classificationProblemData = new ClassificationProblemData(problemData.Dataset,
|
---|
256 | problemData.AllowedInputVariables, problemData.TargetVariable, problemData.Transformations);
|
---|
257 | classificationModel.RecalculateModelParameters(classificationProblemData, classificationProblemData.TrainingIndices);
|
---|
258 |
|
---|
259 | var classificationSolution = new DiscriminantFunctionClassificationSolution(classificationModel, classificationProblemData);
|
---|
260 | Results.Add(new Result("Solution", classificationSolution));
|
---|
261 | } else {
|
---|
262 | // otherwise we produce a regression solution
|
---|
263 | Results.Add(new Result("Solution", new GradientBoostedTreesSolution(model, problemData)));
|
---|
264 | }
|
---|
265 | }
|
---|
266 | }
|
---|
267 | }
|
---|
268 | }
|
---|