forked from opencv/opencv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathold_ml.hpp
2043 lines (1677 loc) · 73 KB
/
old_ml.hpp
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
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// Intel License Agreement
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of Intel Corporation may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
#ifndef OPENCV_OLD_ML_HPP
#define OPENCV_OLD_ML_HPP
#ifdef __cplusplus
# include "opencv2/core.hpp"
#endif
#include "opencv2/core/core_c.h"
#include <limits.h>
#ifdef __cplusplus
#include <map>
#include <iostream>
// Apple defines a check() macro somewhere in the debug headers
// that interferes with a method definition in this header
#undef check
/****************************************************************************************\
* Main struct definitions *
\****************************************************************************************/
/* log(2*PI) */
#define CV_LOG2PI (1.8378770664093454835606594728112)
/* columns of <trainData> matrix are training samples */
#define CV_COL_SAMPLE 0
/* rows of <trainData> matrix are training samples */
#define CV_ROW_SAMPLE 1
#define CV_IS_ROW_SAMPLE(flags) ((flags) & CV_ROW_SAMPLE)
struct CvVectors
{
int type;
int dims, count;
CvVectors* next;
union
{
uchar** ptr;
float** fl;
double** db;
} data;
};
#if 0
/* A structure, representing the lattice range of statmodel parameters.
It is used for optimizing statmodel parameters by cross-validation method.
The lattice is logarithmic, so <step> must be greater then 1. */
typedef struct CvParamLattice
{
double min_val;
double max_val;
double step;
}
CvParamLattice;
CV_INLINE CvParamLattice cvParamLattice( double min_val, double max_val,
double log_step )
{
CvParamLattice pl;
pl.min_val = MIN( min_val, max_val );
pl.max_val = MAX( min_val, max_val );
pl.step = MAX( log_step, 1. );
return pl;
}
CV_INLINE CvParamLattice cvDefaultParamLattice( void )
{
CvParamLattice pl = {0,0,0};
return pl;
}
#endif
/* Variable type */
#define CV_VAR_NUMERICAL 0
#define CV_VAR_ORDERED 0
#define CV_VAR_CATEGORICAL 1
#define CV_TYPE_NAME_ML_SVM "opencv-ml-svm"
#define CV_TYPE_NAME_ML_KNN "opencv-ml-knn"
#define CV_TYPE_NAME_ML_NBAYES "opencv-ml-bayesian"
#define CV_TYPE_NAME_ML_BOOSTING "opencv-ml-boost-tree"
#define CV_TYPE_NAME_ML_TREE "opencv-ml-tree"
#define CV_TYPE_NAME_ML_ANN_MLP "opencv-ml-ann-mlp"
#define CV_TYPE_NAME_ML_CNN "opencv-ml-cnn"
#define CV_TYPE_NAME_ML_RTREES "opencv-ml-random-trees"
#define CV_TYPE_NAME_ML_ERTREES "opencv-ml-extremely-randomized-trees"
#define CV_TYPE_NAME_ML_GBT "opencv-ml-gradient-boosting-trees"
#define CV_TRAIN_ERROR 0
#define CV_TEST_ERROR 1
class CvStatModel
{
public:
CvStatModel();
virtual ~CvStatModel();
virtual void clear();
CV_WRAP virtual void save( const char* filename, const char* name=0 ) const;
CV_WRAP virtual void load( const char* filename, const char* name=0 );
virtual void write( CvFileStorage* storage, const char* name ) const;
virtual void read( CvFileStorage* storage, CvFileNode* node );
protected:
const char* default_model_name;
};
/****************************************************************************************\
* Normal Bayes Classifier *
\****************************************************************************************/
/* The structure, representing the grid range of statmodel parameters.
It is used for optimizing statmodel accuracy by varying model parameters,
the accuracy estimate being computed by cross-validation.
The grid is logarithmic, so <step> must be greater then 1. */
class CvMLData;
struct CvParamGrid
{
// SVM params type
enum { SVM_C=0, SVM_GAMMA=1, SVM_P=2, SVM_NU=3, SVM_COEF=4, SVM_DEGREE=5 };
CvParamGrid()
{
min_val = max_val = step = 0;
}
CvParamGrid( double min_val, double max_val, double log_step );
//CvParamGrid( int param_id );
bool check() const;
CV_PROP_RW double min_val;
CV_PROP_RW double max_val;
CV_PROP_RW double step;
};
inline CvParamGrid::CvParamGrid( double _min_val, double _max_val, double _log_step )
{
min_val = _min_val;
max_val = _max_val;
step = _log_step;
}
class CvNormalBayesClassifier : public CvStatModel
{
public:
CV_WRAP CvNormalBayesClassifier();
virtual ~CvNormalBayesClassifier();
CvNormalBayesClassifier( const CvMat* trainData, const CvMat* responses,
const CvMat* varIdx=0, const CvMat* sampleIdx=0 );
virtual bool train( const CvMat* trainData, const CvMat* responses,
const CvMat* varIdx = 0, const CvMat* sampleIdx=0, bool update=false );
virtual float predict( const CvMat* samples, CV_OUT CvMat* results=0, CV_OUT CvMat* results_prob=0 ) const;
CV_WRAP virtual void clear();
CV_WRAP CvNormalBayesClassifier( const cv::Mat& trainData, const cv::Mat& responses,
const cv::Mat& varIdx=cv::Mat(), const cv::Mat& sampleIdx=cv::Mat() );
CV_WRAP virtual bool train( const cv::Mat& trainData, const cv::Mat& responses,
const cv::Mat& varIdx = cv::Mat(), const cv::Mat& sampleIdx=cv::Mat(),
bool update=false );
CV_WRAP virtual float predict( const cv::Mat& samples, CV_OUT cv::Mat* results=0, CV_OUT cv::Mat* results_prob=0 ) const;
virtual void write( CvFileStorage* storage, const char* name ) const;
virtual void read( CvFileStorage* storage, CvFileNode* node );
protected:
int var_count, var_all;
CvMat* var_idx;
CvMat* cls_labels;
CvMat** count;
CvMat** sum;
CvMat** productsum;
CvMat** avg;
CvMat** inv_eigen_values;
CvMat** cov_rotate_mats;
CvMat* c;
};
/****************************************************************************************\
* K-Nearest Neighbour Classifier *
\****************************************************************************************/
// k Nearest Neighbors
class CvKNearest : public CvStatModel
{
public:
CV_WRAP CvKNearest();
virtual ~CvKNearest();
CvKNearest( const CvMat* trainData, const CvMat* responses,
const CvMat* sampleIdx=0, bool isRegression=false, int max_k=32 );
virtual bool train( const CvMat* trainData, const CvMat* responses,
const CvMat* sampleIdx=0, bool is_regression=false,
int maxK=32, bool updateBase=false );
virtual float find_nearest( const CvMat* samples, int k, CV_OUT CvMat* results=0,
const float** neighbors=0, CV_OUT CvMat* neighborResponses=0, CV_OUT CvMat* dist=0 ) const;
CV_WRAP CvKNearest( const cv::Mat& trainData, const cv::Mat& responses,
const cv::Mat& sampleIdx=cv::Mat(), bool isRegression=false, int max_k=32 );
CV_WRAP virtual bool train( const cv::Mat& trainData, const cv::Mat& responses,
const cv::Mat& sampleIdx=cv::Mat(), bool isRegression=false,
int maxK=32, bool updateBase=false );
virtual float find_nearest( const cv::Mat& samples, int k, cv::Mat* results=0,
const float** neighbors=0, cv::Mat* neighborResponses=0,
cv::Mat* dist=0 ) const;
CV_WRAP virtual float find_nearest( const cv::Mat& samples, int k, CV_OUT cv::Mat& results,
CV_OUT cv::Mat& neighborResponses, CV_OUT cv::Mat& dists) const;
virtual void clear();
int get_max_k() const;
int get_var_count() const;
int get_sample_count() const;
bool is_regression() const;
virtual float write_results( int k, int k1, int start, int end,
const float* neighbor_responses, const float* dist, CvMat* _results,
CvMat* _neighbor_responses, CvMat* _dist, Cv32suf* sort_buf ) const;
virtual void find_neighbors_direct( const CvMat* _samples, int k, int start, int end,
float* neighbor_responses, const float** neighbors, float* dist ) const;
protected:
int max_k, var_count;
int total;
bool regression;
CvVectors* samples;
};
/****************************************************************************************\
* Support Vector Machines *
\****************************************************************************************/
// SVM training parameters
struct CvSVMParams
{
CvSVMParams();
CvSVMParams( int svm_type, int kernel_type,
double degree, double gamma, double coef0,
double Cvalue, double nu, double p,
CvMat* class_weights, CvTermCriteria term_crit );
CV_PROP_RW int svm_type;
CV_PROP_RW int kernel_type;
CV_PROP_RW double degree; // for poly
CV_PROP_RW double gamma; // for poly/rbf/sigmoid/chi2
CV_PROP_RW double coef0; // for poly/sigmoid
CV_PROP_RW double C; // for CV_SVM_C_SVC, CV_SVM_EPS_SVR and CV_SVM_NU_SVR
CV_PROP_RW double nu; // for CV_SVM_NU_SVC, CV_SVM_ONE_CLASS, and CV_SVM_NU_SVR
CV_PROP_RW double p; // for CV_SVM_EPS_SVR
CvMat* class_weights; // for CV_SVM_C_SVC
CV_PROP_RW CvTermCriteria term_crit; // termination criteria
};
struct CvSVMKernel
{
typedef void (CvSVMKernel::*Calc)( int vec_count, int vec_size, const float** vecs,
const float* another, float* results );
CvSVMKernel();
CvSVMKernel( const CvSVMParams* params, Calc _calc_func );
virtual bool create( const CvSVMParams* params, Calc _calc_func );
virtual ~CvSVMKernel();
virtual void clear();
virtual void calc( int vcount, int n, const float** vecs, const float* another, float* results );
const CvSVMParams* params;
Calc calc_func;
virtual void calc_non_rbf_base( int vec_count, int vec_size, const float** vecs,
const float* another, float* results,
double alpha, double beta );
virtual void calc_intersec( int vcount, int var_count, const float** vecs,
const float* another, float* results );
virtual void calc_chi2( int vec_count, int vec_size, const float** vecs,
const float* another, float* results );
virtual void calc_linear( int vec_count, int vec_size, const float** vecs,
const float* another, float* results );
virtual void calc_rbf( int vec_count, int vec_size, const float** vecs,
const float* another, float* results );
virtual void calc_poly( int vec_count, int vec_size, const float** vecs,
const float* another, float* results );
virtual void calc_sigmoid( int vec_count, int vec_size, const float** vecs,
const float* another, float* results );
};
struct CvSVMKernelRow
{
CvSVMKernelRow* prev;
CvSVMKernelRow* next;
float* data;
};
struct CvSVMSolutionInfo
{
double obj;
double rho;
double upper_bound_p;
double upper_bound_n;
double r; // for Solver_NU
};
class CvSVMSolver
{
public:
typedef bool (CvSVMSolver::*SelectWorkingSet)( int& i, int& j );
typedef float* (CvSVMSolver::*GetRow)( int i, float* row, float* dst, bool existed );
typedef void (CvSVMSolver::*CalcRho)( double& rho, double& r );
CvSVMSolver();
CvSVMSolver( int count, int var_count, const float** samples, schar* y,
int alpha_count, double* alpha, double Cp, double Cn,
CvMemStorage* storage, CvSVMKernel* kernel, GetRow get_row,
SelectWorkingSet select_working_set, CalcRho calc_rho );
virtual bool create( int count, int var_count, const float** samples, schar* y,
int alpha_count, double* alpha, double Cp, double Cn,
CvMemStorage* storage, CvSVMKernel* kernel, GetRow get_row,
SelectWorkingSet select_working_set, CalcRho calc_rho );
virtual ~CvSVMSolver();
virtual void clear();
virtual bool solve_generic( CvSVMSolutionInfo& si );
virtual bool solve_c_svc( int count, int var_count, const float** samples, schar* y,
double Cp, double Cn, CvMemStorage* storage,
CvSVMKernel* kernel, double* alpha, CvSVMSolutionInfo& si );
virtual bool solve_nu_svc( int count, int var_count, const float** samples, schar* y,
CvMemStorage* storage, CvSVMKernel* kernel,
double* alpha, CvSVMSolutionInfo& si );
virtual bool solve_one_class( int count, int var_count, const float** samples,
CvMemStorage* storage, CvSVMKernel* kernel,
double* alpha, CvSVMSolutionInfo& si );
virtual bool solve_eps_svr( int count, int var_count, const float** samples, const float* y,
CvMemStorage* storage, CvSVMKernel* kernel,
double* alpha, CvSVMSolutionInfo& si );
virtual bool solve_nu_svr( int count, int var_count, const float** samples, const float* y,
CvMemStorage* storage, CvSVMKernel* kernel,
double* alpha, CvSVMSolutionInfo& si );
virtual float* get_row_base( int i, bool* _existed );
virtual float* get_row( int i, float* dst );
int sample_count;
int var_count;
int cache_size;
int cache_line_size;
const float** samples;
const CvSVMParams* params;
CvMemStorage* storage;
CvSVMKernelRow lru_list;
CvSVMKernelRow* rows;
int alpha_count;
double* G;
double* alpha;
// -1 - lower bound, 0 - free, 1 - upper bound
schar* alpha_status;
schar* y;
double* b;
float* buf[2];
double eps;
int max_iter;
double C[2]; // C[0] == Cn, C[1] == Cp
CvSVMKernel* kernel;
SelectWorkingSet select_working_set_func;
CalcRho calc_rho_func;
GetRow get_row_func;
virtual bool select_working_set( int& i, int& j );
virtual bool select_working_set_nu_svm( int& i, int& j );
virtual void calc_rho( double& rho, double& r );
virtual void calc_rho_nu_svm( double& rho, double& r );
virtual float* get_row_svc( int i, float* row, float* dst, bool existed );
virtual float* get_row_one_class( int i, float* row, float* dst, bool existed );
virtual float* get_row_svr( int i, float* row, float* dst, bool existed );
};
struct CvSVMDecisionFunc
{
double rho;
int sv_count;
double* alpha;
int* sv_index;
};
// SVM model
class CvSVM : public CvStatModel
{
public:
// SVM type
enum { C_SVC=100, NU_SVC=101, ONE_CLASS=102, EPS_SVR=103, NU_SVR=104 };
// SVM kernel type
enum { LINEAR=0, POLY=1, RBF=2, SIGMOID=3, CHI2=4, INTER=5 };
// SVM params type
enum { C=0, GAMMA=1, P=2, NU=3, COEF=4, DEGREE=5 };
CV_WRAP CvSVM();
virtual ~CvSVM();
CvSVM( const CvMat* trainData, const CvMat* responses,
const CvMat* varIdx=0, const CvMat* sampleIdx=0,
CvSVMParams params=CvSVMParams() );
virtual bool train( const CvMat* trainData, const CvMat* responses,
const CvMat* varIdx=0, const CvMat* sampleIdx=0,
CvSVMParams params=CvSVMParams() );
virtual bool train_auto( const CvMat* trainData, const CvMat* responses,
const CvMat* varIdx, const CvMat* sampleIdx, CvSVMParams params,
int kfold = 10,
CvParamGrid Cgrid = get_default_grid(CvSVM::C),
CvParamGrid gammaGrid = get_default_grid(CvSVM::GAMMA),
CvParamGrid pGrid = get_default_grid(CvSVM::P),
CvParamGrid nuGrid = get_default_grid(CvSVM::NU),
CvParamGrid coeffGrid = get_default_grid(CvSVM::COEF),
CvParamGrid degreeGrid = get_default_grid(CvSVM::DEGREE),
bool balanced=false );
virtual float predict( const CvMat* sample, bool returnDFVal=false ) const;
virtual float predict( const CvMat* samples, CV_OUT CvMat* results, bool returnDFVal=false ) const;
CV_WRAP CvSVM( const cv::Mat& trainData, const cv::Mat& responses,
const cv::Mat& varIdx=cv::Mat(), const cv::Mat& sampleIdx=cv::Mat(),
CvSVMParams params=CvSVMParams() );
CV_WRAP virtual bool train( const cv::Mat& trainData, const cv::Mat& responses,
const cv::Mat& varIdx=cv::Mat(), const cv::Mat& sampleIdx=cv::Mat(),
CvSVMParams params=CvSVMParams() );
CV_WRAP virtual bool train_auto( const cv::Mat& trainData, const cv::Mat& responses,
const cv::Mat& varIdx, const cv::Mat& sampleIdx, CvSVMParams params,
int k_fold = 10,
CvParamGrid Cgrid = CvSVM::get_default_grid(CvSVM::C),
CvParamGrid gammaGrid = CvSVM::get_default_grid(CvSVM::GAMMA),
CvParamGrid pGrid = CvSVM::get_default_grid(CvSVM::P),
CvParamGrid nuGrid = CvSVM::get_default_grid(CvSVM::NU),
CvParamGrid coeffGrid = CvSVM::get_default_grid(CvSVM::COEF),
CvParamGrid degreeGrid = CvSVM::get_default_grid(CvSVM::DEGREE),
bool balanced=false);
CV_WRAP virtual float predict( const cv::Mat& sample, bool returnDFVal=false ) const;
CV_WRAP_AS(predict_all) virtual void predict( cv::InputArray samples, cv::OutputArray results ) const;
CV_WRAP virtual int get_support_vector_count() const;
virtual const float* get_support_vector(int i) const;
virtual CvSVMParams get_params() const { return params; }
CV_WRAP virtual void clear();
virtual const CvSVMDecisionFunc* get_decision_function() const { return decision_func; }
static CvParamGrid get_default_grid( int param_id );
virtual void write( CvFileStorage* storage, const char* name ) const;
virtual void read( CvFileStorage* storage, CvFileNode* node );
CV_WRAP int get_var_count() const { return var_idx ? var_idx->cols : var_all; }
protected:
virtual bool set_params( const CvSVMParams& params );
virtual bool train1( int sample_count, int var_count, const float** samples,
const void* responses, double Cp, double Cn,
CvMemStorage* _storage, double* alpha, double& rho );
virtual bool do_train( int svm_type, int sample_count, int var_count, const float** samples,
const CvMat* responses, CvMemStorage* _storage, double* alpha );
virtual void create_kernel();
virtual void create_solver();
virtual float predict( const float* row_sample, int row_len, bool returnDFVal=false ) const;
virtual void write_params( CvFileStorage* fs ) const;
virtual void read_params( CvFileStorage* fs, CvFileNode* node );
void optimize_linear_svm();
CvSVMParams params;
CvMat* class_labels;
int var_all;
float** sv;
int sv_total;
CvMat* var_idx;
CvMat* class_weights;
CvSVMDecisionFunc* decision_func;
CvMemStorage* storage;
CvSVMSolver* solver;
CvSVMKernel* kernel;
private:
CvSVM(const CvSVM&);
CvSVM& operator = (const CvSVM&);
};
/****************************************************************************************\
* Decision Tree *
\****************************************************************************************/\
struct CvPair16u32s
{
unsigned short* u;
int* i;
};
#define CV_DTREE_CAT_DIR(idx,subset) \
(2*((subset[(idx)>>5]&(1 << ((idx) & 31)))==0)-1)
struct CvDTreeSplit
{
int var_idx;
int condensed_idx;
int inversed;
float quality;
CvDTreeSplit* next;
union
{
int subset[2];
struct
{
float c;
int split_point;
}
ord;
};
};
struct CvDTreeNode
{
int class_idx;
int Tn;
double value;
CvDTreeNode* parent;
CvDTreeNode* left;
CvDTreeNode* right;
CvDTreeSplit* split;
int sample_count;
int depth;
int* num_valid;
int offset;
int buf_idx;
double maxlr;
// global pruning data
int complexity;
double alpha;
double node_risk, tree_risk, tree_error;
// cross-validation pruning data
int* cv_Tn;
double* cv_node_risk;
double* cv_node_error;
int get_num_valid(int vi) { return num_valid ? num_valid[vi] : sample_count; }
void set_num_valid(int vi, int n) { if( num_valid ) num_valid[vi] = n; }
};
struct CvDTreeParams
{
CV_PROP_RW int max_categories;
CV_PROP_RW int max_depth;
CV_PROP_RW int min_sample_count;
CV_PROP_RW int cv_folds;
CV_PROP_RW bool use_surrogates;
CV_PROP_RW bool use_1se_rule;
CV_PROP_RW bool truncate_pruned_tree;
CV_PROP_RW float regression_accuracy;
const float* priors;
CvDTreeParams();
CvDTreeParams( int max_depth, int min_sample_count,
float regression_accuracy, bool use_surrogates,
int max_categories, int cv_folds,
bool use_1se_rule, bool truncate_pruned_tree,
const float* priors );
};
struct CvDTreeTrainData
{
CvDTreeTrainData();
CvDTreeTrainData( const CvMat* trainData, int tflag,
const CvMat* responses, const CvMat* varIdx=0,
const CvMat* sampleIdx=0, const CvMat* varType=0,
const CvMat* missingDataMask=0,
const CvDTreeParams& params=CvDTreeParams(),
bool _shared=false, bool _add_labels=false );
virtual ~CvDTreeTrainData();
virtual void set_data( const CvMat* trainData, int tflag,
const CvMat* responses, const CvMat* varIdx=0,
const CvMat* sampleIdx=0, const CvMat* varType=0,
const CvMat* missingDataMask=0,
const CvDTreeParams& params=CvDTreeParams(),
bool _shared=false, bool _add_labels=false,
bool _update_data=false );
virtual void do_responses_copy();
virtual void get_vectors( const CvMat* _subsample_idx,
float* values, uchar* missing, float* responses, bool get_class_idx=false );
virtual CvDTreeNode* subsample_data( const CvMat* _subsample_idx );
virtual void write_params( CvFileStorage* fs ) const;
virtual void read_params( CvFileStorage* fs, CvFileNode* node );
// release all the data
virtual void clear();
int get_num_classes() const;
int get_var_type(int vi) const;
int get_work_var_count() const {return work_var_count;}
virtual const float* get_ord_responses( CvDTreeNode* n, float* values_buf, int* sample_indices_buf );
virtual const int* get_class_labels( CvDTreeNode* n, int* labels_buf );
virtual const int* get_cv_labels( CvDTreeNode* n, int* labels_buf );
virtual const int* get_sample_indices( CvDTreeNode* n, int* indices_buf );
virtual const int* get_cat_var_data( CvDTreeNode* n, int vi, int* cat_values_buf );
virtual void get_ord_var_data( CvDTreeNode* n, int vi, float* ord_values_buf, int* sorted_indices_buf,
const float** ord_values, const int** sorted_indices, int* sample_indices_buf );
virtual int get_child_buf_idx( CvDTreeNode* n );
////////////////////////////////////
virtual bool set_params( const CvDTreeParams& params );
virtual CvDTreeNode* new_node( CvDTreeNode* parent, int count,
int storage_idx, int offset );
virtual CvDTreeSplit* new_split_ord( int vi, float cmp_val,
int split_point, int inversed, float quality );
virtual CvDTreeSplit* new_split_cat( int vi, float quality );
virtual void free_node_data( CvDTreeNode* node );
virtual void free_train_data();
virtual void free_node( CvDTreeNode* node );
int sample_count, var_all, var_count, max_c_count;
int ord_var_count, cat_var_count, work_var_count;
bool have_labels, have_priors;
bool is_classifier;
int tflag;
const CvMat* train_data;
const CvMat* responses;
CvMat* responses_copy; // used in Boosting
int buf_count, buf_size; // buf_size is obsolete, please do not use it, use expression ((int64)buf->rows * (int64)buf->cols / buf_count) instead
bool shared;
int is_buf_16u;
CvMat* cat_count;
CvMat* cat_ofs;
CvMat* cat_map;
CvMat* counts;
CvMat* buf;
inline size_t get_length_subbuf() const
{
size_t res = (size_t)(work_var_count + 1) * (size_t)sample_count;
return res;
}
CvMat* direction;
CvMat* split_buf;
CvMat* var_idx;
CvMat* var_type; // i-th element =
// k<0 - ordered
// k>=0 - categorical, see k-th element of cat_* arrays
CvMat* priors;
CvMat* priors_mult;
CvDTreeParams params;
CvMemStorage* tree_storage;
CvMemStorage* temp_storage;
CvDTreeNode* data_root;
CvSet* node_heap;
CvSet* split_heap;
CvSet* cv_heap;
CvSet* nv_heap;
cv::RNG* rng;
};
class CvDTree;
class CvForestTree;
namespace cv
{
struct DTreeBestSplitFinder;
struct ForestTreeBestSplitFinder;
}
class CvDTree : public CvStatModel
{
public:
CV_WRAP CvDTree();
virtual ~CvDTree();
virtual bool train( const CvMat* trainData, int tflag,
const CvMat* responses, const CvMat* varIdx=0,
const CvMat* sampleIdx=0, const CvMat* varType=0,
const CvMat* missingDataMask=0,
CvDTreeParams params=CvDTreeParams() );
virtual bool train( CvMLData* trainData, CvDTreeParams params=CvDTreeParams() );
// type in {CV_TRAIN_ERROR, CV_TEST_ERROR}
virtual float calc_error( CvMLData* trainData, int type, std::vector<float> *resp = 0 );
virtual bool train( CvDTreeTrainData* trainData, const CvMat* subsampleIdx );
virtual CvDTreeNode* predict( const CvMat* sample, const CvMat* missingDataMask=0,
bool preprocessedInput=false ) const;
CV_WRAP virtual bool train( const cv::Mat& trainData, int tflag,
const cv::Mat& responses, const cv::Mat& varIdx=cv::Mat(),
const cv::Mat& sampleIdx=cv::Mat(), const cv::Mat& varType=cv::Mat(),
const cv::Mat& missingDataMask=cv::Mat(),
CvDTreeParams params=CvDTreeParams() );
CV_WRAP virtual CvDTreeNode* predict( const cv::Mat& sample, const cv::Mat& missingDataMask=cv::Mat(),
bool preprocessedInput=false ) const;
CV_WRAP virtual cv::Mat getVarImportance();
virtual const CvMat* get_var_importance();
CV_WRAP virtual void clear();
virtual void read( CvFileStorage* fs, CvFileNode* node );
virtual void write( CvFileStorage* fs, const char* name ) const;
// special read & write methods for trees in the tree ensembles
virtual void read( CvFileStorage* fs, CvFileNode* node,
CvDTreeTrainData* data );
virtual void write( CvFileStorage* fs ) const;
const CvDTreeNode* get_root() const;
int get_pruned_tree_idx() const;
CvDTreeTrainData* get_data();
protected:
friend struct cv::DTreeBestSplitFinder;
virtual bool do_train( const CvMat* _subsample_idx );
virtual void try_split_node( CvDTreeNode* n );
virtual void split_node_data( CvDTreeNode* n );
virtual CvDTreeSplit* find_best_split( CvDTreeNode* n );
virtual CvDTreeSplit* find_split_ord_class( CvDTreeNode* n, int vi,
float init_quality = 0, CvDTreeSplit* _split = 0, uchar* ext_buf = 0 );
virtual CvDTreeSplit* find_split_cat_class( CvDTreeNode* n, int vi,
float init_quality = 0, CvDTreeSplit* _split = 0, uchar* ext_buf = 0 );
virtual CvDTreeSplit* find_split_ord_reg( CvDTreeNode* n, int vi,
float init_quality = 0, CvDTreeSplit* _split = 0, uchar* ext_buf = 0 );
virtual CvDTreeSplit* find_split_cat_reg( CvDTreeNode* n, int vi,
float init_quality = 0, CvDTreeSplit* _split = 0, uchar* ext_buf = 0 );
virtual CvDTreeSplit* find_surrogate_split_ord( CvDTreeNode* n, int vi, uchar* ext_buf = 0 );
virtual CvDTreeSplit* find_surrogate_split_cat( CvDTreeNode* n, int vi, uchar* ext_buf = 0 );
virtual double calc_node_dir( CvDTreeNode* node );
virtual void complete_node_dir( CvDTreeNode* node );
virtual void cluster_categories( const int* vectors, int vector_count,
int var_count, int* sums, int k, int* cluster_labels );
virtual void calc_node_value( CvDTreeNode* node );
virtual void prune_cv();
virtual double update_tree_rnc( int T, int fold );
virtual int cut_tree( int T, int fold, double min_alpha );
virtual void free_prune_data(bool cut_tree);
virtual void free_tree();
virtual void write_node( CvFileStorage* fs, CvDTreeNode* node ) const;
virtual void write_split( CvFileStorage* fs, CvDTreeSplit* split ) const;
virtual CvDTreeNode* read_node( CvFileStorage* fs, CvFileNode* node, CvDTreeNode* parent );
virtual CvDTreeSplit* read_split( CvFileStorage* fs, CvFileNode* node );
virtual void write_tree_nodes( CvFileStorage* fs ) const;
virtual void read_tree_nodes( CvFileStorage* fs, CvFileNode* node );
CvDTreeNode* root;
CvMat* var_importance;
CvDTreeTrainData* data;
CvMat train_data_hdr, responses_hdr;
cv::Mat train_data_mat, responses_mat;
public:
int pruned_tree_idx;
};
/****************************************************************************************\
* Random Trees Classifier *
\****************************************************************************************/
class CvRTrees;
class CvForestTree: public CvDTree
{
public:
CvForestTree();
virtual ~CvForestTree();
virtual bool train( CvDTreeTrainData* trainData, const CvMat* _subsample_idx, CvRTrees* forest );
virtual int get_var_count() const {return data ? data->var_count : 0;}
virtual void read( CvFileStorage* fs, CvFileNode* node, CvRTrees* forest, CvDTreeTrainData* _data );
/* dummy methods to avoid warnings: BEGIN */
virtual bool train( const CvMat* trainData, int tflag,
const CvMat* responses, const CvMat* varIdx=0,
const CvMat* sampleIdx=0, const CvMat* varType=0,
const CvMat* missingDataMask=0,
CvDTreeParams params=CvDTreeParams() );
virtual bool train( CvDTreeTrainData* trainData, const CvMat* _subsample_idx );
virtual void read( CvFileStorage* fs, CvFileNode* node );
virtual void read( CvFileStorage* fs, CvFileNode* node,
CvDTreeTrainData* data );
/* dummy methods to avoid warnings: END */
protected:
friend struct cv::ForestTreeBestSplitFinder;
virtual CvDTreeSplit* find_best_split( CvDTreeNode* n );
CvRTrees* forest;
};
struct CvRTParams : public CvDTreeParams
{
//Parameters for the forest
CV_PROP_RW bool calc_var_importance; // true <=> RF processes variable importance
CV_PROP_RW int nactive_vars;
CV_PROP_RW CvTermCriteria term_crit;
CvRTParams();
CvRTParams( int max_depth, int min_sample_count,
float regression_accuracy, bool use_surrogates,
int max_categories, const float* priors, bool calc_var_importance,
int nactive_vars, int max_num_of_trees_in_the_forest,
float forest_accuracy, int termcrit_type );
};
class CvRTrees : public CvStatModel
{
public:
CV_WRAP CvRTrees();
virtual ~CvRTrees();
virtual bool train( const CvMat* trainData, int tflag,
const CvMat* responses, const CvMat* varIdx=0,
const CvMat* sampleIdx=0, const CvMat* varType=0,
const CvMat* missingDataMask=0,
CvRTParams params=CvRTParams() );
virtual bool train( CvMLData* data, CvRTParams params=CvRTParams() );
virtual float predict( const CvMat* sample, const CvMat* missing = 0 ) const;
virtual float predict_prob( const CvMat* sample, const CvMat* missing = 0 ) const;
CV_WRAP virtual bool train( const cv::Mat& trainData, int tflag,
const cv::Mat& responses, const cv::Mat& varIdx=cv::Mat(),
const cv::Mat& sampleIdx=cv::Mat(), const cv::Mat& varType=cv::Mat(),
const cv::Mat& missingDataMask=cv::Mat(),
CvRTParams params=CvRTParams() );
CV_WRAP virtual float predict( const cv::Mat& sample, const cv::Mat& missing = cv::Mat() ) const;
CV_WRAP virtual float predict_prob( const cv::Mat& sample, const cv::Mat& missing = cv::Mat() ) const;
CV_WRAP virtual cv::Mat getVarImportance();
CV_WRAP virtual void clear();
virtual const CvMat* get_var_importance();
virtual float get_proximity( const CvMat* sample1, const CvMat* sample2,
const CvMat* missing1 = 0, const CvMat* missing2 = 0 ) const;
virtual float calc_error( CvMLData* data, int type , std::vector<float>* resp = 0 ); // type in {CV_TRAIN_ERROR, CV_TEST_ERROR}
virtual float get_train_error();
virtual void read( CvFileStorage* fs, CvFileNode* node );
virtual void write( CvFileStorage* fs, const char* name ) const;
CvMat* get_active_var_mask();
CvRNG* get_rng();
int get_tree_count() const;
CvForestTree* get_tree(int i) const;
protected:
virtual cv::String getName() const;
virtual bool grow_forest( const CvTermCriteria term_crit );
// array of the trees of the forest
CvForestTree** trees;
CvDTreeTrainData* data;
CvMat train_data_hdr, responses_hdr;
cv::Mat train_data_mat, responses_mat;
int ntrees;
int nclasses;
double oob_error;
CvMat* var_importance;
int nsamples;
cv::RNG* rng;
CvMat* active_var_mask;
};
/****************************************************************************************\
* Extremely randomized trees Classifier *
\****************************************************************************************/
struct CvERTreeTrainData : public CvDTreeTrainData
{
virtual void set_data( const CvMat* trainData, int tflag,
const CvMat* responses, const CvMat* varIdx=0,
const CvMat* sampleIdx=0, const CvMat* varType=0,
const CvMat* missingDataMask=0,
const CvDTreeParams& params=CvDTreeParams(),
bool _shared=false, bool _add_labels=false,
bool _update_data=false );
virtual void get_ord_var_data( CvDTreeNode* n, int vi, float* ord_values_buf, int* missing_buf,
const float** ord_values, const int** missing, int* sample_buf = 0 );
virtual const int* get_sample_indices( CvDTreeNode* n, int* indices_buf );
virtual const int* get_cv_labels( CvDTreeNode* n, int* labels_buf );
virtual const int* get_cat_var_data( CvDTreeNode* n, int vi, int* cat_values_buf );
virtual void get_vectors( const CvMat* _subsample_idx, float* values, uchar* missing,
float* responses, bool get_class_idx=false );
virtual CvDTreeNode* subsample_data( const CvMat* _subsample_idx );