-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
InternalRegressionTree.cs
1543 lines (1349 loc) · 65 KB
/
InternalRegressionTree.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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.ML.Data;
using Microsoft.ML.Internal.Internallearn;
using Microsoft.ML.Internal.Utilities;
using Microsoft.ML.Model.Pfa;
using Microsoft.ML.Runtime;
using Newtonsoft.Json.Linq;
namespace Microsoft.ML.Trainers.FastTree
{
/// Note that <see cref="InternalRegressionTree"/> is shared between FastTree and LightGBM assemblies,
/// so <see cref="InternalRegressionTree"/> has <see cref="BestFriendAttribute"/>.
[BestFriend]
internal class InternalRegressionTree
{
private double _maxOutput;
private double[] _splitGain;
private double[] _gainPValue;
/// <summary>
/// The value of this non-leaf node, prior to split when it was a leaf.
/// </summary>
private double[] _previousLeafValue;
// for each non-leaf, we keep the following data
public float[] DefaultValueForMissing;
public bool[] ActiveFeatures { get; set; }
public int[] LteChild { get; }
public int[] GtChild { get; }
public int[] SplitFeatures { get; }
/// <summary>
/// Indicates if a node's split feature was categorical.
/// </summary>
public bool[] CategoricalSplit { get; }
/// <summary>
/// Array of categorical values for the categorical feature that might be chosen as
/// a split feature for a node.
/// </summary>
public int[][] CategoricalSplitFeatures;
/// <summary>
/// For a given categorical feature that is chosen as a split feature for a node, this
/// array contains its start and end range in the input feature vector at prediction time.
/// </summary>
public int[][] CategoricalSplitFeatureRanges;
// These are the thresholds based on the binned values of the raw features.
public uint[] Thresholds { get; }
// These are the thresholds based on the raw feature values. Populated after training.
public float[] RawThresholds { get; private set; }
public double[] SplitGains { get { return _splitGain; } }
public double[] GainPValues { get { return _gainPValue; } }
public double[] PreviousLeafValues { get { return _previousLeafValue; } }
public double[] LeafValues { get; }
/// <summary>
/// Code to identify the type of tree in binary serialization. These values are
/// persisted, so they should remain consistent for the sake of deserialization
/// backwards compatibility.
/// </summary>
protected enum TreeType : byte
{
Regression = 0,
Affine = 1,
FastForest = 2
}
private InternalRegressionTree()
{
Weight = 1.0;
}
/// <summary>
/// constructs a regression tree with an upper bound on depth
/// </summary>
public InternalRegressionTree(int maxLeaves)
: this()
{
SplitFeatures = new int[maxLeaves - 1];
CategoricalSplit = new bool[maxLeaves - 1];
_splitGain = new double[maxLeaves - 1];
_gainPValue = new double[maxLeaves - 1];
_previousLeafValue = new double[maxLeaves - 1];
Thresholds = new uint[maxLeaves - 1];
DefaultValueForMissing = null;
LteChild = new int[maxLeaves - 1];
GtChild = new int[maxLeaves - 1];
LeafValues = new double[maxLeaves];
NumLeaves = 1;
}
public InternalRegressionTree(byte[] buffer, ref int position)
: this()
{
NumLeaves = buffer.ToInt(ref position);
_maxOutput = buffer.ToDouble(ref position);
Weight = buffer.ToDouble(ref position);
LteChild = buffer.ToIntArray(ref position);
GtChild = buffer.ToIntArray(ref position);
SplitFeatures = buffer.ToIntArray(ref position);
byte[] categoricalSplitAsBytes = buffer.ToByteArray(ref position);
CategoricalSplit = categoricalSplitAsBytes.Select(b => b > 0).ToArray();
if (CategoricalSplit.Any(b => b))
{
CategoricalSplitFeatures = new int[NumNodes][];
CategoricalSplitFeatureRanges = new int[NumNodes][];
for (int index = 0; index < NumNodes; index++)
{
CategoricalSplitFeatures[index] = buffer.ToIntArray(ref position);
CategoricalSplitFeatureRanges[index] = buffer.ToIntArray(ref position);
}
}
Thresholds = buffer.ToUIntArray(ref position);
RawThresholds = buffer.ToFloatArray(ref position);
_splitGain = buffer.ToDoubleArray(ref position);
_gainPValue = buffer.ToDoubleArray(ref position);
_previousLeafValue = buffer.ToDoubleArray(ref position);
LeafValues = buffer.ToDoubleArray(ref position);
}
private bool[] GetCategoricalSplitFromIndices(int[] indices)
{
bool[] categoricalSplit = new bool[NumNodes];
if (indices == null)
return categoricalSplit;
Contracts.Assert(indices.Length <= NumNodes);
foreach (int index in indices)
{
Contracts.Assert(index >= 0 && index < NumNodes);
categoricalSplit[index] = true;
}
return categoricalSplit;
}
private bool[] GetCategoricalSplitFromBytes(byte[] indices)
{
bool[] categoricalSplit = new bool[NumNodes];
if (indices == null)
return categoricalSplit;
Contracts.Assert(indices.Length <= NumNodes);
foreach (int index in indices)
{
Contracts.Assert(index >= 0 && index < NumNodes);
categoricalSplit[index] = true;
}
return categoricalSplit;
}
/// <summary>
/// Create a Regression Tree object from raw tree contents.
/// </summary>
public static InternalRegressionTree Create(int numLeaves, int[] splitFeatures, double[] splitGain,
float[] rawThresholds, float[] defaultValueForMissing, int[] lteChild, int[] gtChild, double[] leafValues,
int[][] categoricalSplitFeatures, bool[] categoricalSplit)
{
if (numLeaves <= 1)
{
// Create a dummy tree.
InternalRegressionTree tree = new InternalRegressionTree(2);
tree.SetOutput(0, 0.0);
tree.SetOutput(1, 0.0);
return tree;
}
else
{
Contracts.CheckParam(numLeaves - 1 == Utils.Size(splitFeatures), nameof(splitFeatures), "Size error, should equal to numLeaves - 1.");
Contracts.CheckParam(numLeaves - 1 == Utils.Size(splitGain), nameof(splitGain), "Size error, should equal to numLeaves - 1.");
Contracts.CheckParam(numLeaves - 1 == Utils.Size(rawThresholds), nameof(rawThresholds), "Size error, should equal to numLeaves - 1.");
Contracts.CheckParam(numLeaves - 1 == Utils.Size(lteChild), nameof(lteChild), "Size error, should equal to numLeaves - 1.");
Contracts.CheckParam(numLeaves - 1 == Utils.Size(gtChild), nameof(gtChild), "Size error, should equal to numLeaves - 1.");
Contracts.CheckParam(numLeaves - 1 == Utils.Size(defaultValueForMissing), nameof(defaultValueForMissing), "Size error, should equal to numLeaves - 1.");
Contracts.CheckParam(numLeaves == Utils.Size(leafValues), nameof(leafValues), "Size error, should equal to numLeaves.");
Contracts.CheckParam(numLeaves - 1 == Utils.Size(categoricalSplitFeatures), nameof(categoricalSplitFeatures), "Size error, should equal to numLeaves - 1.");
Contracts.CheckParam(numLeaves - 1 == Utils.Size(categoricalSplit), nameof(categoricalSplit), "Size error, should equal to numLeaves - 1.");
return new InternalRegressionTree(splitFeatures, splitGain, null, rawThresholds, defaultValueForMissing, lteChild, gtChild, leafValues, categoricalSplitFeatures, categoricalSplit);
}
}
internal InternalRegressionTree(int[] splitFeatures, double[] splitGain, double[] gainPValue,
float[] rawThresholds, float[] defaultValueForMissing, int[] lteChild, int[] gtChild, double[] leafValues,
int[][] categoricalSplitFeatures, bool[] categoricalSplit)
: this()
{
Contracts.CheckParam(Utils.Size(splitFeatures) > 0, nameof(splitFeatures), "Number of split features must be positive");
NumLeaves = Utils.Size(splitFeatures) + 1;
SplitFeatures = splitFeatures;
_splitGain = splitGain;
_gainPValue = gainPValue;
RawThresholds = rawThresholds;
DefaultValueForMissing = defaultValueForMissing;
LteChild = lteChild;
GtChild = gtChild;
LeafValues = leafValues;
CategoricalSplitFeatures = categoricalSplitFeatures;
CategoricalSplitFeatureRanges = new int[CategoricalSplitFeatures.Length][];
for (int i = 0; i < CategoricalSplitFeatures.Length; ++i)
{
if (CategoricalSplitFeatures[i] != null && CategoricalSplitFeatures[i].Length > 0)
{
CategoricalSplitFeatureRanges[i] = new int[2];
CategoricalSplitFeatureRanges[i][0] = CategoricalSplitFeatures[i].First();
CategoricalSplitFeatureRanges[i][1] = CategoricalSplitFeatures[i].Last();
Contracts.Assert(categoricalSplit[i]);
}
}
CategoricalSplit = categoricalSplit;
CheckValid(Contracts.Check);
if (DefaultValueForMissing != null)
{
bool allZero = true;
foreach (var val in DefaultValueForMissing)
{
if (val != 0.0f)
{
allZero = false;
break;
}
}
if (allZero)
DefaultValueForMissing = null;
}
}
internal InternalRegressionTree(ModelLoadContext ctx, bool usingDefaultValue, bool categoricalSplits)
: this()
{
// *** Binary format ***
// Four convenient quantities to keep in mind:
// -- L and N (number of leaves and nodes, L = N+1)
// -- ML and MN (maximum number of leaves and nodes this can support, ML = MN+1)
// -- C (Number of nodes that have categorical split feature)
// -- CT (Number of categorical feature values for a chosen split feature)
// Some arrays can be null if they do not effect prediction, or redundant.
// All arrays, despite having prescribed sizes, are prefixed with size
//
// byte: tree type code, 0 if regression, 1 if affine (unsupported), 2 if fast forest
// int: number of leaves currently in the tree, L
// double: maxoutput
// double: weight
// int[MN]: lte child, MN is inferred from the length of this array
// int[MN]: gt child
// int[MN]: split feature index
// int[C]: categorical node indices.
// int[C*(CT + 2)]: categorical feature values and categorical feature range in the input feature vector.
// int[MN]: threshold bin index (can be null of raw thresholds are not null)
// float[MN]: raw threshold (can be not null if threshold bin indices are not null)
// float[MN]: default value For missing
// double[ML]: leaf value
// double[MN]: gain of this split (can be null)
// double[MN]: p-value of this split (can be null)
// double[MN]: previous value of a node before it made the transition from leaf to node (can be null)
BinaryReader reader = ctx.Reader;
NumLeaves = reader.ReadInt32();
_maxOutput = reader.ReadDouble();
Weight = reader.ReadDouble();
// Tree structure...
LteChild = reader.ReadIntArray();
GtChild = reader.ReadIntArray();
SplitFeatures = reader.ReadIntArray();
if (categoricalSplits)
{
int[] categoricalNodeIndices = reader.ReadIntArray();
CategoricalSplit = GetCategoricalSplitFromIndices(categoricalNodeIndices);
if (categoricalNodeIndices?.Length > 0)
{
CategoricalSplitFeatures = new int[NumNodes][];
CategoricalSplitFeatureRanges = new int[NumNodes][];
foreach (var index in categoricalNodeIndices)
{
Contracts.Assert(CategoricalSplit[index]);
Contracts.Assert(index >= 0 && index < NumNodes);
CategoricalSplitFeatures[index] = reader.ReadIntArray();
CategoricalSplitFeatureRanges[index] = reader.ReadIntArray(2);
}
}
}
else
CategoricalSplit = new bool[NumNodes];
Thresholds = reader.ReadUIntArray();
RawThresholds = reader.ReadFloatArray();
DefaultValueForMissing = null;
if (usingDefaultValue)
DefaultValueForMissing = reader.ReadFloatArray();
LeafValues = reader.ReadDoubleArray();
// Informational...
_splitGain = reader.ReadDoubleArray();
_gainPValue = reader.ReadDoubleArray();
_previousLeafValue = reader.ReadDoubleArray();
CheckValid(Contracts.CheckDecode);
// Check the need of _defaultValueForMissing
if (DefaultValueForMissing != null)
{
bool allZero = true;
foreach (var val in DefaultValueForMissing)
{
if (val != 0.0f)
{
allZero = false;
break;
}
}
if (allZero)
DefaultValueForMissing = null;
}
}
protected void Save(ModelSaveContext ctx, TreeType code)
{
#if DEBUG
// This must be compiled only in the debug case, since you can't
// have delegates on functions with conditional attributes.
CheckValid((t, s) => Contracts.Assert(t, s));
#endif
// *** Binary format ***
// Four convenient quantities to keep in mind:
// -- L and N (number of leaves and nodes, L = N+1)
// -- ML and MN (maximum number of leaves and nodes this can support, ML = MN+1)
// -- C (Number of nodes that have categorical split feature)
// -- CT (Number of categorical feature values for a chosen split feature)
// Some arrays can be null if they do not effect prediction, or redundant.
// All arrays, despite having prescribed sizes, are prefixed with size
//
// byte: tree type code, 0 if regression, 1 if affine (unsupported), 2 if fast forest
// int: number of leaves currently in the tree, L
// double: maxoutput
// double: weight
// int[MN]: lte child, MN is inferred from the length of this array
// int[MN]: gt child
// int[MN]: split feature index
// int[C]: categorical node indices.
// int[C*(CT + 2)]: categorical feature values and categorical feature range in the input feature vector.
// int[MN]: threshold bin index (can be null if raw thresholds are not null)
// float[MN]: raw threshold (can be not null if threshold bin indices are not null)
// float[MN]: default value For missing
// double[ML]: leaf value
// double[MN]: gain of this split (can be null)
// double[MN]: p-value of this split (can be null)
// double[MN]: previous value of a node before it made the transition from leaf to node (can be null)
BinaryWriter writer = ctx.Writer;
writer.Write((byte)code);
writer.Write(NumLeaves);
writer.Write(_maxOutput);
writer.Write(Weight);
writer.WriteIntArray(LteChild);
writer.WriteIntArray(GtChild);
writer.WriteIntArray(SplitFeatures);
Contracts.Assert(CategoricalSplit != null);
Contracts.Assert(CategoricalSplit.Length >= NumNodes);
List<int> categoricalNodeIndices = new List<int>();
for (int index = 0; index < NumNodes; index++)
{
if (CategoricalSplit[index])
categoricalNodeIndices.Add(index);
}
writer.WriteIntArray(categoricalNodeIndices.ToArray());
for (int index = 0; index < categoricalNodeIndices.Count; index++)
{
int indexLocal = categoricalNodeIndices[index];
Contracts.Assert(indexLocal >= 0 && indexLocal < NumNodes);
Contracts.Assert(CategoricalSplitFeatures[indexLocal] != null &&
CategoricalSplitFeatures[indexLocal].Length > 0);
Contracts.Assert(CategoricalSplitFeatureRanges[indexLocal] != null &&
CategoricalSplitFeatureRanges[indexLocal].Length == 2);
writer.WriteIntArray(CategoricalSplitFeatures[indexLocal]);
writer.WriteIntsNoCount(CategoricalSplitFeatureRanges[indexLocal].AsSpan(0, 2));
}
writer.WriteUIntArray(Thresholds);
writer.WriteSingleArray(RawThresholds);
writer.WriteSingleArray(DefaultValueForMissing);
writer.WriteDoubleArray(LeafValues);
writer.WriteDoubleArray(_splitGain);
writer.WriteDoubleArray(_gainPValue);
writer.WriteDoubleArray(_previousLeafValue);
}
internal virtual void Save(ModelSaveContext ctx)
{
Save(ctx, TreeType.Regression);
}
public static InternalRegressionTree Load(ModelLoadContext ctx, bool usingDefaultValues, bool categoricalSplits)
{
TreeType code = (TreeType)ctx.Reader.ReadByte();
switch (code)
{
case TreeType.Regression:
return new InternalRegressionTree(ctx, usingDefaultValues, categoricalSplits);
case TreeType.Affine:
// Affine regression trees do not actually work, nor is it clear how they ever
// could have worked within TLC, so the chance of this happening seems remote.
throw Contracts.ExceptNotSupp("Affine regression trees unsupported");
case TreeType.FastForest:
return new InternalQuantileRegressionTree(ctx, usingDefaultValues, categoricalSplits);
default:
throw Contracts.ExceptDecode();
}
}
private void CheckValid(Action<bool, string> checker)
{
int numMaxNodes = Utils.Size(LteChild);
int numMaxLeaves = numMaxNodes + 1;
checker(NumLeaves > 1, "non-positive number of leaves");
checker(Weight >= 0, "negative tree weight");
checker(numMaxLeaves >= NumLeaves, "inconsistent number of leaves with maximum leaf capacity");
checker(GtChild != null && GtChild.Length == numMaxNodes, "bad gtchild");
checker(LteChild != null && LteChild.Length == numMaxNodes, "bad ltechild");
checker(SplitFeatures != null && SplitFeatures.Length == numMaxNodes, "bad split feature length");
checker(CategoricalSplit != null &&
(CategoricalSplit.Length == numMaxNodes || CategoricalSplit.Length == NumNodes), "bad categorical split length");
if (CategoricalSplit.Any(x => x))
{
checker(CategoricalSplitFeatures != null &&
(CategoricalSplitFeatures.Length == NumNodes ||
CategoricalSplitFeatures.Length == numMaxNodes),
"bad categorical split features length");
checker(CategoricalSplitFeatureRanges != null &&
(CategoricalSplitFeatureRanges.Length == NumNodes ||
CategoricalSplitFeatureRanges.Length == numMaxNodes),
"bad categorical split feature ranges length");
checker(CategoricalSplitFeatureRanges.All(x => x == null || x.Length == 0 || x.Length == 2),
"bad categorical split feature ranges values");
for (int index = 0; index < CategoricalSplit.Length; index++)
{
if (CategoricalSplit[index])
{
checker(CategoricalSplitFeatures[index] != null, "Categorical split features is null");
checker(CategoricalSplitFeatures[index].Length > 0,
"Categorical split features is zero length");
checker(CategoricalSplitFeatureRanges[index] != null,
"Categorical split feature ranges is null");
checker(CategoricalSplitFeatureRanges[index].Length == 2,
"Categorical split feature range length is not two.");
int previous = -1;
for (int featureIndex = 0; featureIndex < CategoricalSplitFeatures[index].Length; featureIndex++)
{
checker(CategoricalSplitFeatures[index][featureIndex] > previous,
"categorical split features is not sorted");
checker(CategoricalSplitFeatures[index][featureIndex] >=
CategoricalSplitFeatureRanges[index][0] &&
CategoricalSplitFeatures[index][featureIndex] <=
CategoricalSplitFeatureRanges[index][1],
"categorical split features values are out of range.");
previous = CategoricalSplitFeatures[index][featureIndex];
}
}
}
}
checker(Utils.Size(Thresholds) == 0 || Thresholds.Length == numMaxNodes, "bad threshold length");
checker(Utils.Size(RawThresholds) == 0 || RawThresholds.Length == NumLeaves - 1, "bad rawthreshold length");
checker(RawThresholds != null || Thresholds != null,
"at most one of raw or indexed thresholds can be null");
checker(Utils.Size(_splitGain) == 0 || _splitGain.Length == numMaxNodes, "bad splitgain length");
checker(Utils.Size(_gainPValue) == 0 || _gainPValue.Length == numMaxNodes, "bad gainpvalue length");
checker(Utils.Size(_previousLeafValue) == 0 || _previousLeafValue.Length == numMaxNodes, "bad previous leaf value length");
checker(LeafValues != null && LeafValues.Length == numMaxLeaves, "bad leaf value length");
}
public virtual int SizeInBytes()
{
return NumLeaves.SizeInBytes() +
_maxOutput.SizeInBytes() +
Weight.SizeInBytes() +
LteChild.SizeInBytes() +
GtChild.SizeInBytes() +
SplitFeatures.SizeInBytes() +
(CategoricalSplitFeatures != null ? CategoricalSplitFeatures.Select(thresholds => thresholds.SizeInBytes()).Sum() : 0) +
(CategoricalSplitFeatureRanges != null ? CategoricalSplitFeatureRanges.Select(ranges => ranges.SizeInBytes()).Sum() : 0) +
NumNodes * sizeof(int) +
CategoricalSplit.Length * sizeof(bool) +
Thresholds.SizeInBytes() +
RawThresholds.SizeInBytes() +
_splitGain.SizeInBytes() +
_gainPValue.SizeInBytes() +
_previousLeafValue.SizeInBytes() +
LeafValues.SizeInBytes();
}
public virtual void ToByteArray(byte[] buffer, ref int position)
{
NumLeaves.ToByteArray(buffer, ref position);
_maxOutput.ToByteArray(buffer, ref position);
Weight.ToByteArray(buffer, ref position);
LteChild.ToByteArray(buffer, ref position);
GtChild.ToByteArray(buffer, ref position);
SplitFeatures.ToByteArray(buffer, ref position);
CategoricalSplit.Length.ToByteArray(buffer, ref position);
foreach (var split in CategoricalSplit)
Convert.ToByte(split).ToByteArray(buffer, ref position);
if (CategoricalSplitFeatures != null)
{
Contracts.AssertValue(CategoricalSplitFeatureRanges);
for (int i = 0; i < CategoricalSplitFeatures.Length; i++)
{
CategoricalSplitFeatures[i].ToByteArray(buffer, ref position);
CategoricalSplitFeatureRanges[i].ToByteArray(buffer, ref position);
}
}
Thresholds.ToByteArray(buffer, ref position);
RawThresholds.ToByteArray(buffer, ref position);
_splitGain.ToByteArray(buffer, ref position);
_gainPValue.ToByteArray(buffer, ref position);
_previousLeafValue.ToByteArray(buffer, ref position);
LeafValues.ToByteArray(buffer, ref position);
}
public void SumupValue(IChannel ch, InternalRegressionTree tree)
{
if (LeafValues.Length != tree.LeafValues.Length)
{
throw Contracts.Except("cannot sumup value with different lengths");
}
for (int node = 0; node < LeafValues.Length; ++node)
{
if (node < LeafValues.Length - 1 &&
(LteChild[node] != tree.LteChild[node] ||
GtChild[node] != tree.GtChild[node] ||
Thresholds[node] != tree.Thresholds[node] ||
SplitFeatures[node] != tree.SplitFeatures[node] ||
Math.Abs(_splitGain[node] - tree._splitGain[node]) > 1e-6))
{
ch.Warning(
"mismatch @ {10}: {0}/{1}, {2}/{3}, {4}/{5}, {6}/{7}, {8}/{9}",
LteChild[node],
tree.LteChild[node],
GtChild[node],
tree.GtChild[node],
Thresholds[node],
tree.Thresholds[node],
SplitFeatures[node],
tree.SplitFeatures[node],
_splitGain[node],
tree._splitGain[node],
node);
throw Contracts.Except("trees from different workers do not match");
}
LeafValues[node] += tree.LeafValues[node];
}
}
/// <summary>
/// The current number of leaves in the tree.
/// </summary>
public int NumLeaves { get; private set; }
/// <summary>
/// The current number of nodes in the tree. This doesn't include the number of leaves. For example, a tree,
/// node0
/// / \
/// node1 leaf3
/// / \
/// leaf1 leaf2
/// <see cref="NumNodes"/> and <see cref="NumLeaves"/> should be 2 and 3, respectively.
/// </summary>
public int NumNodes => NumLeaves - 1;
/// <summary>
/// The maximum number of leaves the internal structure of this tree can support.
/// </summary>
public int MaxNumLeaves => LeafValues.Length;
/// <summary>
/// The maximum number of nodes this tree can support.
/// </summary>
public int MaxNumNodes => LteChild.Length;
public double MaxOutput => _maxOutput;
/// <summary>
/// Weight of this tree in an <see cref="InternalTreeEnsemble"/>.
/// </summary>
public double Weight { get; set; }
/// <summary>
/// Retrieve the less-than-threshold child node of the specified parent node.
/// </summary>
/// <param name="node">A 0-based index to specify a parent node. This value should be smaller than <see cref="NumNodes"/>.</param>
/// <returns>A child node's index of the specified node.</returns>
public int GetLteChildForNode(int node)
{
return LteChild[node];
}
public int GetGtChildForNode(int node)
{
return GtChild[node];
}
public int SplitFeature(int node)
{
return SplitFeatures[node];
}
public uint Threshold(int node)
{
return Thresholds[node];
}
public float RawThreshold(int node)
{
return RawThresholds[node];
}
/// <summary>
/// Return the prediction value learned at the specified leaf node.
/// </summary>
/// <param name="leaf">A 0-based index to specify a leaf node. This value should be smaller than <see cref="NumLeaves"/>.</param>
/// <returns>The value associated with the specified leaf</returns>
public double LeafValue(int leaf)
{
return LeafValues[leaf];
}
public void SetLeafValue(int leaf, double newValue)
{
LeafValues[leaf] = newValue;
}
// adds value to all of the tree outputs
public void ShiftOutputs(double value)
{
for (int node = 0; node < LeafValues.Length; ++node)
LeafValues[node] += value;
}
/// <summary>
/// Scales all of the output values at the leaves of the tree by a given scalar
/// </summary>
public virtual void ScaleOutputsBy(double scalar)
{
for (int i = 0; i < LeafValues.Length; ++i)
{
LeafValues[i] *= scalar;
}
}
public void UpdateOutputWithDelta(int leafIndex, double delta)
{
LeafValues[leafIndex] += delta;
}
/// <summary>
/// Evaluates the regression tree on a given document.
/// </summary>
/// <param name="featureBins"></param>
/// <returns>the real-valued regression tree output</returns>
public virtual double GetOutput(Dataset.RowForwardIndexer.Row featureBins)
{
if (LteChild[0] == 0)
return 0;
int leaf = GetLeaf(featureBins);
return GetOutput(leaf);
}
/// <summary>
/// evaluates the regression tree on a given binnedinstance.
/// </summary>
/// <param name="binnedInstance">A previously binned instance/document</param>
/// <returns>the real-valued regression tree output</returns>
public virtual double GetOutput(int[] binnedInstance)
{
if (LteChild[0] == 0)
return 0;
int leaf = GetLeaf(binnedInstance);
return GetOutput(leaf);
}
public virtual double GetOutput(in VBuffer<float> feat)
{
if (LteChild[0] == 0)
return 0;
int leaf = GetLeaf(in feat);
return GetOutput(leaf);
}
public double GetOutput(int leaf)
{
return LeafValues[leaf];
}
public void SetOutput(int leaf, double value)
{
LeafValues[leaf] = value;
}
// Returns index to a leaf a document belongs to
// For empty tree returns 0
public int GetLeaf(Dataset.RowForwardIndexer.Row featureBins)
{
// check for an empty tree
if (NumLeaves == 1)
return 0;
int node = 0;
while (node >= 0)
{
if (featureBins[SplitFeatures[node]] <= Thresholds[node])
node = LteChild[node];
else
node = GtChild[node];
}
return ~node;
}
// Returns index to a leaf an instance/document belongs to.
// For empty tree returns 0.
public int GetLeaf(int[] binnedInstance)
{
// check for an empty tree
if (NumLeaves == 1)
return 0;
int node = 0;
while (node >= 0)
{
if (binnedInstance[SplitFeatures[node]] <= Thresholds[node])
node = LteChild[node];
else
node = GtChild[node];
}
return ~node;
}
// Returns index to a leaf an instance/document belongs to.
// Input are the raw feature values in dense format.
// For empty tree returns 0.
public int GetLeaf(in VBuffer<float> feat)
{
// REVIEW: This really should validate feat.Length!
if (feat.IsDense)
return GetLeafCore(feat.GetValues());
return GetLeafCore(feat.GetIndices(), feat.GetValues());
}
/// <summary>
/// Returns leaf index the instance falls into, if we start the search from the <paramref name="root"/> node.
/// </summary>
private int GetLeafFrom(in VBuffer<float> feat, int root)
{
if (root < 0)
{
// This is already a leaf.
return ~root;
}
if (feat.IsDense)
return GetLeafCore(feat.GetValues(), root: root);
return GetLeafCore(feat.GetIndices(), feat.GetValues(), root: root);
}
/// <summary>
/// Returns the leaf node for the given feature vector, and populates 'path' with the list of internal nodes in the
/// path from the root to that leaf. If 'path' is null a new list is initialized. All elements in 'path' are cleared
/// before filling in the current path nodes.
/// </summary>
public int GetLeaf(in VBuffer<float> feat, ref List<int> path)
{
// REVIEW: This really should validate feat.Length!
if (path == null)
path = new List<int>();
else
path.Clear();
if (feat.IsDense)
return GetLeafCore(feat.GetValues(), path);
return GetLeafCore(feat.GetIndices(), feat.GetValues(), path);
}
private float GetFeatureValue(float x, int node)
{
// Not need to convert missing vaules.
if (DefaultValueForMissing == null)
return x;
if (double.IsNaN(x))
{
return DefaultValueForMissing[node];
}
else
{
return x;
}
}
private int GetLeafCore(ReadOnlySpan<float> nonBinnedInstance, List<int> path = null, int root = 0)
{
Contracts.Assert(path == null || path.Count == 0);
Contracts.Assert(root >= 0);
// Check for an empty tree.
if (NumLeaves == 1)
return 0;
int node = root;
if (path == null)
{
while (node >= 0)
{
//REVIEW: Think about optimizing dense case for performance.
if (CategoricalSplit[node])
{
Contracts.Assert(CategoricalSplitFeatures != null);
int newNode = LteChild[node];
foreach (var indices in CategoricalSplitFeatures[node])
{
float fv = GetFeatureValue(nonBinnedInstance[indices], node);
if (fv > 0.0f)
{
newNode = GtChild[node];
break;
}
}
node = newNode;
}
else
{
float fv = GetFeatureValue(nonBinnedInstance[SplitFeatures[node]], node);
if (fv <= RawThresholds[node])
node = LteChild[node];
else
node = GtChild[node];
}
}
}
else
{
while (node >= 0)
{
path.Add(node);
if (CategoricalSplit[node])
{
Contracts.Assert(CategoricalSplitFeatures != null);
int newNode = LteChild[node];
foreach (var index in CategoricalSplitFeatures[node])
{
float fv = GetFeatureValue(nonBinnedInstance[index], node);
if (fv > 0.0f)
{
newNode = GtChild[node];
break;
}
}
node = newNode;
}
else
{
float fv = GetFeatureValue(nonBinnedInstance[SplitFeatures[node]], node);
if (fv <= RawThresholds[node])
node = LteChild[node];
else
node = GtChild[node];
}
}
}
return ~node;
}
private int GetLeafCore(ReadOnlySpan<int> featIndices, ReadOnlySpan<float> featValues, List<int> path = null, int root = 0)
{
Contracts.Assert(featIndices.Length == featValues.Length);
Contracts.Assert(path == null || path.Count == 0);
Contracts.Assert(root >= 0);
int count = featValues.Length;
// check for an empty tree
if (NumLeaves == 1)
return 0;
int node = root;
while (node >= 0)
{
if (path != null)
path.Add(node);
if (CategoricalSplit[node])
{
Contracts.Assert(CategoricalSplitFeatures != null);
Contracts.Assert(CategoricalSplitFeatureRanges != null);
//REVIEW: Consider experimenting with bitmap instead of doing log(n) binary search.
int newNode = LteChild[node];
int end = featIndices.FindIndexSorted(0, count, CategoricalSplitFeatureRanges[node][1]);
for (int i = featIndices.FindIndexSorted(0, count, CategoricalSplitFeatureRanges[node][0]);
i < count && i <= end;
++i)
{
int index = featIndices[i];
if (CategoricalSplitFeatures[node].TryFindIndexSorted(0, CategoricalSplitFeatures[node].Length, index, out int ii))
{
float val = GetFeatureValue(featValues[i], node);
if (val > 0.0f)
{
newNode = GtChild[node];
break;
}
}
}
node = newNode;
}
else
{
float val = 0;
int ifeat = SplitFeatures[node];
int ii = featIndices.FindIndexSorted(0, count, ifeat);
if (ii < count && featIndices[ii] == ifeat)
val = featValues[ii];
val = GetFeatureValue(val, node);
if (val <= RawThresholds[node])
node = LteChild[node];
else
node = GtChild[node];
}
}
return ~node;
}
//Returns all leafs indexes belonging for a given node.
//If node<0 it treats it node as being a leaf and returns ~node
public IEnumerable<int> GetNodesLeaves(int node)
{
if (NumLeaves == 1)
return Enumerable.Range(0, NumLeaves);
if (node < 0)
return Enumerable.Range(~node, 1);
return GetNodesLeaves(LteChild[node]).Concat(GetNodesLeaves(GtChild[node]));
}
/// <summary>
/// returns the hypothesis output for an entire dataset
/// </summary>
public double[] GetOutputs(Dataset dataset)
{
var featureBinRows = dataset.GetFeatureBinRowwiseIndexer();
double[] outputs = new double[dataset.NumDocs];
for (int d = 0; d < dataset.NumDocs; ++d)
outputs[d] = GetOutput(featureBinRows[d]);
return outputs;
}