-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrandom_forest.cpp
More file actions
1917 lines (1564 loc) · 51.6 KB
/
Copy pathrandom_forest.cpp
File metadata and controls
1917 lines (1564 loc) · 51.6 KB
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
/*
* MIT License
*
* Copyright (c) 2025 Matthew Abbott
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <ctime>
#include <cstdint>
#include <cctype>
const int MAX_FEATURES = 100;
const int MAX_SAMPLES = 10000;
const int MAX_TREES = 500;
const int MAX_DEPTH_DEFAULT = 10;
const int MIN_SAMPLES_LEAF_DEFAULT = 1;
const int MIN_SAMPLES_SPLIT_DEFAULT = 2;
enum TaskType { Classification, Regression };
enum SplitCriterion { Gini, Entropy, MSE, VarianceReduction };
typedef double TDataRow[MAX_FEATURES];
typedef double TTargetArray[MAX_SAMPLES];
typedef TDataRow TDataMatrix[MAX_SAMPLES];
typedef int TIndexArray[MAX_SAMPLES];
typedef int TFeatureArray[MAX_FEATURES];
typedef bool TBoolArray[MAX_SAMPLES];
typedef double TDoubleArray[MAX_FEATURES];
struct TreeNodeRec {
bool isLeaf;
int featureIndex;
double threshold;
double prediction;
int classLabel;
double impurity;
int numSamples;
TreeNodeRec* left;
TreeNodeRec* right;
};
typedef TreeNodeRec* TreeNode;
struct TDecisionTreeRec {
TreeNode root;
int maxDepth;
int minSamplesLeaf;
int minSamplesSplit;
int maxFeatures;
TaskType taskType;
SplitCriterion criterion;
TBoolArray oobIndices;
int numOobIndices;
};
typedef TDecisionTreeRec* TDecisionTree;
class TRandomForest {
private:
TDecisionTree trees[MAX_TREES];
int numTrees;
int maxDepth;
int minSamplesLeaf;
int minSamplesSplit;
int maxFeatures;
int numFeatures;
int numSamples;
TaskType taskType;
SplitCriterion criterion;
TDoubleArray featureImportances;
long randomSeed;
TDataMatrix data;
TTargetArray targets;
public:
TRandomForest();
// Hyperparameter Handling
void setNumTrees(int n);
void setMaxDepth(int d);
void setMinSamplesLeaf(int m);
void setMinSamplesSplit(int m);
void setMaxFeatures(int m);
void setTaskType(TaskType t);
void setCriterion(SplitCriterion c);
void setRandomSeed(long seed);
// Random Number Generator
int randomInt(int maxVal);
double randomDouble();
// Data Handling Functions
void loadData(TDataMatrix inputData, TTargetArray inputTargets,
int nSamples, int nFeatures);
void trainTestSplit(TIndexArray trainIndices, TIndexArray testIndices,
int& numTrain, int& numTest, double testRatio);
void bootstrap(TIndexArray sampleIndices, int& numBootstrap,
TBoolArray oobMask);
void selectFeatureSubset(TFeatureArray featureIndices,
int& numSelected);
// Decision Tree Functions
double calculateGini(TIndexArray indices, int numIndices);
double calculateEntropy(TIndexArray indices, int numIndices);
double calculateMSE(TIndexArray indices, int numIndices);
double calculateVariance(TIndexArray indices, int numIndices);
double calculateImpurity(TIndexArray indices, int numIndices);
bool findBestSplit(TIndexArray indices, int numIndices,
TFeatureArray featureIndices, int nFeatures,
int& bestFeature, double& bestThreshold,
double& bestGain);
int getMajorityClass(TIndexArray indices, int numIndices);
double getMeanTarget(TIndexArray indices, int numIndices);
TreeNode createLeafNode(TIndexArray indices, int numIndices);
bool shouldStop(int depth, int numIndices, double impurity);
TreeNode buildTree(TIndexArray indices, int numIndices,
int depth, TDecisionTree tree);
double predictTree(TreeNode node, TDataRow sample);
void freeTreeNode(TreeNode node);
void freeTree(TDecisionTree tree);
// Random Forest Training
void fit();
void fitTree(int treeIndex);
// Random Forest Prediction
double predict(TDataRow sample);
int predictClass(TDataRow sample);
void predictBatch(TDataMatrix samples, int nSamples,
TTargetArray predictions);
// Out-of-Bag Error
double calculateOOBError();
// Feature Importance
void calculateFeatureImportance();
double getFeatureImportance(int featureIndex);
void printFeatureImportances();
// Performance Metrics
double accuracy(TTargetArray predictions, TTargetArray actual,
int nSamples);
double precision(TTargetArray predictions, TTargetArray actual,
int nSamples, int positiveClass);
double recall(TTargetArray predictions, TTargetArray actual,
int nSamples, int positiveClass);
double f1Score(TTargetArray predictions, TTargetArray actual,
int nSamples, int positiveClass);
double meanSquaredError(TTargetArray predictions, TTargetArray actual,
int nSamples);
double rSquared(TTargetArray predictions, TTargetArray actual,
int nSamples);
// Utility
void printForestInfo();
void freeForest();
// Accessors for Facade
int getNumTrees();
int getNumFeatures();
int getNumSamples();
int getMaxDepth();
int getMaxFeatures();
TDecisionTree getTree(int treeId);
double getData(int sampleIdx, int featureIdx);
double getTarget(int sampleIdx);
TaskType getTaskType();
SplitCriterion getCriterion();
// Tree Management for Facade
void addNewTree();
void removeTreeAt(int treeId);
void retrainTreeAt(int treeId);
// JSON serialization methods
void saveModelToJSON(const char* filename);
void loadModelFromJSON(const char* filename);
// JSON helper functions
const char* taskTypeToStr(TaskType t);
const char* criterionToStr(SplitCriterion c);
TaskType parseTaskType(const char* s);
SplitCriterion parseCriterion(const char* s);
char* Array1DToJSON(TDoubleArray Arr, int size);
char* Array2DToJSON(TDataMatrix Arr, int rows, int cols);
char* treeNodeToJSON(TreeNode node);
TreeNode JSONToTreeNode(const char* json);
};
// ============================================================================
// Constructor
// ============================================================================
TRandomForest::TRandomForest() {
int i;
numTrees = 100;
maxDepth = MAX_DEPTH_DEFAULT;
minSamplesLeaf = MIN_SAMPLES_LEAF_DEFAULT;
minSamplesSplit = MIN_SAMPLES_SPLIT_DEFAULT;
maxFeatures = 0;
numFeatures = 0;
numSamples = 0;
taskType = Classification;
criterion = Gini;
randomSeed = 42;
for (i = 0; i < MAX_TREES; i++)
trees[i] = NULL;
for (i = 0; i < MAX_FEATURES; i++)
featureImportances[i] = 0.0;
srand((unsigned)time(NULL));
}
// ============================================================================
// Hyperparameter Handling
// ============================================================================
void TRandomForest::setNumTrees(int n) {
if (n > MAX_TREES)
numTrees = MAX_TREES;
else if (n < 1)
numTrees = 1;
else
numTrees = n;
}
void TRandomForest::setMaxDepth(int d) {
if (d < 1)
maxDepth = 1;
else
maxDepth = d;
}
void TRandomForest::setMinSamplesLeaf(int m) {
if (m < 1)
minSamplesLeaf = 1;
else
minSamplesLeaf = m;
}
void TRandomForest::setMinSamplesSplit(int m) {
if (m < 2)
minSamplesSplit = 2;
else
minSamplesSplit = m;
}
void TRandomForest::setMaxFeatures(int m) {
maxFeatures = m;
}
void TRandomForest::setTaskType(TaskType t) {
taskType = t;
if (t == Classification)
criterion = Gini;
else
criterion = MSE;
}
void TRandomForest::setCriterion(SplitCriterion c) {
criterion = c;
}
void TRandomForest::setRandomSeed(long seed) {
randomSeed = seed;
srand((unsigned)seed);
}
// ============================================================================
// Random Number Generator
// ============================================================================
int TRandomForest::randomInt(int maxVal) {
if (maxVal <= 0) return 0;
return rand() % maxVal;
}
double TRandomForest::randomDouble() {
return (double)rand() / RAND_MAX;
}
// ============================================================================
// Data Handling Functions
// ============================================================================
void TRandomForest::loadData(TDataMatrix inputData, TTargetArray inputTargets,
int nSamples, int nFeatures) {
int i, j;
numSamples = nSamples;
numFeatures = nFeatures;
if (maxFeatures == 0) {
if (taskType == Classification)
maxFeatures = (int)sqrt(nFeatures);
else
maxFeatures = nFeatures / 3;
if (maxFeatures < 1)
maxFeatures = 1;
}
for (i = 0; i < nSamples; i++) {
for (j = 0; j < nFeatures; j++)
data[i][j] = inputData[i][j];
targets[i] = inputTargets[i];
}
}
void TRandomForest::trainTestSplit(TIndexArray trainIndices, TIndexArray testIndices,
int& numTrain, int& numTest, double testRatio) {
int i, j, temp;
TIndexArray shuffled;
for (i = 0; i < numSamples; i++)
shuffled[i] = i;
for (i = numSamples - 1; i >= 1; i--) {
j = randomInt(i + 1);
temp = shuffled[i];
shuffled[i] = shuffled[j];
shuffled[j] = temp;
}
numTest = (int)(numSamples * testRatio);
numTrain = numSamples - numTest;
for (i = 0; i < numTrain; i++)
trainIndices[i] = shuffled[i];
for (i = 0; i < numTest; i++)
testIndices[i] = shuffled[numTrain + i];
}
void TRandomForest::bootstrap(TIndexArray sampleIndices, int& numBootstrap,
TBoolArray oobMask) {
int i, idx;
numBootstrap = numSamples;
for (i = 0; i < numSamples; i++)
oobMask[i] = true;
for (i = 0; i < numBootstrap; i++) {
idx = randomInt(numSamples);
sampleIndices[i] = idx;
oobMask[idx] = false;
}
}
void TRandomForest::selectFeatureSubset(TFeatureArray featureIndices,
int& numSelected) {
int i, j, temp;
TFeatureArray available;
for (i = 0; i < numFeatures; i++)
available[i] = i;
for (i = numFeatures - 1; i >= 1; i--) {
j = randomInt(i + 1);
temp = available[i];
available[i] = available[j];
available[j] = temp;
}
numSelected = maxFeatures;
if (numSelected > numFeatures)
numSelected = numFeatures;
for (i = 0; i < numSelected; i++)
featureIndices[i] = available[i];
}
// ============================================================================
// Decision Tree - Impurity Functions
// ============================================================================
double TRandomForest::calculateGini(TIndexArray indices, int numIndices) {
int i;
int classCount[100];
int numClasses, classLabel;
double prob, gini;
if (numIndices == 0)
return 0.0;
for (i = 0; i < 100; i++)
classCount[i] = 0;
numClasses = 0;
for (i = 0; i < numIndices; i++) {
classLabel = (int)targets[indices[i]];
if (classLabel > numClasses)
numClasses = classLabel;
classCount[classLabel]++;
}
gini = 1.0;
for (i = 0; i <= numClasses; i++) {
prob = (double)classCount[i] / numIndices;
gini = gini - (prob * prob);
}
return gini;
}
double TRandomForest::calculateEntropy(TIndexArray indices, int numIndices) {
int i;
int classCount[100];
int numClasses, classLabel;
double prob, entropy;
if (numIndices == 0)
return 0.0;
for (i = 0; i < 100; i++)
classCount[i] = 0;
numClasses = 0;
for (i = 0; i < numIndices; i++) {
classLabel = (int)targets[indices[i]];
if (classLabel > numClasses)
numClasses = classLabel;
classCount[classLabel]++;
}
entropy = 0.0;
for (i = 0; i <= numClasses; i++) {
if (classCount[i] > 0) {
prob = (double)classCount[i] / numIndices;
entropy = entropy - (prob * log(prob) / log(2.0));
}
}
return entropy;
}
double TRandomForest::calculateMSE(TIndexArray indices, int numIndices) {
int i;
double mean, mse, diff;
if (numIndices == 0)
return 0.0;
mean = 0.0;
for (i = 0; i < numIndices; i++)
mean = mean + targets[indices[i]];
mean = mean / numIndices;
mse = 0.0;
for (i = 0; i < numIndices; i++) {
diff = targets[indices[i]] - mean;
mse = mse + (diff * diff);
}
return mse / numIndices;
}
double TRandomForest::calculateVariance(TIndexArray indices, int numIndices) {
int i;
double mean, variance, diff;
if (numIndices == 0)
return 0.0;
mean = 0.0;
for (i = 0; i < numIndices; i++)
mean = mean + targets[indices[i]];
mean = mean / numIndices;
variance = 0.0;
for (i = 0; i < numIndices; i++) {
diff = targets[indices[i]] - mean;
variance = variance + (diff * diff);
}
return variance / numIndices;
}
double TRandomForest::calculateImpurity(TIndexArray indices, int numIndices) {
switch (criterion) {
case Gini:
return calculateGini(indices, numIndices);
case Entropy:
return calculateEntropy(indices, numIndices);
case MSE:
return calculateMSE(indices, numIndices);
case VarianceReduction:
return calculateVariance(indices, numIndices);
default:
return calculateGini(indices, numIndices);
}
}
bool TRandomForest::findBestSplit(TIndexArray indices, int numIndices,
TFeatureArray featureIndices, int nFeatures,
int& bestFeature, double& bestThreshold,
double& bestGain) {
int i, j, f, feat;
double threshold, gain, leftImpurity, rightImpurity;
double parentImpurity, leftWeight, rightWeight;
int leftCount, rightCount;
TIndexArray leftIndices, rightIndices;
bool foundSplit = false;
bestGain = -1.0;
bestFeature = -1;
bestThreshold = 0.0;
parentImpurity = calculateImpurity(indices, numIndices);
for (f = 0; f < nFeatures; f++) {
feat = featureIndices[f];
for (i = 0; i < numIndices; i++) {
threshold = data[indices[i]][feat];
leftCount = 0;
rightCount = 0;
for (j = 0; j < numIndices; j++) {
if (data[indices[j]][feat] <= threshold) {
leftIndices[leftCount] = indices[j];
leftCount++;
} else {
rightIndices[rightCount] = indices[j];
rightCount++;
}
}
if (leftCount == 0 || rightCount == 0)
continue;
leftImpurity = calculateImpurity(leftIndices, leftCount);
rightImpurity = calculateImpurity(rightIndices, rightCount);
leftWeight = (double)leftCount / numIndices;
rightWeight = (double)rightCount / numIndices;
gain = parentImpurity - (leftWeight * leftImpurity + rightWeight * rightImpurity);
if (gain > bestGain) {
bestGain = gain;
bestFeature = feat;
bestThreshold = threshold;
foundSplit = true;
}
}
}
return foundSplit;
}
int TRandomForest::getMajorityClass(TIndexArray indices, int numIndices) {
int i;
int classCount[100];
int maxClass = 0, maxCount = 0, classLabel;
for (i = 0; i < 100; i++)
classCount[i] = 0;
for (i = 0; i < numIndices; i++) {
classLabel = (int)targets[indices[i]];
classCount[classLabel]++;
if (classCount[classLabel] > maxCount) {
maxCount = classCount[classLabel];
maxClass = classLabel;
}
}
return maxClass;
}
double TRandomForest::getMeanTarget(TIndexArray indices, int numIndices) {
int i;
double sum = 0.0;
if (numIndices == 0)
return 0.0;
for (i = 0; i < numIndices; i++)
sum = sum + targets[indices[i]];
return sum / numIndices;
}
TreeNode TRandomForest::createLeafNode(TIndexArray indices, int numIndices) {
TreeNode node = new TreeNodeRec();
node->isLeaf = true;
node->left = NULL;
node->right = NULL;
if (taskType == Classification) {
node->classLabel = getMajorityClass(indices, numIndices);
node->prediction = node->classLabel;
} else {
node->prediction = getMeanTarget(indices, numIndices);
node->classLabel = (int)node->prediction;
}
return node;
}
bool TRandomForest::shouldStop(int depth, int numIndices, double impurity) {
if (depth >= maxDepth)
return true;
if (numIndices < minSamplesSplit)
return true;
if (impurity == 0.0)
return true;
return false;
}
TreeNode TRandomForest::buildTree(TIndexArray indices, int numIndices,
int depth, TDecisionTree tree) {
TreeNode node;
TFeatureArray featureIndices;
int numFeatures_, bestFeature;
double bestThreshold, bestGain, impurity;
TIndexArray leftIndices, rightIndices;
int leftCount, rightCount, i, j;
impurity = calculateImpurity(indices, numIndices);
if (shouldStop(depth, numIndices, impurity))
return createLeafNode(indices, numIndices);
selectFeatureSubset(featureIndices, numFeatures_);
if (!findBestSplit(indices, numIndices, featureIndices, numFeatures_,
bestFeature, bestThreshold, bestGain))
return createLeafNode(indices, numIndices);
node = new TreeNodeRec();
node->isLeaf = false;
node->featureIndex = bestFeature;
node->threshold = bestThreshold;
node->impurity = impurity;
node->numSamples = numIndices;
leftCount = 0;
rightCount = 0;
for (i = 0; i < numIndices; i++) {
if (data[indices[i]][bestFeature] <= bestThreshold) {
leftIndices[leftCount] = indices[i];
leftCount++;
} else {
rightIndices[rightCount] = indices[i];
rightCount++;
}
}
node->left = buildTree(leftIndices, leftCount, depth + 1, tree);
node->right = buildTree(rightIndices, rightCount, depth + 1, tree);
return node;
}
double TRandomForest::predictTree(TreeNode node, TDataRow sample) {
if (node == NULL)
return 0.0;
if (node->isLeaf)
return node->prediction;
if (sample[node->featureIndex] <= node->threshold)
return predictTree(node->left, sample);
else
return predictTree(node->right, sample);
}
void TRandomForest::freeTreeNode(TreeNode node) {
if (node == NULL)
return;
if (!node->isLeaf) {
freeTreeNode(node->left);
freeTreeNode(node->right);
}
delete node;
}
void TRandomForest::freeTree(TDecisionTree tree) {
if (tree == NULL)
return;
freeTreeNode(tree->root);
delete tree;
}
// ============================================================================
// Random Forest Training
// ============================================================================
void TRandomForest::fit() {
int i;
for (i = 0; i < numTrees; i++)
fitTree(i);
}
void TRandomForest::fitTree(int treeIndex) {
TIndexArray sampleIndices;
int numBootstrap;
TBoolArray oobMask;
TDecisionTree tree;
int i;
tree = new TDecisionTreeRec();
tree->maxDepth = maxDepth;
tree->minSamplesLeaf = minSamplesLeaf;
tree->minSamplesSplit = minSamplesSplit;
tree->maxFeatures = maxFeatures;
tree->taskType = taskType;
tree->criterion = criterion;
bootstrap(sampleIndices, numBootstrap, oobMask);
for (i = 0; i < numSamples; i++)
tree->oobIndices[i] = oobMask[i];
tree->numOobIndices = 0;
for (i = 0; i < numSamples; i++)
if (tree->oobIndices[i])
tree->numOobIndices++;
tree->root = buildTree(sampleIndices, numBootstrap, 0, tree);
trees[treeIndex] = tree;
}
// ============================================================================
// Random Forest Prediction
// ============================================================================
double TRandomForest::predict(TDataRow sample) {
int i, count = 0;
double sum = 0.0;
for (i = 0; i < numTrees; i++) {
if (trees[i] != NULL) {
sum = sum + predictTree(trees[i]->root, sample);
count++;
}
}
if (count == 0)
return 0.0;
return sum / count;
}
int TRandomForest::predictClass(TDataRow sample) {
return (int)predict(sample);
}
void TRandomForest::predictBatch(TDataMatrix samples, int nSamples,
TTargetArray predictions) {
int i;
for (i = 0; i < nSamples; i++)
predictions[i] = predict(samples[i]);
}
// ============================================================================
// Out-of-Bag Error
// ============================================================================
double TRandomForest::calculateOOBError() {
int i, j, count;
double error = 0.0, prediction;
for (i = 0; i < numSamples; i++) {
count = 0;
prediction = 0.0;
for (j = 0; j < numTrees; j++) {
if (trees[j] != NULL && trees[j]->oobIndices[i]) {
prediction = prediction + predictTree(trees[j]->root, data[i]);
count++;
}
}
if (count > 0) {
prediction = prediction / count;
error = error + (targets[i] - prediction) * (targets[i] - prediction);
}
}
if (numSamples == 0)
return 0.0;
return error / numSamples;
}
// ============================================================================
// Feature Importance
// ============================================================================
void TRandomForest::calculateFeatureImportance() {
int i;
for (i = 0; i < numFeatures; i++)
featureImportances[i] = 0.0;
}
double TRandomForest::getFeatureImportance(int featureIndex) {
if (featureIndex < 0 || featureIndex >= numFeatures)
return 0.0;
return featureImportances[featureIndex];
}
void TRandomForest::printFeatureImportances() {
int i;
printf("Feature Importances:\n");
for (i = 0; i < numFeatures; i++) {
printf("Feature %d: %f\n", i, featureImportances[i]);
}
}
// ============================================================================
// Performance Metrics
// ============================================================================
double TRandomForest::accuracy(TTargetArray predictions, TTargetArray actual,
int nSamples) {
int i, correct = 0;
if (nSamples == 0)
return 0.0;
for (i = 0; i < nSamples; i++) {
if ((int)predictions[i] == (int)actual[i])
correct++;
}
return (double)correct / nSamples;
}
double TRandomForest::precision(TTargetArray predictions, TTargetArray actual,
int nSamples, int positiveClass) {
int i, truePositive = 0, predictedPositive = 0;
for (i = 0; i < nSamples; i++) {
if ((int)predictions[i] == positiveClass) {
predictedPositive++;
if ((int)actual[i] == positiveClass)
truePositive++;
}
}
if (predictedPositive == 0)
return 0.0;
return (double)truePositive / predictedPositive;
}
double TRandomForest::recall(TTargetArray predictions, TTargetArray actual,
int nSamples, int positiveClass) {
int i, truePositive = 0, actualPositive = 0;
for (i = 0; i < nSamples; i++) {
if ((int)actual[i] == positiveClass) {
actualPositive++;
if ((int)predictions[i] == positiveClass)
truePositive++;
}
}
if (actualPositive == 0)
return 0.0;
return (double)truePositive / actualPositive;
}
double TRandomForest::f1Score(TTargetArray predictions, TTargetArray actual,
int nSamples, int positiveClass) {
double p = precision(predictions, actual, nSamples, positiveClass);
double r = recall(predictions, actual, nSamples, positiveClass);
if (p + r == 0.0)
return 0.0;
return 2.0 * (p * r) / (p + r);
}
double TRandomForest::meanSquaredError(TTargetArray predictions, TTargetArray actual,
int nSamples) {
int i;
double mse = 0.0, diff;
if (nSamples == 0)
return 0.0;
for (i = 0; i < nSamples; i++) {
diff = predictions[i] - actual[i];
mse = mse + (diff * diff);
}
return mse / nSamples;
}
double TRandomForest::rSquared(TTargetArray predictions, TTargetArray actual,
int nSamples) {
int i;
double mean = 0.0, ssRes = 0.0, ssTot = 0.0;
if (nSamples == 0)
return 0.0;
for (i = 0; i < nSamples; i++)
mean = mean + actual[i];
mean = mean / nSamples;
for (i = 0; i < nSamples; i++) {
ssRes = ssRes + (actual[i] - predictions[i]) * (actual[i] - predictions[i]);
ssTot = ssTot + (actual[i] - mean) * (actual[i] - mean);
}
if (ssTot == 0.0)
return 0.0;
return 1.0 - (ssRes / ssTot);
}
// ============================================================================
// Utility
// ============================================================================
void TRandomForest::printForestInfo() {
printf("Random Forest Model Information\n");
printf("===============================\n");
printf("Number of trees: %d\n", numTrees);
printf("Max depth: %d\n", maxDepth);
printf("Min samples leaf: %d\n", minSamplesLeaf);
printf("Min samples split: %d\n", minSamplesSplit);
printf("Max features: %d\n", maxFeatures);
printf("Task type: %s\n", taskTypeToStr(taskType));
printf("Criterion: %s\n", criterionToStr(criterion));
}
void TRandomForest::freeForest() {
int i;
for (i = 0; i < numTrees; i++) {
if (trees[i] != NULL) {
freeTree(trees[i]);
trees[i] = NULL;
}
}
numTrees = 0;
}
// ============================================================================
// Accessors for Facade
// ============================================================================
int TRandomForest::getNumTrees() {
return numTrees;
}
int TRandomForest::getNumFeatures() {
return numFeatures;
}
int TRandomForest::getNumSamples() {
return numSamples;
}
int TRandomForest::getMaxDepth() {
return maxDepth;
}