1 | #region License Information
|
---|
2 | /* HeuristicLab
|
---|
3 | * Copyright (C) Heuristic and Evolutionary Algorithms Laboratory (HEAL)
|
---|
4 | *
|
---|
5 | * This file is part of HeuristicLab.
|
---|
6 | *
|
---|
7 | * HeuristicLab is free software: you can redistribute it and/or modify
|
---|
8 | * it under the terms of the GNU General Public License as published by
|
---|
9 | * the Free Software Foundation, either version 3 of the License, or
|
---|
10 | * (at your option) any later version.
|
---|
11 | *
|
---|
12 | * HeuristicLab is distributed in the hope that it will be useful,
|
---|
13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
|
---|
14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
---|
15 | * GNU General Public License for more details.
|
---|
16 | *
|
---|
17 | * You should have received a copy of the GNU General Public License
|
---|
18 | * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
|
---|
19 | */
|
---|
20 | #endregion
|
---|
21 |
|
---|
22 | extern alias alglib_3_7;
|
---|
23 |
|
---|
24 | using System;
|
---|
25 | using System.Collections.Generic;
|
---|
26 | using System.Linq;
|
---|
27 | using HEAL.Attic;
|
---|
28 | using HeuristicLab.Common;
|
---|
29 | using HeuristicLab.Core;
|
---|
30 | using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
|
---|
31 | using HeuristicLab.Problems.DataAnalysis;
|
---|
32 | using HeuristicLab.Problems.DataAnalysis.Symbolic;
|
---|
33 |
|
---|
34 | namespace HeuristicLab.Algorithms.DataAnalysis {
|
---|
35 | /// <summary>
|
---|
36 | /// Represents a random forest model for regression and classification
|
---|
37 | /// </summary>
|
---|
38 | [Obsolete("This class only exists for backwards compatibility reasons for stored models with the XML Persistence. Use RFModelSurrogate or RFModelFull instead.")]
|
---|
39 | [StorableType("9AA4CCC2-CD75-4471-8DF6-949E5B783642")]
|
---|
40 | [Item("RandomForestModel", "Represents a random forest for regression and classification.")]
|
---|
41 | public sealed class RandomForestModel : ClassificationModel, IRandomForestModel {
|
---|
42 | // not persisted
|
---|
43 | private alglib_3_7.alglib.decisionforest randomForest;
|
---|
44 | private alglib_3_7.alglib.decisionforest RandomForest {
|
---|
45 | get {
|
---|
46 | // recalculate lazily
|
---|
47 | if (randomForest.innerobj.trees == null || randomForest.innerobj.trees.Length == 0) RecalculateModel();
|
---|
48 | return randomForest;
|
---|
49 | }
|
---|
50 | }
|
---|
51 |
|
---|
52 | public override IEnumerable<string> VariablesUsedForPrediction {
|
---|
53 | get { return originalTrainingData.AllowedInputVariables; }
|
---|
54 | }
|
---|
55 |
|
---|
56 | public int NumberOfTrees {
|
---|
57 | get { return nTrees; }
|
---|
58 | }
|
---|
59 |
|
---|
60 | // instead of storing the data of the model itself
|
---|
61 | // we instead only store data necessary to recalculate the same model lazily on demand
|
---|
62 | [Storable]
|
---|
63 | private int seed;
|
---|
64 | [Storable]
|
---|
65 | private IDataAnalysisProblemData originalTrainingData;
|
---|
66 | [Storable]
|
---|
67 | private double[] classValues;
|
---|
68 | [Storable]
|
---|
69 | private int nTrees;
|
---|
70 | [Storable]
|
---|
71 | private double r;
|
---|
72 | [Storable]
|
---|
73 | private double m;
|
---|
74 |
|
---|
75 | [StorableConstructor]
|
---|
76 | private RandomForestModel(StorableConstructorFlag _) : base(_) {
|
---|
77 | // for backwards compatibility (loading old solutions)
|
---|
78 | randomForest = new alglib_3_7.alglib.decisionforest();
|
---|
79 | }
|
---|
80 | private RandomForestModel(RandomForestModel original, Cloner cloner)
|
---|
81 | : base(original, cloner) {
|
---|
82 | randomForest = new alglib_3_7.alglib.decisionforest();
|
---|
83 | randomForest.innerobj.bufsize = original.randomForest.innerobj.bufsize;
|
---|
84 | randomForest.innerobj.nclasses = original.randomForest.innerobj.nclasses;
|
---|
85 | randomForest.innerobj.ntrees = original.randomForest.innerobj.ntrees;
|
---|
86 | randomForest.innerobj.nvars = original.randomForest.innerobj.nvars;
|
---|
87 | // we assume that the trees array (double[]) is immutable in alglib
|
---|
88 | randomForest.innerobj.trees = original.randomForest.innerobj.trees;
|
---|
89 |
|
---|
90 | // allowedInputVariables is immutable so we don't need to clone
|
---|
91 | allowedInputVariables = original.allowedInputVariables;
|
---|
92 |
|
---|
93 | // clone data which is necessary to rebuild the model
|
---|
94 | this.seed = original.seed;
|
---|
95 | this.originalTrainingData = cloner.Clone(original.originalTrainingData);
|
---|
96 | // classvalues is immutable so we don't need to clone
|
---|
97 | this.classValues = original.classValues;
|
---|
98 | this.nTrees = original.nTrees;
|
---|
99 | this.r = original.r;
|
---|
100 | this.m = original.m;
|
---|
101 | }
|
---|
102 |
|
---|
103 | // random forest models can only be created through the static factory methods CreateRegressionModel and CreateClassificationModel
|
---|
104 | private RandomForestModel(string targetVariable, alglib_3_7.alglib.decisionforest randomForest,
|
---|
105 | int seed, IDataAnalysisProblemData originalTrainingData,
|
---|
106 | int nTrees, double r, double m, double[] classValues = null)
|
---|
107 | : base(targetVariable) {
|
---|
108 | this.name = ItemName;
|
---|
109 | this.description = ItemDescription;
|
---|
110 | // the model itself
|
---|
111 | this.randomForest = randomForest;
|
---|
112 | // data which is necessary for recalculation of the model
|
---|
113 | this.seed = seed;
|
---|
114 | this.originalTrainingData = (IDataAnalysisProblemData)originalTrainingData.Clone();
|
---|
115 | this.classValues = classValues;
|
---|
116 | this.nTrees = nTrees;
|
---|
117 | this.r = r;
|
---|
118 | this.m = m;
|
---|
119 | }
|
---|
120 |
|
---|
121 | public override IDeepCloneable Clone(Cloner cloner) {
|
---|
122 | return new RandomForestModel(this, cloner);
|
---|
123 | }
|
---|
124 |
|
---|
125 | private void RecalculateModel() {
|
---|
126 | double rmsError, oobRmsError, relClassError, oobRelClassError;
|
---|
127 | var regressionProblemData = originalTrainingData as IRegressionProblemData;
|
---|
128 | var classificationProblemData = originalTrainingData as IClassificationProblemData;
|
---|
129 | if (regressionProblemData != null) {
|
---|
130 | var model = CreateRegressionModel(regressionProblemData,
|
---|
131 | nTrees, r, m, seed, out rmsError, out oobRmsError,
|
---|
132 | out relClassError, out oobRelClassError);
|
---|
133 | randomForest = model.randomForest;
|
---|
134 | } else if (classificationProblemData != null) {
|
---|
135 | var model = CreateClassificationModel(classificationProblemData,
|
---|
136 | nTrees, r, m, seed, out rmsError, out oobRmsError,
|
---|
137 | out relClassError, out oobRelClassError);
|
---|
138 | randomForest = model.randomForest;
|
---|
139 | }
|
---|
140 | }
|
---|
141 |
|
---|
142 | public IEnumerable<double> GetEstimatedValues(IDataset dataset, IEnumerable<int> rows) {
|
---|
143 | double[,] inputData = dataset.ToArray(AllowedInputVariables, rows);
|
---|
144 | RandomForestUtil.AssertInputMatrix(inputData);
|
---|
145 |
|
---|
146 | int n = inputData.GetLength(0);
|
---|
147 | int columns = inputData.GetLength(1);
|
---|
148 | double[] x = new double[columns];
|
---|
149 | double[] y = new double[1];
|
---|
150 |
|
---|
151 | for (int row = 0; row < n; row++) {
|
---|
152 | for (int column = 0; column < columns; column++) {
|
---|
153 | x[column] = inputData[row, column];
|
---|
154 | }
|
---|
155 | alglib_3_7.alglib.dfprocess(RandomForest, x, ref y);
|
---|
156 | yield return y[0];
|
---|
157 | }
|
---|
158 | }
|
---|
159 |
|
---|
160 | public IEnumerable<double> GetEstimatedVariances(IDataset dataset, IEnumerable<int> rows) {
|
---|
161 | double[,] inputData = dataset.ToArray(AllowedInputVariables, rows);
|
---|
162 | RandomForestUtil.AssertInputMatrix(inputData);
|
---|
163 |
|
---|
164 | int n = inputData.GetLength(0);
|
---|
165 | int columns = inputData.GetLength(1);
|
---|
166 | double[] x = new double[columns];
|
---|
167 | double[] ys = new double[this.RandomForest.innerobj.ntrees];
|
---|
168 |
|
---|
169 | for (int row = 0; row < n; row++) {
|
---|
170 | for (int column = 0; column < columns; column++) {
|
---|
171 | x[column] = inputData[row, column];
|
---|
172 | }
|
---|
173 | alglib_3_7.alglib.dforest.dfprocessraw(RandomForest.innerobj, x, ref ys);
|
---|
174 | yield return ys.VariancePop();
|
---|
175 | }
|
---|
176 | }
|
---|
177 |
|
---|
178 | public override IEnumerable<double> GetEstimatedClassValues(IDataset dataset, IEnumerable<int> rows) {
|
---|
179 | double[,] inputData = dataset.ToArray(AllowedInputVariables, rows);
|
---|
180 | RandomForestUtil.AssertInputMatrix(inputData);
|
---|
181 |
|
---|
182 | int n = inputData.GetLength(0);
|
---|
183 | int columns = inputData.GetLength(1);
|
---|
184 | double[] x = new double[columns];
|
---|
185 | double[] y = new double[RandomForest.innerobj.nclasses];
|
---|
186 |
|
---|
187 | for (int row = 0; row < n; row++) {
|
---|
188 | for (int column = 0; column < columns; column++) {
|
---|
189 | x[column] = inputData[row, column];
|
---|
190 | }
|
---|
191 | alglib_3_7.alglib.dfprocess(randomForest, x, ref y);
|
---|
192 | // find class for with the largest probability value
|
---|
193 | int maxProbClassIndex = 0;
|
---|
194 | double maxProb = y[0];
|
---|
195 | for (int i = 1; i < y.Length; i++) {
|
---|
196 | if (maxProb < y[i]) {
|
---|
197 | maxProb = y[i];
|
---|
198 | maxProbClassIndex = i;
|
---|
199 | }
|
---|
200 | }
|
---|
201 | yield return classValues[maxProbClassIndex];
|
---|
202 | }
|
---|
203 | }
|
---|
204 |
|
---|
205 | public ISymbolicExpressionTree ExtractTree(int treeIdx) {
|
---|
206 | var rf = RandomForest;
|
---|
207 | // hoping that the internal representation of alglib is stable
|
---|
208 |
|
---|
209 | // TREE FORMAT
|
---|
210 | // W[Offs] - size of sub-array (for the tree)
|
---|
211 | // node info:
|
---|
212 | // W[K+0] - variable number (-1 for leaf mode)
|
---|
213 | // W[K+1] - threshold (class/value for leaf node)
|
---|
214 | // W[K+2] - ">=" branch index (absent for leaf node)
|
---|
215 |
|
---|
216 | // skip irrelevant trees
|
---|
217 | int offset = 0;
|
---|
218 | for (int i = 0; i < treeIdx - 1; i++) {
|
---|
219 | offset = offset + (int)Math.Round(rf.innerobj.trees[offset]);
|
---|
220 | }
|
---|
221 |
|
---|
222 | var constSy = new Constant();
|
---|
223 | var varCondSy = new VariableCondition() { IgnoreSlope = true };
|
---|
224 |
|
---|
225 | var node = CreateRegressionTreeRec(rf.innerobj.trees, offset, offset + 1, constSy, varCondSy);
|
---|
226 |
|
---|
227 | var startNode = new StartSymbol().CreateTreeNode();
|
---|
228 | startNode.AddSubtree(node);
|
---|
229 | var root = new ProgramRootSymbol().CreateTreeNode();
|
---|
230 | root.AddSubtree(startNode);
|
---|
231 | return new SymbolicExpressionTree(root);
|
---|
232 | }
|
---|
233 |
|
---|
234 | private ISymbolicExpressionTreeNode CreateRegressionTreeRec(double[] trees, int offset, int k, Constant constSy, VariableCondition varCondSy) {
|
---|
235 |
|
---|
236 | // alglib source for evaluation of one tree (dfprocessinternal)
|
---|
237 | // offs = 0
|
---|
238 | //
|
---|
239 | // Set pointer to the root
|
---|
240 | //
|
---|
241 | // k = offs + 1;
|
---|
242 | //
|
---|
243 | // //
|
---|
244 | // // Navigate through the tree
|
---|
245 | // //
|
---|
246 | // while (true) {
|
---|
247 | // if ((double)(df.trees[k]) == (double)(-1)) {
|
---|
248 | // if (df.nclasses == 1) {
|
---|
249 | // y[0] = y[0] + df.trees[k + 1];
|
---|
250 | // } else {
|
---|
251 | // idx = (int)Math.Round(df.trees[k + 1]);
|
---|
252 | // y[idx] = y[idx] + 1;
|
---|
253 | // }
|
---|
254 | // break;
|
---|
255 | // }
|
---|
256 | // if ((double)(x[(int)Math.Round(df.trees[k])]) < (double)(df.trees[k + 1])) {
|
---|
257 | // k = k + innernodewidth;
|
---|
258 | // } else {
|
---|
259 | // k = offs + (int)Math.Round(df.trees[k + 2]);
|
---|
260 | // }
|
---|
261 | // }
|
---|
262 |
|
---|
263 | if ((double)(trees[k]) == (double)(-1)) {
|
---|
264 | var constNode = (ConstantTreeNode)constSy.CreateTreeNode();
|
---|
265 | constNode.Value = trees[k + 1];
|
---|
266 | return constNode;
|
---|
267 | } else {
|
---|
268 | var condNode = (VariableConditionTreeNode)varCondSy.CreateTreeNode();
|
---|
269 | condNode.VariableName = AllowedInputVariables[(int)Math.Round(trees[k])];
|
---|
270 | condNode.Threshold = trees[k + 1];
|
---|
271 | condNode.Slope = double.PositiveInfinity;
|
---|
272 |
|
---|
273 | var left = CreateRegressionTreeRec(trees, offset, k + 3, constSy, varCondSy);
|
---|
274 | var right = CreateRegressionTreeRec(trees, offset, offset + (int)Math.Round(trees[k + 2]), constSy, varCondSy);
|
---|
275 |
|
---|
276 | condNode.AddSubtree(left); // not 100% correct because interpreter uses: if(x <= thres) left() else right() and RF uses if(x < thres) left() else right() (see above)
|
---|
277 | condNode.AddSubtree(right);
|
---|
278 | return condNode;
|
---|
279 | }
|
---|
280 | }
|
---|
281 |
|
---|
282 |
|
---|
283 | public IRegressionSolution CreateRegressionSolution(IRegressionProblemData problemData) {
|
---|
284 | return new RandomForestRegressionSolution(this, new RegressionProblemData(problemData));
|
---|
285 | }
|
---|
286 | public override IClassificationSolution CreateClassificationSolution(IClassificationProblemData problemData) {
|
---|
287 | return new RandomForestClassificationSolution(this, new ClassificationProblemData(problemData));
|
---|
288 | }
|
---|
289 |
|
---|
290 | public bool IsProblemDataCompatible(IRegressionProblemData problemData, out string errorMessage) {
|
---|
291 | return RegressionModel.IsProblemDataCompatible(this, problemData, out errorMessage);
|
---|
292 | }
|
---|
293 |
|
---|
294 | public override bool IsProblemDataCompatible(IDataAnalysisProblemData problemData, out string errorMessage) {
|
---|
295 | if (problemData == null) throw new ArgumentNullException("problemData", "The provided problemData is null.");
|
---|
296 |
|
---|
297 | var regressionProblemData = problemData as IRegressionProblemData;
|
---|
298 | if (regressionProblemData != null)
|
---|
299 | return IsProblemDataCompatible(regressionProblemData, out errorMessage);
|
---|
300 |
|
---|
301 | var classificationProblemData = problemData as IClassificationProblemData;
|
---|
302 | if (classificationProblemData != null)
|
---|
303 | return IsProblemDataCompatible(classificationProblemData, out errorMessage);
|
---|
304 |
|
---|
305 | throw new ArgumentException("The problem data is not compatible with this random forest. Instead a " + problemData.GetType().GetPrettyName() + " was provided.", "problemData");
|
---|
306 | }
|
---|
307 |
|
---|
308 | public static RandomForestModel CreateRegressionModel(IRegressionProblemData problemData, int nTrees, double r, double m, int seed,
|
---|
309 | out double rmsError, out double outOfBagRmsError, out double avgRelError, out double outOfBagAvgRelError) {
|
---|
310 | return CreateRegressionModel(problemData, problemData.TrainingIndices, nTrees, r, m, seed,
|
---|
311 | rmsError: out rmsError, outOfBagRmsError: out outOfBagRmsError, avgRelError: out avgRelError, outOfBagAvgRelError: out outOfBagAvgRelError);
|
---|
312 | }
|
---|
313 |
|
---|
314 | public static RandomForestModel CreateRegressionModel(IRegressionProblemData problemData, IEnumerable<int> trainingIndices, int nTrees, double r, double m, int seed,
|
---|
315 | out double rmsError, out double outOfBagRmsError, out double avgRelError, out double outOfBagAvgRelError) {
|
---|
316 | var variables = problemData.AllowedInputVariables.Concat(new string[] { problemData.TargetVariable });
|
---|
317 | double[,] inputMatrix = problemData.Dataset.ToArray(variables, trainingIndices);
|
---|
318 |
|
---|
319 | var dForest = RandomForestUtil.CreateRandomForestModelAlglib_3_7(seed, inputMatrix, nTrees, r, m, 1, out var rep);
|
---|
320 |
|
---|
321 | rmsError = rep.rmserror;
|
---|
322 | outOfBagRmsError = rep.oobrmserror;
|
---|
323 | avgRelError = rep.avgrelerror;
|
---|
324 | outOfBagAvgRelError = rep.oobavgrelerror;
|
---|
325 |
|
---|
326 | return new RandomForestModel(problemData.TargetVariable, dForest, seed, problemData, nTrees, r, m);
|
---|
327 | }
|
---|
328 |
|
---|
329 | public static RandomForestModel CreateClassificationModel(IClassificationProblemData problemData, int nTrees, double r, double m, int seed,
|
---|
330 | out double rmsError, out double outOfBagRmsError, out double relClassificationError, out double outOfBagRelClassificationError) {
|
---|
331 | return CreateClassificationModel(problemData, problemData.TrainingIndices, nTrees, r, m, seed,
|
---|
332 | out rmsError, out outOfBagRmsError, out relClassificationError, out outOfBagRelClassificationError);
|
---|
333 | }
|
---|
334 |
|
---|
335 | public static RandomForestModel CreateClassificationModel(IClassificationProblemData problemData, IEnumerable<int> trainingIndices, int nTrees, double r, double m, int seed,
|
---|
336 | out double rmsError, out double outOfBagRmsError, out double relClassificationError, out double outOfBagRelClassificationError) {
|
---|
337 |
|
---|
338 | var variables = problemData.AllowedInputVariables.Concat(new string[] { problemData.TargetVariable });
|
---|
339 | double[,] inputMatrix = problemData.Dataset.ToArray(variables, trainingIndices);
|
---|
340 |
|
---|
341 | var classValues = problemData.ClassValues.ToArray();
|
---|
342 | int nClasses = classValues.Length;
|
---|
343 |
|
---|
344 | // map original class values to values [0..nClasses-1]
|
---|
345 | var classIndices = new Dictionary<double, double>();
|
---|
346 | for (int i = 0; i < nClasses; i++) {
|
---|
347 | classIndices[classValues[i]] = i;
|
---|
348 | }
|
---|
349 |
|
---|
350 | int nRows = inputMatrix.GetLength(0);
|
---|
351 | int nColumns = inputMatrix.GetLength(1);
|
---|
352 | for (int row = 0; row < nRows; row++) {
|
---|
353 | inputMatrix[row, nColumns - 1] = classIndices[inputMatrix[row, nColumns - 1]];
|
---|
354 | }
|
---|
355 |
|
---|
356 | var dForest = RandomForestUtil.CreateRandomForestModelAlglib_3_7(seed, inputMatrix, nTrees, r, m, nClasses, out var rep);
|
---|
357 |
|
---|
358 | rmsError = rep.rmserror;
|
---|
359 | outOfBagRmsError = rep.oobrmserror;
|
---|
360 | relClassificationError = rep.relclserror;
|
---|
361 | outOfBagRelClassificationError = rep.oobrelclserror;
|
---|
362 |
|
---|
363 | return new RandomForestModel(problemData.TargetVariable, dForest, seed, problemData, nTrees, r, m, classValues);
|
---|
364 | }
|
---|
365 |
|
---|
366 | #region persistence for backwards compatibility
|
---|
367 | // when the originalTrainingData is null this means the model was loaded from an old file
|
---|
368 | // therefore, we cannot use the new persistence mechanism because the original data is not available anymore
|
---|
369 | // in such cases we still store the compete model
|
---|
370 | private bool IsCompatibilityLoaded { get { return originalTrainingData == null; } }
|
---|
371 |
|
---|
372 | private string[] allowedInputVariables;
|
---|
373 | [Storable(Name = "allowedInputVariables")]
|
---|
374 | private string[] AllowedInputVariables {
|
---|
375 | get {
|
---|
376 | if (IsCompatibilityLoaded) return allowedInputVariables;
|
---|
377 | else return originalTrainingData.AllowedInputVariables.ToArray();
|
---|
378 | }
|
---|
379 | set { allowedInputVariables = value; }
|
---|
380 | }
|
---|
381 | [Storable]
|
---|
382 | private int RandomForestBufSize {
|
---|
383 | get {
|
---|
384 | if (IsCompatibilityLoaded) return randomForest.innerobj.bufsize;
|
---|
385 | else return 0;
|
---|
386 | }
|
---|
387 | set {
|
---|
388 | randomForest.innerobj.bufsize = value;
|
---|
389 | }
|
---|
390 | }
|
---|
391 | [Storable]
|
---|
392 | private int RandomForestNClasses {
|
---|
393 | get {
|
---|
394 | if (IsCompatibilityLoaded) return randomForest.innerobj.nclasses;
|
---|
395 | else return 0;
|
---|
396 | }
|
---|
397 | set {
|
---|
398 | randomForest.innerobj.nclasses = value;
|
---|
399 | }
|
---|
400 | }
|
---|
401 | [Storable]
|
---|
402 | private int RandomForestNTrees {
|
---|
403 | get {
|
---|
404 | if (IsCompatibilityLoaded) return randomForest.innerobj.ntrees;
|
---|
405 | else return 0;
|
---|
406 | }
|
---|
407 | set {
|
---|
408 | randomForest.innerobj.ntrees = value;
|
---|
409 | }
|
---|
410 | }
|
---|
411 | [Storable]
|
---|
412 | private int RandomForestNVars {
|
---|
413 | get {
|
---|
414 | if (IsCompatibilityLoaded) return randomForest.innerobj.nvars;
|
---|
415 | else return 0;
|
---|
416 | }
|
---|
417 | set {
|
---|
418 | randomForest.innerobj.nvars = value;
|
---|
419 | }
|
---|
420 | }
|
---|
421 | [Storable]
|
---|
422 | private double[] RandomForestTrees {
|
---|
423 | get {
|
---|
424 | if (IsCompatibilityLoaded) return randomForest.innerobj.trees;
|
---|
425 | else return new double[] { };
|
---|
426 | }
|
---|
427 | set {
|
---|
428 | randomForest.innerobj.trees = value;
|
---|
429 | }
|
---|
430 | }
|
---|
431 | #endregion
|
---|
432 | }
|
---|
433 | }
|
---|