-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathboost.cpp
executable file
·1680 lines (1482 loc) · 55.8 KB
/
boost.cpp
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
#include "opencv2/core/core.hpp"
#include "opencv2/core/internal.hpp"
#include "boost.h"
#include "cascadeclassifier.h"
#include <queue>
#include "cxmisc.h"
using namespace std;
static inline double
logRatio( double val )
{
const double eps = 1e-5;
val = max( val, eps );
val = min( val, 1. - eps );
return log( val/(1. - val) );
}
#define CV_CMP_FLT(i,j) (i < j)
static CV_IMPLEMENT_QSORT_EX( icvSortFlt, float, CV_CMP_FLT, const float* )
#define CV_CMP_NUM_IDX(i,j) (aux[i] < aux[j])
static CV_IMPLEMENT_QSORT_EX( icvSortIntAux, int, CV_CMP_NUM_IDX, const float* )
static CV_IMPLEMENT_QSORT_EX( icvSortUShAux, unsigned short, CV_CMP_NUM_IDX, const float* )
#define CV_THRESHOLD_EPS (0.00001F)
static const int MinBlockSize = 1 << 16;
static const int BlockSizeDelta = 1 << 10;
// TODO remove this code duplication with ml/precomp.hpp
static int CV_CDECL icvCmpIntegers( const void* a, const void* b )
{
return *(const int*)a - *(const int*)b;
}
static CvMat* cvPreprocessIndexArray( const CvMat* idx_arr, int data_arr_size, bool check_for_duplicates=false )
{
CvMat* idx = 0;
CV_FUNCNAME( "cvPreprocessIndexArray" );
__BEGIN__;
int i, idx_total, idx_selected = 0, step, type, prev = INT_MIN, is_sorted = 1;
uchar* srcb = 0;
int* srci = 0;
int* dsti;
if( !CV_IS_MAT(idx_arr) )
CV_ERROR( CV_StsBadArg, "Invalid index array" );
if( idx_arr->rows != 1 && idx_arr->cols != 1 )
CV_ERROR( CV_StsBadSize, "the index array must be 1-dimensional" );
idx_total = idx_arr->rows + idx_arr->cols - 1;
srcb = idx_arr->data.ptr;
srci = idx_arr->data.i;
type = CV_MAT_TYPE(idx_arr->type);
step = CV_IS_MAT_CONT(idx_arr->type) ? 1 : idx_arr->step/CV_ELEM_SIZE(type);
switch( type )
{
case CV_8UC1:
case CV_8SC1:
// idx_arr is array of 1's and 0's -
// i.e. it is a mask of the selected components
if( idx_total != data_arr_size )
CV_ERROR( CV_StsUnmatchedSizes,
"Component mask should contain as many elements as the total number of input variables" );
for( i = 0; i < idx_total; i++ )
idx_selected += srcb[i*step] != 0;
if( idx_selected == 0 )
CV_ERROR( CV_StsOutOfRange, "No components/input_variables is selected!" );
break;
case CV_32SC1:
// idx_arr is array of integer indices of selected components
if( idx_total > data_arr_size )
CV_ERROR( CV_StsOutOfRange,
"index array may not contain more elements than the total number of input variables" );
idx_selected = idx_total;
// check if sorted already
for( i = 0; i < idx_total; i++ )
{
int val = srci[i*step];
if( val >= prev )
{
is_sorted = 0;
break;
}
prev = val;
}
break;
default:
CV_ERROR( CV_StsUnsupportedFormat, "Unsupported index array data type "
"(it should be 8uC1, 8sC1 or 32sC1)" );
}
CV_CALL( idx = cvCreateMat( 1, idx_selected, CV_32SC1 ));
dsti = idx->data.i;
if( type < CV_32SC1 )
{
for( i = 0; i < idx_total; i++ )
if( srcb[i*step] )
*dsti++ = i;
}
else
{
for( i = 0; i < idx_total; i++ )
dsti[i] = srci[i*step];
if( !is_sorted )
qsort( dsti, idx_total, sizeof(dsti[0]), icvCmpIntegers );
if( dsti[0] < 0 || dsti[idx_total-1] >= data_arr_size )
CV_ERROR( CV_StsOutOfRange, "the index array elements are out of range" );
if( check_for_duplicates )
{
for( i = 1; i < idx_total; i++ )
if( dsti[i] <= dsti[i-1] )
CV_ERROR( CV_StsBadArg, "There are duplicated index array elements" );
}
}
__END__;
if( cvGetErrStatus() < 0 )
cvReleaseMat( &idx );
return idx;
}
//----------------------------- CascadeBoostParams -------------------------------------------------
CvCascadeBoostParams::CvCascadeBoostParams() : minHitRate( 0.995F), maxFalseAlarm( 0.5F )
{
boost_type = CvBoost::GENTLE;
use_surrogates = use_1se_rule = truncate_pruned_tree = false;
}
CvCascadeBoostParams::CvCascadeBoostParams( int _boostType,
float _minHitRate, float _maxFalseAlarm,
double _weightTrimRate, int _maxDepth, int _maxWeakCount ) :
CvBoostParams( _boostType, _maxWeakCount, _weightTrimRate, _maxDepth, false, 0 )
{
boost_type = CvBoost::GENTLE;
minHitRate = _minHitRate;
maxFalseAlarm = _maxFalseAlarm;
use_surrogates = use_1se_rule = truncate_pruned_tree = false;
}
void CvCascadeBoostParams::write( FileStorage &fs ) const
{
String boostTypeStr = boost_type == CvBoost::DISCRETE ? CC_DISCRETE_BOOST :
boost_type == CvBoost::REAL ? CC_REAL_BOOST :
boost_type == CvBoost::LOGIT ? CC_LOGIT_BOOST :
boost_type == CvBoost::GENTLE ? CC_GENTLE_BOOST : String();
CV_Assert( !boostTypeStr.empty() );
fs << CC_BOOST_TYPE << boostTypeStr;
fs << CC_MINHITRATE << minHitRate;
fs << CC_MAXFALSEALARM << maxFalseAlarm;
fs << CC_TRIM_RATE << weight_trim_rate;
fs << CC_MAX_DEPTH << max_depth;
fs << CC_WEAK_COUNT << weak_count;
}
bool CvCascadeBoostParams::read( const FileNode &node )
{
String boostTypeStr;
FileNode rnode = node[CC_BOOST_TYPE];
rnode >> boostTypeStr;
boost_type = !boostTypeStr.compare( CC_DISCRETE_BOOST ) ? CvBoost::DISCRETE :
!boostTypeStr.compare( CC_REAL_BOOST ) ? CvBoost::REAL :
!boostTypeStr.compare( CC_LOGIT_BOOST ) ? CvBoost::LOGIT :
!boostTypeStr.compare( CC_GENTLE_BOOST ) ? CvBoost::GENTLE : -1;
if (boost_type == -1)
CV_Error( CV_StsBadArg, "unsupported Boost type" );
node[CC_MINHITRATE] >> minHitRate;
node[CC_MAXFALSEALARM] >> maxFalseAlarm;
node[CC_TRIM_RATE] >> weight_trim_rate ;
node[CC_MAX_DEPTH] >> max_depth ;
node[CC_WEAK_COUNT] >> weak_count ;
if ( minHitRate <= 0 || minHitRate > 1 ||
maxFalseAlarm <= 0 || maxFalseAlarm > 1 ||
weight_trim_rate <= 0 || weight_trim_rate > 1 ||
max_depth <= 0 || weak_count <= 0 )
CV_Error( CV_StsBadArg, "bad parameters range");
return true;
}
void CvCascadeBoostParams::printDefaults() const
{
cout << "--boostParams--" << endl;
cout << " [-bt <{" << CC_DISCRETE_BOOST << ", "
<< CC_REAL_BOOST << ", "
<< CC_LOGIT_BOOST ", "
<< CC_GENTLE_BOOST << "(default)}>]" << endl;
cout << " [-minHitRate <min_hit_rate> = " << minHitRate << ">]" << endl;
cout << " [-maxFalseAlarmRate <max_false_alarm_rate = " << maxFalseAlarm << ">]" << endl;
cout << " [-weightTrimRate <weight_trim_rate = " << weight_trim_rate << ">]" << endl;
cout << " [-maxDepth <max_depth_of_weak_tree = " << max_depth << ">]" << endl;
cout << " [-maxWeakCount <max_weak_tree_count = " << weak_count << ">]" << endl;
}
void CvCascadeBoostParams::printAttrs() const
{
String boostTypeStr = boost_type == CvBoost::DISCRETE ? CC_DISCRETE_BOOST :
boost_type == CvBoost::REAL ? CC_REAL_BOOST :
boost_type == CvBoost::LOGIT ? CC_LOGIT_BOOST :
boost_type == CvBoost::GENTLE ? CC_GENTLE_BOOST : String();
CV_Assert( !boostTypeStr.empty() );
cout << "boostType: " << boostTypeStr << endl;
cout << "minHitRate: " << minHitRate << endl;
cout << "maxFalseAlarmRate: " << maxFalseAlarm << endl;
cout << "weightTrimRate: " << weight_trim_rate << endl;
cout << "maxDepth: " << max_depth << endl;
cout << "maxWeakCount: " << weak_count << endl;
}
bool CvCascadeBoostParams::scanAttr( const String prmName, const String val)
{
bool res = true;
if( !prmName.compare( "-bt" ) )
{
boost_type = !val.compare( CC_DISCRETE_BOOST ) ? CvBoost::DISCRETE :
!val.compare( CC_REAL_BOOST ) ? CvBoost::REAL :
!val.compare( CC_LOGIT_BOOST ) ? CvBoost::LOGIT :
!val.compare( CC_GENTLE_BOOST ) ? CvBoost::GENTLE : -1;
if (boost_type == -1)
res = false;
}
else if( !prmName.compare( "-minHitRate" ) )
{
minHitRate = (float) atof( val.c_str() );
}
else if( !prmName.compare( "-maxFalseAlarmRate" ) )
{
maxFalseAlarm = (float) atof( val.c_str() );
}
else if( !prmName.compare( "-weightTrimRate" ) )
{
weight_trim_rate = (float) atof( val.c_str() );
}
else if( !prmName.compare( "-maxDepth" ) )
{
max_depth = atoi( val.c_str() );
}
else if( !prmName.compare( "-maxWeakCount" ) )
{
weak_count = atoi( val.c_str() );
}
else
res = false;
return res;
}
CvDTreeNode* CvCascadeBoostTrainData::subsample_data( const CvMat* _subsample_idx )
{
CvDTreeNode* root = 0;
CvMat* isubsample_idx = 0;
CvMat* subsample_co = 0;
bool isMakeRootCopy = true;
if( !data_root )
CV_Error( CV_StsError, "No training data has been set" );
if( _subsample_idx )
{
CV_Assert( (isubsample_idx = cvPreprocessIndexArray( _subsample_idx, sample_count )) != 0 );
if( isubsample_idx->cols + isubsample_idx->rows - 1 == sample_count )
{
const int* sidx = isubsample_idx->data.i;
for( int i = 0; i < sample_count; i++ )
{
if( sidx[i] != i )
{
isMakeRootCopy = false;
break;
}
}
}
else
isMakeRootCopy = false;
}
if( isMakeRootCopy )
{
// make a copy of the root node
CvDTreeNode temp;
int i;
root = new_node( 0, 1, 0, 0 );
temp = *root;
*root = *data_root;
root->num_valid = temp.num_valid;
if( root->num_valid )
{
for( i = 0; i < var_count; i++ )
root->num_valid[i] = data_root->num_valid[i];
}
root->cv_Tn = temp.cv_Tn;
root->cv_node_risk = temp.cv_node_risk;
root->cv_node_error = temp.cv_node_error;
}
else
{
int* sidx = isubsample_idx->data.i;
// co - array of count/offset pairs (to handle duplicated values in _subsample_idx)
int* co, cur_ofs = 0;
int workVarCount = get_work_var_count();
int count = isubsample_idx->rows + isubsample_idx->cols - 1;
root = new_node( 0, count, 1, 0 );
CV_Assert( (subsample_co = cvCreateMat( 1, sample_count*2, CV_32SC1 )) != 0);
cvZero( subsample_co );
co = subsample_co->data.i;
for( int i = 0; i < count; i++ )
co[sidx[i]*2]++;
for( int i = 0; i < sample_count; i++ )
{
if( co[i*2] )
{
co[i*2+1] = cur_ofs;
cur_ofs += co[i*2];
}
else
co[i*2+1] = -1;
}
cv::AutoBuffer<uchar> inn_buf(sample_count*(2*sizeof(int) + sizeof(float)));
// subsample ordered variables
for( int vi = 0; vi < numPrecalcIdx; vi++ )
{
int ci = get_var_type(vi);
CV_Assert( ci < 0 );
int *src_idx_buf = (int*)(uchar*)inn_buf;
float *src_val_buf = (float*)(src_idx_buf + sample_count);
int* sample_indices_buf = (int*)(src_val_buf + sample_count);
const int* src_idx = 0;
const float* src_val = 0;
get_ord_var_data( data_root, vi, src_val_buf, src_idx_buf, &src_val, &src_idx, sample_indices_buf );
int j = 0, idx, count_i;
int num_valid = data_root->get_num_valid(vi);
CV_Assert( num_valid == sample_count );
if (is_buf_16u)
{
unsigned short* udst_idx = (unsigned short*)(buf->data.s + root->buf_idx*get_length_subbuf() +
vi*sample_count + data_root->offset);
for( int i = 0; i < num_valid; i++ )
{
idx = src_idx[i];
count_i = co[idx*2];
if( count_i )
for( cur_ofs = co[idx*2+1]; count_i > 0; count_i--, j++, cur_ofs++ )
udst_idx[j] = (unsigned short)cur_ofs;
}
}
else
{
int* idst_idx = buf->data.i + root->buf_idx*get_length_subbuf() +
vi*sample_count + root->offset;
for( int i = 0; i < num_valid; i++ )
{
idx = src_idx[i];
count_i = co[idx*2];
if( count_i )
for( cur_ofs = co[idx*2+1]; count_i > 0; count_i--, j++, cur_ofs++ )
idst_idx[j] = cur_ofs;
}
}
}
// subsample cv_lables
const int* src_lbls = get_cv_labels(data_root, (int*)(uchar*)inn_buf);
if (is_buf_16u)
{
unsigned short* udst = (unsigned short*)(buf->data.s + root->buf_idx*get_length_subbuf() +
(workVarCount-1)*sample_count + root->offset);
for( int i = 0; i < count; i++ )
udst[i] = (unsigned short)src_lbls[sidx[i]];
}
else
{
int* idst = buf->data.i + root->buf_idx*get_length_subbuf() +
(workVarCount-1)*sample_count + root->offset;
for( int i = 0; i < count; i++ )
idst[i] = src_lbls[sidx[i]];
}
// subsample sample_indices
const int* sample_idx_src = get_sample_indices(data_root, (int*)(uchar*)inn_buf);
if (is_buf_16u)
{
unsigned short* sample_idx_dst = (unsigned short*)(buf->data.s + root->buf_idx*get_length_subbuf() +
workVarCount*sample_count + root->offset);
for( int i = 0; i < count; i++ )
sample_idx_dst[i] = (unsigned short)sample_idx_src[sidx[i]];
}
else
{
int* sample_idx_dst = buf->data.i + root->buf_idx*get_length_subbuf() +
workVarCount*sample_count + root->offset;
for( int i = 0; i < count; i++ )
sample_idx_dst[i] = sample_idx_src[sidx[i]];
}
for( int vi = 0; vi < var_count; vi++ )
root->set_num_valid(vi, count);
}
cvReleaseMat( &isubsample_idx );
cvReleaseMat( &subsample_co );
return root;
}
//---------------------------- CascadeBoostTrainData -----------------------------
CvCascadeBoostTrainData::CvCascadeBoostTrainData( const CvFeatureEvaluator* _featureEvaluator,
const CvDTreeParams& _params )
{
is_classifier = true;
var_all = var_count = (int)_featureEvaluator->getNumFeatures();
featureEvaluator = _featureEvaluator;
shared = true;
set_params( _params );
max_c_count = MAX( 2, featureEvaluator->getMaxCatCount() );
var_type = cvCreateMat( 1, var_count + 2, CV_32SC1 );
if ( featureEvaluator->getMaxCatCount() > 0 )
{
numPrecalcIdx = 0;
cat_var_count = var_count;
ord_var_count = 0;
for( int vi = 0; vi < var_count; vi++ )
{
var_type->data.i[vi] = vi;
}
}
else
{
cat_var_count = 0;
ord_var_count = var_count;
for( int vi = 1; vi <= var_count; vi++ )
{
var_type->data.i[vi-1] = -vi;
}
}
var_type->data.i[var_count] = cat_var_count;
var_type->data.i[var_count+1] = cat_var_count+1;
int maxSplitSize = cvAlign(sizeof(CvDTreeSplit) + (MAX(0,max_c_count - 33)/32)*sizeof(int),sizeof(void*));
int treeBlockSize = MAX((int)sizeof(CvDTreeNode)*8, maxSplitSize);
treeBlockSize = MAX(treeBlockSize + BlockSizeDelta, MinBlockSize);
tree_storage = cvCreateMemStorage( treeBlockSize );
node_heap = cvCreateSet( 0, sizeof(node_heap[0]), sizeof(CvDTreeNode), tree_storage );
split_heap = cvCreateSet( 0, sizeof(split_heap[0]), maxSplitSize, tree_storage );
}
CvCascadeBoostTrainData::CvCascadeBoostTrainData( const CvFeatureEvaluator* _featureEvaluator,
int _numSamples,
int _precalcValBufSize, int _precalcIdxBufSize,
const CvDTreeParams& _params )
{
setData( _featureEvaluator, _numSamples, _precalcValBufSize, _precalcIdxBufSize, _params );
}
void CvCascadeBoostTrainData::setData( const CvFeatureEvaluator* _featureEvaluator,
int _numSamples,
int _precalcValBufSize, int _precalcIdxBufSize,
const CvDTreeParams& _params )
{
int* idst = 0;
unsigned short* udst = 0;
uint64 effective_buf_size = 0;
int effective_buf_height = 0, effective_buf_width = 0;
clear();
shared = true;
have_labels = true;
have_priors = false;
is_classifier = true;
rng = &cv::theRNG();
set_params( _params );
CV_Assert( _featureEvaluator );
featureEvaluator = _featureEvaluator;
max_c_count = MAX( 2, featureEvaluator->getMaxCatCount() );
_resp = featureEvaluator->getCls();
responses = &_resp;
// TODO: check responses: elements must be 0 or 1
if( _precalcValBufSize < 0 || _precalcIdxBufSize < 0)
CV_Error( CV_StsOutOfRange, "_numPrecalcVal and _numPrecalcIdx must be positive or 0" );
var_count = var_all = featureEvaluator->getNumFeatures() * featureEvaluator->getFeatureSize();
sample_count = _numSamples;
is_buf_16u = false;
if (sample_count < 65536)
is_buf_16u = true;
numPrecalcVal = min( cvRound((double)_precalcValBufSize*1048576. / (sizeof(float)*sample_count)), var_count );
numPrecalcIdx = min( cvRound((double)_precalcIdxBufSize*1048576. /
((is_buf_16u ? sizeof(unsigned short) : sizeof (int))*sample_count)), var_count );
assert( numPrecalcIdx >= 0 && numPrecalcVal >= 0 );
valCache.create( numPrecalcVal, sample_count, CV_32FC1 );
var_type = cvCreateMat( 1, var_count + 2, CV_32SC1 );
if ( featureEvaluator->getMaxCatCount() > 0 )
{
numPrecalcIdx = 0;
cat_var_count = var_count;
ord_var_count = 0;
for( int vi = 0; vi < var_count; vi++ )
{
var_type->data.i[vi] = vi;
}
}
else
{
cat_var_count = 0;
ord_var_count = var_count;
for( int vi = 1; vi <= var_count; vi++ )
{
var_type->data.i[vi-1] = -vi;
}
}
var_type->data.i[var_count] = cat_var_count;
var_type->data.i[var_count+1] = cat_var_count+1;
work_var_count = ( cat_var_count ? 0 : numPrecalcIdx ) + 1/*cv_lables*/;
buf_count = 2;
buf_size = -1; // the member buf_size is obsolete
effective_buf_size = (uint64)(work_var_count + 1)*(uint64)sample_count * buf_count; // this is the total size of "CvMat buf" to be allocated
effective_buf_width = sample_count;
effective_buf_height = work_var_count+1;
if (effective_buf_width >= effective_buf_height)
effective_buf_height *= buf_count;
else
effective_buf_width *= buf_count;
if ((uint64)effective_buf_width * (uint64)effective_buf_height != effective_buf_size)
{
CV_Error(CV_StsBadArg, "The memory buffer cannot be allocated since its size exceeds integer fields limit");
}
if ( is_buf_16u )
buf = cvCreateMat( effective_buf_height, effective_buf_width, CV_16UC1 );
else
buf = cvCreateMat( effective_buf_height, effective_buf_width, CV_32SC1 );
cat_count = cvCreateMat( 1, cat_var_count + 1, CV_32SC1 );
// precalculate valCache and set indices in buf
precalculate();
// now calculate the maximum size of split,
// create memory storage that will keep nodes and splits of the decision tree
// allocate root node and the buffer for the whole training data
int maxSplitSize = cvAlign(sizeof(CvDTreeSplit) +
(MAX(0,sample_count - 33)/32)*sizeof(int),sizeof(void*));
int treeBlockSize = MAX((int)sizeof(CvDTreeNode)*8, maxSplitSize);
treeBlockSize = MAX(treeBlockSize + BlockSizeDelta, MinBlockSize);
tree_storage = cvCreateMemStorage( treeBlockSize );
node_heap = cvCreateSet( 0, sizeof(*node_heap), sizeof(CvDTreeNode), tree_storage );
int nvSize = var_count*sizeof(int);
nvSize = cvAlign(MAX( nvSize, (int)sizeof(CvSetElem) ), sizeof(void*));
int tempBlockSize = nvSize;
tempBlockSize = MAX( tempBlockSize + BlockSizeDelta, MinBlockSize );
temp_storage = cvCreateMemStorage( tempBlockSize );
nv_heap = cvCreateSet( 0, sizeof(*nv_heap), nvSize, temp_storage );
data_root = new_node( 0, sample_count, 0, 0 );
// set sample labels
if (is_buf_16u)
udst = (unsigned short*)(buf->data.s + work_var_count*sample_count);
else
idst = buf->data.i + work_var_count*sample_count;
for (int si = 0; si < sample_count; si++)
{
if (udst)
udst[si] = (unsigned short)si;
else
idst[si] = si;
}
for( int vi = 0; vi < var_count; vi++ )
data_root->set_num_valid(vi, sample_count);
for( int vi = 0; vi < cat_var_count; vi++ )
cat_count->data.i[vi] = max_c_count;
cat_count->data.i[cat_var_count] = 2;
maxSplitSize = cvAlign(sizeof(CvDTreeSplit) +
(MAX(0,max_c_count - 33)/32)*sizeof(int),sizeof(void*));
split_heap = cvCreateSet( 0, sizeof(*split_heap), maxSplitSize, tree_storage );
priors = cvCreateMat( 1, get_num_classes(), CV_64F );
cvSet(priors, cvScalar(1));
priors_mult = cvCloneMat( priors );
counts = cvCreateMat( 1, get_num_classes(), CV_32SC1 );
direction = cvCreateMat( 1, sample_count, CV_8UC1 );
split_buf = cvCreateMat( 1, sample_count, CV_32SC1 );//TODO: make a pointer
}
void CvCascadeBoostTrainData::free_train_data()
{
CvDTreeTrainData::free_train_data();
valCache.release();
}
const int* CvCascadeBoostTrainData::get_class_labels( CvDTreeNode* n, int* labelsBuf)
{
int nodeSampleCount = n->sample_count;
int rStep = CV_IS_MAT_CONT( responses->type ) ? 1 : responses->step / CV_ELEM_SIZE( responses->type );
int* sampleIndicesBuf = labelsBuf; //
const int* sampleIndices = get_sample_indices(n, sampleIndicesBuf);
for( int si = 0; si < nodeSampleCount; si++ )
{
int sidx = sampleIndices[si];
labelsBuf[si] = (int)responses->data.fl[sidx*rStep];
}
return labelsBuf;
}
const int* CvCascadeBoostTrainData::get_sample_indices( CvDTreeNode* n, int* indicesBuf )
{
return CvDTreeTrainData::get_cat_var_data( n, get_work_var_count(), indicesBuf );
}
const int* CvCascadeBoostTrainData::get_cv_labels( CvDTreeNode* n, int* labels_buf )
{
return CvDTreeTrainData::get_cat_var_data( n, get_work_var_count() - 1, labels_buf );
}
void CvCascadeBoostTrainData::get_ord_var_data( CvDTreeNode* n, int vi, float* ordValuesBuf, int* sortedIndicesBuf,
const float** ordValues, const int** sortedIndices, int* sampleIndicesBuf )
{
int nodeSampleCount = n->sample_count;
const int* sampleIndices = get_sample_indices(n, sampleIndicesBuf);
if ( vi < numPrecalcIdx )
{
if( !is_buf_16u )
*sortedIndices = buf->data.i + n->buf_idx*get_length_subbuf() + vi*sample_count + n->offset;
else
{
const unsigned short* shortIndices = (const unsigned short*)(buf->data.s + n->buf_idx*get_length_subbuf() +
vi*sample_count + n->offset );
for( int i = 0; i < nodeSampleCount; i++ )
sortedIndicesBuf[i] = shortIndices[i];
*sortedIndices = sortedIndicesBuf;
}
if( vi < numPrecalcVal )
{
for( int i = 0; i < nodeSampleCount; i++ )
{
int idx = (*sortedIndices)[i];
idx = sampleIndices[idx];
ordValuesBuf[i] = valCache.at<float>( vi, idx);
}
}
else
{
for( int i = 0; i < nodeSampleCount; i++ )
{
int idx = (*sortedIndices)[i];
idx = sampleIndices[idx];
ordValuesBuf[i] = (*featureEvaluator)( vi, idx);
}
}
}
else // vi >= numPrecalcIdx
{
cv::AutoBuffer<float> abuf(nodeSampleCount);
float* sampleValues = &abuf[0];
if ( vi < numPrecalcVal )
{
for( int i = 0; i < nodeSampleCount; i++ )
{
sortedIndicesBuf[i] = i;
sampleValues[i] = valCache.at<float>( vi, sampleIndices[i] );
}
}
else
{
for( int i = 0; i < nodeSampleCount; i++ )
{
sortedIndicesBuf[i] = i;
sampleValues[i] = (*featureEvaluator)( vi, sampleIndices[i]);
}
}
icvSortIntAux( sortedIndicesBuf, nodeSampleCount, &sampleValues[0] );
for( int i = 0; i < nodeSampleCount; i++ )
ordValuesBuf[i] = (&sampleValues[0])[sortedIndicesBuf[i]];
*sortedIndices = sortedIndicesBuf;
}
*ordValues = ordValuesBuf;
}
const int* CvCascadeBoostTrainData::get_cat_var_data( CvDTreeNode* n, int vi, int* catValuesBuf )
{
int nodeSampleCount = n->sample_count;
int* sampleIndicesBuf = catValuesBuf; //
const int* sampleIndices = get_sample_indices(n, sampleIndicesBuf);
if ( vi < numPrecalcVal )
{
for( int i = 0; i < nodeSampleCount; i++ )
catValuesBuf[i] = (int) valCache.at<float>( vi, sampleIndices[i]);
}
else
{
if( vi >= numPrecalcVal && vi < var_count )
{
for( int i = 0; i < nodeSampleCount; i++ )
catValuesBuf[i] = (int)(*featureEvaluator)( vi, sampleIndices[i] );
}
else
{
get_cv_labels( n, catValuesBuf );
}
}
return catValuesBuf;
}
float CvCascadeBoostTrainData::getVarValue( int vi, int si )
{
if ( vi < numPrecalcVal && !valCache.empty() )
return valCache.at<float>( vi, si );
return (*featureEvaluator)( vi, si );
}
struct FeatureIdxOnlyPrecalc
{
FeatureIdxOnlyPrecalc( const CvFeatureEvaluator* _featureEvaluator, CvMat* _buf, int _sample_count, bool _is_buf_16u )
{
featureEvaluator = _featureEvaluator;
sample_count = _sample_count;
udst = (unsigned short*)_buf->data.s;
idst = _buf->data.i;
is_buf_16u = _is_buf_16u;
}
void operator()( const BlockedRange& range ) const
{
cv::AutoBuffer<float> valCache(sample_count);
float* valCachePtr = (float*)valCache;
for ( int fi = range.begin(); fi < range.end(); fi++)
{
for( int si = 0; si < sample_count; si++ )
{
valCachePtr[si] = (*featureEvaluator)( fi, si );
if ( is_buf_16u )
*(udst + fi*sample_count + si) = (unsigned short)si;
else
*(idst + fi*sample_count + si) = si;
}
if ( is_buf_16u )
icvSortUShAux( udst + fi*sample_count, sample_count, valCachePtr );
else
icvSortIntAux( idst + fi*sample_count, sample_count, valCachePtr );
}
}
const CvFeatureEvaluator* featureEvaluator;
int sample_count;
int* idst;
unsigned short* udst;
bool is_buf_16u;
};
struct FeatureValAndIdxPrecalc
{
FeatureValAndIdxPrecalc( const CvFeatureEvaluator* _featureEvaluator, CvMat* _buf, Mat* _valCache, int _sample_count, bool _is_buf_16u )
{
featureEvaluator = _featureEvaluator;
valCache = _valCache;
sample_count = _sample_count;
udst = (unsigned short*)_buf->data.s;
idst = _buf->data.i;
is_buf_16u = _is_buf_16u;
}
void operator()( const BlockedRange& range ) const
{
for ( int fi = range.begin(); fi < range.end(); fi++)
{
for( int si = 0; si < sample_count; si++ )
{
valCache->at<float>(fi,si) = (*featureEvaluator)( fi, si );
if ( is_buf_16u )
*(udst + fi*sample_count + si) = (unsigned short)si;
else
*(idst + fi*sample_count + si) = si;
}
if ( is_buf_16u )
icvSortUShAux( udst + fi*sample_count, sample_count, valCache->ptr<float>(fi) );
else
icvSortIntAux( idst + fi*sample_count, sample_count, valCache->ptr<float>(fi) );
}
}
const CvFeatureEvaluator* featureEvaluator;
Mat* valCache;
int sample_count;
int* idst;
unsigned short* udst;
bool is_buf_16u;
};
struct FeatureValOnlyPrecalc
{
FeatureValOnlyPrecalc( const CvFeatureEvaluator* _featureEvaluator, Mat* _valCache, int _sample_count )
{
featureEvaluator = _featureEvaluator;
valCache = _valCache;
sample_count = _sample_count;
}
void operator()( const BlockedRange& range ) const
{
for ( int fi = range.begin(); fi < range.end(); fi++)
for( int si = 0; si < sample_count; si++ )
valCache->at<float>(fi,si) = (*featureEvaluator)( fi, si );
}
const CvFeatureEvaluator* featureEvaluator;
Mat* valCache;
int sample_count;
};
void CvCascadeBoostTrainData::precalculate()
{
int minNum = MIN( numPrecalcVal, numPrecalcIdx);
double proctime = -TIME( 0 );
parallel_for( BlockedRange(numPrecalcVal, numPrecalcIdx),
FeatureIdxOnlyPrecalc(featureEvaluator, buf, sample_count, is_buf_16u!=0) );
parallel_for( BlockedRange(0, minNum),
FeatureValAndIdxPrecalc(featureEvaluator, buf, &valCache, sample_count, is_buf_16u!=0) );
parallel_for( BlockedRange(minNum, numPrecalcVal),
FeatureValOnlyPrecalc(featureEvaluator, &valCache, sample_count) );
cout << "Precalculation time: " << (proctime + TIME( 0 )) << endl;
}
//-------------------------------- CascadeBoostTree ----------------------------------------
CvDTreeNode* CvCascadeBoostTree::predict( int sampleIdx ) const
{
CvDTreeNode* node = root;
if( !node )
CV_Error( CV_StsError, "The tree has not been trained yet" );
if ( ((CvCascadeBoostTrainData*)data)->featureEvaluator->getMaxCatCount() == 0 ) // ordered
{
while( node->left )
{
CvDTreeSplit* split = node->split;
float val = ((CvCascadeBoostTrainData*)data)->getVarValue( split->var_idx, sampleIdx );
node = val <= split->ord.c ? node->left : node->right;
}
}
else // categorical
{
while( node->left )
{
CvDTreeSplit* split = node->split;
int c = (int)((CvCascadeBoostTrainData*)data)->getVarValue( split->var_idx, sampleIdx );
node = CV_DTREE_CAT_DIR(c, split->subset) < 0 ? node->left : node->right;
}
}
return node;
}
void CvCascadeBoostTree::write( FileStorage &fs, const Mat& featureMap )
{
int maxCatCount = ((CvCascadeBoostTrainData*)data)->featureEvaluator->getMaxCatCount();
int subsetN = (maxCatCount + 31)/32;
queue<CvDTreeNode*> internalNodesQueue;
int size = (int)pow( 2.f, (float)ensemble->get_params().max_depth);
Ptr<float> leafVals = new float[size];
int leafValIdx = 0;
int internalNodeIdx = 1;
CvDTreeNode* tempNode;
CV_DbgAssert( root );
internalNodesQueue.push( root );
fs << "{";
fs << CC_INTERNAL_NODES << "[:";
while (!internalNodesQueue.empty())
{
tempNode = internalNodesQueue.front();
CV_Assert( tempNode->left );
if ( !tempNode->left->left && !tempNode->left->right) // left node is leaf
{
leafVals[-leafValIdx] = (float)tempNode->left->value;
fs << leafValIdx-- ;
}
else
{
internalNodesQueue.push( tempNode->left );
fs << internalNodeIdx++;
}
CV_Assert( tempNode->right );
if ( !tempNode->right->left && !tempNode->right->right) // right node is leaf
{
leafVals[-leafValIdx] = (float)tempNode->right->value;
fs << leafValIdx--;
}
else
{
internalNodesQueue.push( tempNode->right );
fs << internalNodeIdx++;
}
int fidx = tempNode->split->var_idx;
fidx = featureMap.empty() ? fidx : featureMap.at<int>(0, fidx);
fs << fidx;
if ( !maxCatCount )
fs << tempNode->split->ord.c;
else
for( int i = 0; i < subsetN; i++ )
fs << tempNode->split->subset[i];
internalNodesQueue.pop();
}
fs << "]"; // CC_INTERNAL_NODES
fs << CC_LEAF_VALUES << "[:";
for (int ni = 0; ni < -leafValIdx; ni++)
fs << leafVals[ni];
fs << "]"; // CC_LEAF_VALUES
fs << "}";
}
void CvCascadeBoostTree::read( const FileNode &node, CvBoost* _ensemble,
CvDTreeTrainData* _data )
{
int maxCatCount = ((CvCascadeBoostTrainData*)_data)->featureEvaluator->getMaxCatCount();
int subsetN = (maxCatCount + 31)/32;
int step = 3 + ( maxCatCount>0 ? subsetN : 1 );
queue<CvDTreeNode*> internalNodesQueue;
FileNodeIterator internalNodesIt, leafValsuesIt;
CvDTreeNode* prntNode, *cldNode;
clear();
data = _data;
ensemble = _ensemble;
pruned_tree_idx = 0;
// read tree nodes
FileNode rnode = node[CC_INTERNAL_NODES];
internalNodesIt = rnode.end();
leafValsuesIt = node[CC_LEAF_VALUES].end();
internalNodesIt--; leafValsuesIt--;
for( size_t i = 0; i < rnode.size()/step; i++ )
{
prntNode = data->new_node( 0, 0, 0, 0 );
if ( maxCatCount > 0 )
{
prntNode->split = data->new_split_cat( 0, 0 );
for( int j = subsetN-1; j>=0; j--)
{
*internalNodesIt >> prntNode->split->subset[j]; internalNodesIt--;
}
}
else
{
float split_value;
*internalNodesIt >> split_value; internalNodesIt--;