source: branches/GBT/HeuristicLab.Algorithms.DataAnalysis/3.4/GradientBoostedTrees/RegressionTreeBuilder.cs @ 12349

Last change on this file since 12349 was 12349, checked in by gkronber, 5 years ago

#2261: added serialization constructor for RegressionTreeModel

File size: 13.4 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Diagnostics;
4using System.Diagnostics.Contracts;
5using System.Linq;
6using HeuristicLab.Common;
7using HeuristicLab.Core;
8using HeuristicLab.Problems.DataAnalysis;
9
10namespace GradientBoostedTrees {
11  public class RegressionTreeBuilder {
12    private readonly IRandom random;
13    private readonly IRegressionProblemData problemData;
14
15    private readonly int nCols;
16    private readonly double[][] x; // all training data (original order from problemData)
17    private double[] y; // training labels (original order from problemData)
18
19    private Dictionary<string, double> sumImprovements; // for variable relevance calculation
20
21    private readonly string[] allowedVariables; // all variables in shuffled order
22    private Dictionary<string, int> varName2Index; // maps the variable names to column indexes
23    private int effectiveVars; // number of variables that are used from allowedVariables
24
25    private int effectiveRows; // number of rows that are used from
26    private readonly int[][] sortedIdxAll;
27    private readonly int[][] sortedIdx; // random selection from sortedIdxAll (for r < 1.0)
28
29
30
31    // helper arrays which are allocated to maximal necessary size only once in the ctor
32    private readonly int[] internalIdx, which, leftTmp, rightTmp;
33    private readonly double[] outx;
34    private readonly int[] outSortedIdx;
35    private readonly IList<RegressionTreeModel.TreeNode> nodeQueue; //TODO
36
37    // prepare and allocate buffer variables in ctor
38    public RegressionTreeBuilder(IRegressionProblemData problemData, IRandom random) {
39      this.problemData = problemData;
40      this.random = random;
41
42      var rows = problemData.TrainingIndices.Count();
43
44      this.nCols = problemData.AllowedInputVariables.Count();
45
46      allowedVariables = problemData.AllowedInputVariables.ToArray();
47      varName2Index = new Dictionary<string, int>(allowedVariables.Length);
48      for (int i = 0; i < allowedVariables.Length; i++) varName2Index.Add(allowedVariables[i], i);
49
50      sortedIdxAll = new int[nCols][];
51      sortedIdx = new int[nCols][];
52      sumImprovements = new Dictionary<string, double>();
53      internalIdx = new int[rows];
54      which = new int[rows];
55      leftTmp = new int[rows];
56      rightTmp = new int[rows];
57      outx = new double[rows];
58      outSortedIdx = new int[rows];
59      nodeQueue = new List<RegressionTreeModel.TreeNode>();
60
61      x = new double[nCols][];
62      y = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, problemData.TrainingIndices).ToArray();
63
64
65      int col = 0;
66      foreach (var inputVariable in problemData.AllowedInputVariables) {
67        x[col] = problemData.Dataset.GetDoubleValues(inputVariable, problemData.TrainingIndices).ToArray();
68        sortedIdxAll[col] = Enumerable.Range(0, rows).OrderBy(r => x[col][r]).ToArray();
69        sortedIdx[col] = new int[rows];
70        col++;
71      }
72    }
73
74    // r and m work in the same way as for alglib random forest
75    // r is fraction of rows to use for training
76    // m is fraction of variables to use for training
77    public IRegressionModel CreateRegressionTree(int maxDepth, double r = 0.5, double m = 0.5) {
78      // subtract mean of y first
79      var yAvg = y.Average();
80      for (int i = 0; i < y.Length; i++) y[i] -= yAvg;
81
82      var seLoss = new SquaredErrorLoss();
83      var zeros = Enumerable.Repeat(0.0, y.Length);
84      var ones = Enumerable.Repeat(1.0, y.Length);
85
86      var model = CreateRegressionTreeForGradientBoosting(y, maxDepth, problemData.TrainingIndices.ToArray(), seLoss.GetLineSearchFunc(y, zeros, ones), r, m);
87      return new GradientBoostedTreesModel(new[] { new ConstantRegressionModel(yAvg), model }, new[] { 1.0, 1.0 });
88    }
89
90    // specific interface that allows to specify the target labels and the training rows which is necessary when this functionality is called by the gradient boosting routine
91    public IRegressionModel CreateRegressionTreeForGradientBoosting(double[] y, int maxDepth, int[] idx, LineSearchFunc lineSearch, double r = 0.5, double m = 0.5) {
92      Contract.Assert(maxDepth > 0);
93      Contract.Assert(r > 0);
94      Contract.Assert(r <= 1.0);
95      Contract.Assert(y.Count() == this.y.Length);
96      Contract.Assert(m > 0);
97      Contract.Assert(m <= 1.0);
98
99      this.y = y; // y is changed in gradient boosting
100
101      // shuffle row idx
102      HeuristicLab.Random.ListExtensions.ShuffleInPlace(idx, random);
103
104      int nRows = idx.Count();
105
106      // shuffle variable idx
107      HeuristicLab.Random.ListExtensions.ShuffleInPlace(allowedVariables, random);
108
109      effectiveRows = (int)Math.Ceiling(nRows * r);
110      effectiveVars = (int)Math.Ceiling(nCols * m);
111
112      Array.Clear(which, 0, which.Length);
113
114      // mark selected rows
115      for (int row = 0; row < effectiveRows; row++) {
116        which[idx[row]] = 1;
117        internalIdx[row] = idx[row];
118      }
119
120      for (int col = 0; col < nCols; col++) {
121        int i = 0;
122        for (int row = 0; row < nRows; row++) {
123          if (which[sortedIdxAll[col][row]] > 0) {
124            Trace.Assert(i < effectiveRows);
125            sortedIdx[col][i] = sortedIdxAll[col][row];
126            i++;
127          }
128        }
129      }
130      // start and end idx are inclusive
131      var tree = CreateRegressionTreeForIdx(maxDepth, 0, effectiveRows - 1, lineSearch);
132      return new RegressionTreeModel(tree);
133    }
134
135    // startIdx and endIdx are inclusive
136    private RegressionTreeModel.TreeNode CreateRegressionTreeForIdx(int maxDepth, int startIdx, int endIdx, LineSearchFunc lineSearch) {
137      Contract.Assert(endIdx - startIdx >= 0);
138      Contract.Assert(startIdx >= 0);
139      Contract.Assert(endIdx < internalIdx.Length);
140
141      RegressionTreeModel.TreeNode t;
142      // TODO: stop when y is constant
143      // TODO: use priority queue of nodes to be expanded (sorted by improvement) instead of the recursion to maximum depth
144      if (maxDepth <= 1 || endIdx - startIdx == 0) {
145        // max depth reached or only one element         
146        t = new RegressionTreeModel.TreeNode(RegressionTreeModel.TreeNode.NO_VARIABLE, lineSearch(internalIdx, startIdx, endIdx));
147        return t;
148      } else {
149        int i, j;
150        double threshold;
151        string bestVariableName;
152        FindBestVariableAndThreshold(startIdx, endIdx, out threshold, out bestVariableName);
153
154        // if bestVariableName is NO_VARIABLE then no split was possible anymore
155        if (bestVariableName == RegressionTreeModel.TreeNode.NO_VARIABLE) {
156          return new RegressionTreeModel.TreeNode(RegressionTreeModel.TreeNode.NO_VARIABLE, lineSearch(internalIdx, startIdx, endIdx));
157        } else {
158
159
160          int bestVarIdx = varName2Index[bestVariableName];
161          // split - two pass
162
163          // store which index goes where
164          for (int k = startIdx; k <= endIdx; k++) {
165            if (x[bestVarIdx][internalIdx[k]] <= threshold)
166              which[internalIdx[k]] = -1; // left partition
167            else
168              which[internalIdx[k]] = 1; // right partition
169          }
170
171          // partition sortedIdx for each variable
172          for (int col = 0; col < nCols; col++) {
173            i = 0;
174            j = 0;
175            int k;
176            for (k = startIdx; k <= endIdx; k++) {
177              Debug.Assert(Math.Abs(which[sortedIdx[col][k]]) == 1);
178
179              if (which[sortedIdx[col][k]] < 0) {
180                leftTmp[i++] = sortedIdx[col][k];
181              } else {
182                rightTmp[j++] = sortedIdx[col][k];
183              }
184            }
185            Debug.Assert(i > 0); // at least on element in the left partition
186            Debug.Assert(j > 0); // at least one element in the right partition
187            Debug.Assert(i + j == endIdx - startIdx + 1);
188            k = startIdx;
189            for (int l = 0; l < i; l++) sortedIdx[col][k++] = leftTmp[l];
190            for (int l = 0; l < j; l++) sortedIdx[col][k++] = rightTmp[l];
191          }
192
193          // partition row indices
194          i = startIdx;
195          j = endIdx;
196          while (i <= j) {
197            Debug.Assert(Math.Abs(which[internalIdx[i]]) == 1);
198            Debug.Assert(Math.Abs(which[internalIdx[j]]) == 1);
199            if (which[internalIdx[i]] < 0) i++;
200            else if (which[internalIdx[j]] > 0) j--;
201            else {
202              Trace.Assert(which[internalIdx[i]] > 0);
203              Trace.Assert(which[internalIdx[j]] < 0);
204              // swap
205              int tmp = internalIdx[i];
206              internalIdx[i] = internalIdx[j];
207              internalIdx[j] = tmp;
208              i++;
209              j--;
210            }
211          }
212          Debug.Assert(j < i);
213          Debug.Assert(i >= startIdx);
214          Debug.Assert(j <= endIdx);
215
216          t = new RegressionTreeModel.TreeNode(bestVariableName,
217            threshold,
218            CreateRegressionTreeForIdx(maxDepth - 1, startIdx, j, lineSearch),
219            CreateRegressionTreeForIdx(maxDepth - 1, i, endIdx, lineSearch));
220
221          return t;
222        }
223      }
224    }
225
226    private void FindBestVariableAndThreshold(int startIdx, int endIdx, out double threshold, out string bestVar) {
227      Contract.Assert(startIdx < endIdx + 1); // at least 2 elements
228
229      int rows = endIdx - startIdx + 1;
230      Contract.Assert(rows >= 2);
231
232      double sumY = 0.0;
233      for (int i = startIdx; i <= endIdx; i++) {
234        sumY += y[internalIdx[i]];
235      }
236
237      double bestImprovement = 0.0;
238      double bestThreshold = double.PositiveInfinity;
239      bestVar = string.Empty;
240
241      for (int col = 0; col < effectiveVars; col++) {
242        // sort values for variable to prepare for threshold selection
243        var curVariable = allowedVariables[col];
244        var curVariableIdx = varName2Index[curVariable];
245        for (int i = startIdx; i <= endIdx; i++) {
246          var sortedI = sortedIdx[curVariableIdx][i];
247          outSortedIdx[i - startIdx] = sortedI;
248          outx[i - startIdx] = x[curVariableIdx][sortedI];
249        }
250
251        double curImprovement;
252        double curThreshold;
253        FindBestThreshold(outx, outSortedIdx, rows, y, sumY, out curThreshold, out curImprovement);
254
255        if (curImprovement > bestImprovement) {
256          bestImprovement = curImprovement;
257          bestThreshold = curThreshold;
258          bestVar = allowedVariables[col];
259        }
260      }
261
262      UpdateVariableRelevance(bestVar, sumY, bestImprovement, rows);
263
264      threshold = bestThreshold;
265
266      // Contract.Assert(bestImprovement > 0);
267      // Contract.Assert(bestImprovement < double.PositiveInfinity);
268      // Contract.Assert(bestVar != string.Empty);
269      // Contract.Assert(allowedVariables.Contains(bestVar));
270    }
271
272    // assumption is that the Average(y) = 0
273    private void UpdateVariableRelevance(string bestVar, double sumY, double bestImprovement, int rows) {
274      // update variable relevance
275      double err = sumY * sumY / rows;
276      double errAfterSplit = bestImprovement;
277
278      double delta = (errAfterSplit - err); // relative reduction in squared error
279      double v;
280      if (!sumImprovements.TryGetValue(bestVar, out v)) {
281        sumImprovements[bestVar] = delta;
282      }
283      sumImprovements[bestVar] = v + delta;
284    }
285
286    // x [0..N-1] contains rows sorted values in the range from [0..rows-1]
287    // sortedIdx [0..N-1] contains the idx of the values in x in the original dataset in the range from [0..rows-1]
288    // rows specifies the number of valid entries in x and sortedIdx
289    // y [0..N-1] contains the target values in original sorting order
290    // sumY is y.Sum()
291    //
292    // the routine returns the best threshold (x[i] + x[i+1]) / 2 for i = [0 .. rows-2] by calculating the reduction in squared error
293    // additionally the reduction in squared error is returned in bestImprovement
294    // if all elements of x are equal the routing fails to produce a threshold
295    private static void FindBestThreshold(double[] x, int[] sortedIdx, int rows, double[] y, double sumY, out double bestThreshold, out double bestImprovement) {
296      Contract.Assert(rows >= 2);
297
298      double sl = 0.0;
299      double sr = sumY;
300      double nl = 0.0;
301      double nr = rows;
302
303      bestImprovement = 0.0;
304      bestThreshold = double.NegativeInfinity;
305      // for all thresholds
306      // if we have n rows there are n-1 possible splits
307      for (int i = 0; i < rows - 1; i++) {
308        sl += y[sortedIdx[i]];
309        sr -= y[sortedIdx[i]];
310
311        nl++;
312        nr--;
313        Debug.Assert(nl > 0);
314        Debug.Assert(nr > 0);
315
316        if (x[i] < x[i + 1]) { // don't try to split when two elements are equal
317          double curQuality = sl * sl / nl + sr * sr / nr;
318          // curQuality = nl*nr / (nl+nr) * Sqr(sl / nl - sr / nr) // greedy function approximation page 12 eqn (35)
319
320          if (curQuality > bestImprovement) {
321            bestThreshold = (x[i] + x[i + 1]) / 2.0;
322            bestImprovement = curQuality;
323          }
324        }
325      }
326
327      // if all elements where the same then no split can be found
328    }
329
330
331    public IEnumerable<KeyValuePair<string, double>> GetVariableRelevance() {
332      double scaling = 100 / sumImprovements.Max(t => t.Value);
333      return
334        sumImprovements
335        .Select(t => new KeyValuePair<string, double>(t.Key, t.Value * scaling))
336        .OrderByDescending(t => t.Value);
337    }
338  }
339}
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
Note: See TracBrowser for help on using the repository browser.