/
DTrees.cs
467 lines (417 loc) · 12.9 KB
/
DTrees.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
using System.Diagnostics.CodeAnalysis;
using OpenCvSharp.Internal;
using OpenCvSharp.Internal.Vectors;
namespace OpenCvSharp.ML;
/// <summary>
/// Decision tree
/// </summary>
public class DTrees : StatModel
{
private Ptr? ptrObj;
#region Init and Disposal
/// <summary>
///
/// </summary>
protected DTrees()
{
ptrObj = null;
}
/// <summary>
/// Creates instance by raw pointer cv::ml::SVM*
/// </summary>
protected DTrees(IntPtr p)
{
ptrObj = new Ptr(p);
ptr = ptrObj.Get();
}
/// <summary>
/// Creates the empty model.
/// </summary>
/// <returns></returns>
public static DTrees Create()
{
NativeMethods.HandleException(
NativeMethods.ml_DTrees_create(out var ptr));
return new DTrees(ptr);
}
/// <summary>
/// Loads and creates a serialized model from a file.
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public static DTrees Load(string filePath)
{
if (filePath is null)
throw new ArgumentNullException(nameof(filePath));
NativeMethods.HandleException(
NativeMethods.ml_DTrees_load(filePath, out var ptr));
return new DTrees(ptr);
}
/// <summary>
/// Loads algorithm from a String.
/// </summary>
/// <param name="strModel">he string variable containing the model you want to load.</param>
/// <returns></returns>
public static DTrees LoadFromString(string strModel)
{
if (strModel is null)
throw new ArgumentNullException(nameof(strModel));
NativeMethods.HandleException(
NativeMethods.ml_DTrees_loadFromString(strModel, out var ptr));
return new DTrees(ptr);
}
/// <summary>
/// Releases managed resources
/// </summary>
protected override void DisposeManaged()
{
ptrObj?.Dispose();
ptrObj = null;
base.DisposeManaged();
}
#endregion
#region Properties
/// <summary>
/// Cluster possible values of a categorical variable into
/// K < =maxCategories clusters to find a suboptimal split.
/// </summary>
public int MaxCategories
{
get
{
NativeMethods.HandleException(
NativeMethods.ml_DTrees_getMaxCategories(ptr, out var ret));
GC.KeepAlive(this);
return ret;
}
set
{
NativeMethods.HandleException(
NativeMethods.ml_DTrees_setMaxCategories(ptr, value));
GC.KeepAlive(this);
}
}
/// <summary>
/// The maximum possible depth of the tree.
/// </summary>
public int MaxDepth
{
get
{
NativeMethods.HandleException(
NativeMethods.ml_DTrees_getMaxDepth(ptr, out var ret));
GC.KeepAlive(this);
return ret;
}
set
{
NativeMethods.HandleException(
NativeMethods.ml_DTrees_setMaxDepth(ptr, value));
GC.KeepAlive(this);
}
}
/// <summary>
/// If the number of samples in a node is less than this parameter then the
/// node will not be split. Default value is 10.
/// </summary>
public int MinSampleCount
{
get
{
NativeMethods.HandleException(
NativeMethods.ml_DTrees_getMinSampleCount(ptr, out var ret));
GC.KeepAlive(this);
return ret;
}
set
{
NativeMethods.HandleException(
NativeMethods.ml_DTrees_setMinSampleCount(ptr, value));
GC.KeepAlive(this);
}
}
/// <summary>
/// If CVFolds \> 1 then algorithms prunes the built decision tree using K-fold
/// cross-validation procedure where K is equal to CVFolds. Default value is 10.
/// </summary>
// ReSharper disable once InconsistentNaming
public int CVFolds
{
get
{
NativeMethods.HandleException(
NativeMethods.ml_DTrees_getCVFolds(ptr, out var ret));
GC.KeepAlive(this);
return ret;
}
set
{
NativeMethods.HandleException(
NativeMethods.ml_DTrees_setCVFolds(ptr, value));
GC.KeepAlive(this);
}
}
/// <summary>
/// If true then surrogate splits will be built.
/// These splits allow to work with missing data and compute variable
/// importance correctly. Default value is false.
/// </summary>
public bool UseSurrogates
{
get
{
NativeMethods.HandleException(
NativeMethods.ml_DTrees_getUseSurrogates(ptr, out var ret));
GC.KeepAlive(this);
return ret != 0;
}
set
{
NativeMethods.HandleException(
NativeMethods.ml_DTrees_setUseSurrogates(ptr, value ? 1 : 0));
GC.KeepAlive(this);
}
}
/// <summary>
/// If true then a pruning will be harsher.
/// This will make a tree more compact and more resistant to the training
/// data noise but a bit less accurate. Default value is true.
/// </summary>
// ReSharper disable once InconsistentNaming
public bool Use1SERule
{
get
{
NativeMethods.HandleException(
NativeMethods.ml_DTrees_getUse1SERule(ptr, out var ret));
GC.KeepAlive(this);
return ret != 0;
}
set
{
NativeMethods.HandleException(
NativeMethods.ml_DTrees_setUse1SERule(ptr, value ? 1 : 0));
GC.KeepAlive(this);
}
}
/// <summary>
/// If true then pruned branches are physically removed from the tree.
/// Otherwise they are retained and it is possible to get results from the
/// original unpruned (or pruned less aggressively) tree. Default value is true.
/// </summary>
public bool TruncatePrunedTree
{
get
{
NativeMethods.HandleException(
NativeMethods.ml_DTrees_getTruncatePrunedTree(ptr, out var ret));
GC.KeepAlive(this);
return ret != 0;
}
set
{
NativeMethods.HandleException(
NativeMethods.ml_DTrees_setTruncatePrunedTree(ptr, value ? 1 : 0));
GC.KeepAlive(this);
}
}
/// <summary>
/// Termination criteria for regression trees.
/// If all absolute differences between an estimated value in a node and
/// values of train samples in this node are less than this parameter
/// then the node will not be split further. Default value is 0.01f.
/// </summary>
public float RegressionAccuracy
{
get
{
NativeMethods.HandleException(
NativeMethods.ml_DTrees_getRegressionAccuracy(ptr, out var ret));
GC.KeepAlive(this);
return ret;
}
set
{
NativeMethods.HandleException(
NativeMethods.ml_DTrees_setRegressionAccuracy(ptr, value));
GC.KeepAlive(this);
}
}
/// <summary>
/// The array of a priori class probabilities, sorted by the class label value.
/// </summary>
public Mat Priors
{
get
{
NativeMethods.HandleException(
NativeMethods.ml_DTrees_getPriors(ptr, out var ret));
GC.KeepAlive(this);
return new Mat(ret);
}
set
{
if (value is null)
throw new ArgumentNullException(nameof(value));
NativeMethods.HandleException(
NativeMethods.ml_DTrees_setPriors(ptr, value.CvPtr));
GC.KeepAlive(this);
}
}
#endregion
#region Methods
/// <summary>
/// Returns indices of root nodes
/// </summary>
/// <returns></returns>
public int[] GetRoots()
{
if (ptr == IntPtr.Zero)
throw new ObjectDisposedException(GetType().Name);
using var vector = new VectorOfInt32();
NativeMethods.HandleException(
NativeMethods.ml_DTrees_getRoots(ptr, vector.CvPtr));
GC.KeepAlive(this);
return vector.ToArray();
}
/// <summary>
/// Returns all the nodes.
/// all the node indices are indices in the returned vector
/// </summary>
public Node[] GetNodes()
{
if (ptr == IntPtr.Zero)
throw new ObjectDisposedException(GetType().Name);
using var vector = new VectorOfDTreesNode();
NativeMethods.HandleException(
NativeMethods.ml_DTrees_getNodes(ptr, vector.CvPtr));
GC.KeepAlive(this);
return vector.ToArray();
}
/// <summary>
/// Returns all the splits.
/// all the split indices are indices in the returned vector
/// </summary>
/// <returns></returns>
public Split[] GetSplits()
{
if (ptr == IntPtr.Zero)
throw new ObjectDisposedException(GetType().Name);
using var vector = new VectorOfDTreesSplit();
NativeMethods.HandleException(
NativeMethods.ml_DTrees_getSplits(ptr, vector.CvPtr));
GC.KeepAlive(this);
return vector.ToArray();
}
/// <summary>
/// Returns all the bitsets for categorical splits.
/// Split::subsetOfs is an offset in the returned vector
/// </summary>
/// <returns></returns>
public int[] GetSubsets()
{
if (ptr == IntPtr.Zero)
throw new ObjectDisposedException(GetType().Name);
using var vector = new VectorOfInt32();
NativeMethods.HandleException(
NativeMethods.ml_DTrees_getSubsets(ptr, vector.CvPtr));
GC.KeepAlive(this);
return vector.ToArray();
}
#endregion
#region Types
#pragma warning disable CA1034
#pragma warning disable CA1051
/// <summary>
/// The class represents a decision tree node.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1815: Override equals and operator equals on value types")]
public struct Node
{
/// <summary>
/// Value at the node: a class label in case of classification or estimated
/// function value in case of regression.
/// </summary>
public double Value;
/// <summary>
/// Class index normalized to 0..class_count-1 range and assigned to the
/// node. It is used internally in classification trees and tree ensembles.
/// </summary>
public int ClassIdx;
/// <summary>
/// Index of the parent node
/// </summary>
public int Parent;
/// <summary>
/// Index of the left child node
/// </summary>
public int Left;
/// <summary>
/// Index of right child node
/// </summary>
public int Right;
/// <summary>
/// Default direction where to go (-1: left or +1: right). It helps in the
/// case of missing values.
/// </summary>
public int DefaultDir;
/// <summary>
/// Index of the first split
/// </summary>
public int Split;
}
#pragma warning disable CA1034
/// <summary>
/// The class represents split in a decision tree.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1815: Override equals and operator equals on value types")]
public struct Split
{
/// <summary>
/// Index of variable on which the split is created.
/// </summary>
public int VarIdx;
/// <summary>
/// If not 0, then the inverse split rule is used (i.e. left and right
/// branches are exchanged in the rule expressions below).
/// </summary>
public int Inversed;
/// <summary>
/// The split quality, a positive number. It is used to choose the best split.
/// </summary>
public float Quality;
/// <summary>
/// Index of the next split in the list of splits for the node
/// </summary>
public int Next;
/// <summary>
/// The threshold value in case of split on an ordered variable.
/// </summary>
public float C;
/// <summary>
/// Offset of the bitset used by the split on a categorical variable.
/// </summary>
public int SubsetOfs;
}
#pragma warning restore CA1051
#endregion
internal class Ptr : OpenCvSharp.Ptr
{
public Ptr(IntPtr ptr) : base(ptr)
{
}
public override IntPtr Get()
{
NativeMethods.HandleException(
NativeMethods.ml_Ptr_DTrees_get(ptr, out var ret));
GC.KeepAlive(this);
return ret;
}
protected override void DisposeUnmanaged()
{
NativeMethods.HandleException(
NativeMethods.ml_Ptr_DTrees_delete(ptr));
base.DisposeUnmanaged();
}
}
}