1
/*M///////////////////////////////////////////////////////////////////////////////////////
3
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
5
// By downloading, copying, installing or using the software you agree to this license.
6
// If you do not agree to this license, do not download, install,
7
// copy or use the software.
11
// For Open Source Computer Vision Library
13
// Copyright (C) 2000, Intel Corporation, all rights reserved.
14
// Copyright (C) 2014, Itseez Inc, all rights reserved.
15
// Third party copyrights are property of their respective owners.
17
// Redistribution and use in source and binary forms, with or without modification,
18
// are permitted provided that the following conditions are met:
20
// * Redistribution's of source code must retain the above copyright notice,
21
// this list of conditions and the following disclaimer.
23
// * Redistribution's in binary form must reproduce the above copyright notice,
24
// this list of conditions and the following disclaimer in the documentation
25
// and/or other materials provided with the distribution.
27
// * The name of the copyright holders may not be used to endorse or promote products
28
// derived from this software without specific prior written permission.
30
// This software is provided by the copyright holders and contributors "as is" and
31
// any express or implied warranties, including, but not limited to, the implied
32
// warranties of merchantability and fitness for a particular purpose are disclaimed.
33
// In no event shall the Intel Corporation or contributors be liable for any direct,
34
// indirect, incidental, special, exemplary, or consequential damages
35
// (including, but not limited to, procurement of substitute goods or services;
36
// loss of use, data, or profits; or business interruption) however caused
37
// and on any theory of liability, whether in contract, strict liability,
38
// or tort (including negligence or otherwise) arising in any way out of
39
// the use of this software, even if advised of the possibility of such damage.
43
#include "precomp.hpp"
51
TreeParams::TreeParams()
55
regressionAccuracy = 0.01f;
56
useSurrogates = false;
60
truncatePrunedTree = true;
64
TreeParams::TreeParams(int _maxDepth, int _minSampleCount,
65
double _regressionAccuracy, bool _useSurrogates,
66
int _maxCategories, int _CVFolds,
67
bool _use1SERule, bool _truncatePrunedTree,
71
minSampleCount = _minSampleCount;
72
regressionAccuracy = (float)_regressionAccuracy;
73
useSurrogates = _useSurrogates;
74
maxCategories = _maxCategories;
76
use1SERule = _use1SERule;
77
truncatePrunedTree = _truncatePrunedTree;
85
parent = left = right = split = defaultDir = -1;
88
DTrees::Split::Split()
99
DTreesImpl::WorkData::WorkData(const Ptr<TrainData>& _data)
102
vector<int> subsampleIdx;
103
Mat sidx0 = _data->getTrainSampleIdx();
107
std::sort(sidx.begin(), sidx.end());
111
int n = _data->getNSamples();
112
setRangeVector(sidx, n);
118
DTreesImpl::DTreesImpl() {}
119
DTreesImpl::~DTreesImpl() {}
120
void DTreesImpl::clear()
134
_isClassifier = false;
137
void DTreesImpl::startTraining( const Ptr<TrainData>& data, int )
140
w = makePtr<WorkData>(data);
142
Mat vtype = data->getVarType();
143
vtype.copyTo(varType);
145
data->getCatOfs().copyTo(catOfs);
146
data->getCatMap().copyTo(catMap);
147
data->getDefaultSubstValues().copyTo(missingSubst);
149
int nallvars = data->getNAllVars();
151
Mat vidx0 = data->getVarIdx();
153
vidx0.copyTo(varIdx);
155
setRangeVector(varIdx, nallvars);
159
w->maxSubsetSize = 0;
161
int i, nvars = (int)varIdx.size();
162
for( i = 0; i < nvars; i++ )
163
w->maxSubsetSize = std::max(w->maxSubsetSize, getCatCount(varIdx[i]));
165
w->maxSubsetSize = std::max((w->maxSubsetSize + 31)/32, 1);
167
data->getSampleWeights().copyTo(w->sample_weights);
169
_isClassifier = data->getResponseType() == VAR_CATEGORICAL;
173
data->getNormCatResponses().copyTo(w->cat_responses);
174
data->getClassLabels().copyTo(classLabels);
175
int nclasses = (int)classLabels.size();
177
Mat class_weights = params.priors;
178
if( !class_weights.empty() )
180
if( class_weights.type() != CV_64F || !class_weights.isContinuous() )
183
class_weights.convertTo(temp, CV_64F);
184
class_weights = temp;
186
CV_Assert( class_weights.checkVector(1, CV_64F) == nclasses );
188
int nsamples = (int)w->cat_responses.size();
189
const double* cw = class_weights.ptr<double>();
190
CV_Assert( (int)w->sample_weights.size() == nsamples );
192
for( i = 0; i < nsamples; i++ )
194
int ci = w->cat_responses[i];
195
CV_Assert( 0 <= ci && ci < nclasses );
196
w->sample_weights[i] *= cw[ci];
201
data->getResponses().copyTo(w->ord_responses);
205
void DTreesImpl::initCompVarIdx()
207
int nallvars = (int)varType.size();
208
compVarIdx.assign(nallvars, -1);
209
int i, nvars = (int)varIdx.size(), prevIdx = -1;
210
for( i = 0; i < nvars; i++ )
213
CV_Assert( 0 <= vi && vi < nallvars && vi > prevIdx );
219
void DTreesImpl::endTraining()
224
bool DTreesImpl::train( const Ptr<TrainData>& trainData, int flags )
226
startTraining(trainData, flags);
227
bool ok = addTree( w->sidx ) >= 0;
233
const vector<int>& DTreesImpl::getActiveVars()
238
int DTreesImpl::addTree(const vector<int>& sidx )
240
size_t n = (params.getMaxDepth() > 0 ? (1 << params.getMaxDepth()) : 1024) + w->wnodes.size();
242
w->wnodes.reserve(n);
243
w->wsplits.reserve(n);
244
w->wsubsets.reserve(n*w->maxSubsetSize);
249
int cv_n = params.getCVFolds();
253
w->cv_Tn.resize(n*cv_n);
254
w->cv_node_error.resize(n*cv_n);
255
w->cv_node_risk.resize(n*cv_n);
258
// build the tree recursively
259
int w_root = addNodeAndTrySplit(-1, sidx);
260
int maxdepth = INT_MAX;//pruneCV(root);
262
int w_nidx = w_root, pidx = -1, depth = 0;
263
int root = (int)nodes.size();
267
const WNode& wnode = w->wnodes[w_nidx];
270
node.classIdx = wnode.class_idx;
271
node.value = wnode.value;
272
node.defaultDir = wnode.defaultDir;
274
int wsplit_idx = wnode.split;
275
if( wsplit_idx >= 0 )
277
const WSplit& wsplit = w->wsplits[wsplit_idx];
280
split.quality = wsplit.quality;
281
split.inversed = wsplit.inversed;
282
split.varIdx = wsplit.varIdx;
283
split.subsetOfs = -1;
284
if( wsplit.subsetOfs >= 0 )
286
int ssize = getSubsetSize(split.varIdx);
287
split.subsetOfs = (int)subsets.size();
288
subsets.resize(split.subsetOfs + ssize);
289
// This check verifies that subsets index is in the correct range
290
// as in case ssize == 0 no real resize performed.
291
// Thus memory kept safe.
292
// Also this skips useless memcpy call when size parameter is zero
295
memcpy(&subsets[split.subsetOfs], &w->wsubsets[wsplit.subsetOfs], ssize*sizeof(int));
298
node.split = (int)splits.size();
299
splits.push_back(split);
301
int nidx = (int)nodes.size();
302
nodes.push_back(node);
305
int w_pidx = w->wnodes[w_nidx].parent;
306
if( w->wnodes[w_pidx].left == w_nidx )
308
nodes[pidx].left = nidx;
312
CV_Assert(w->wnodes[w_pidx].right == w_nidx);
313
nodes[pidx].right = nidx;
317
if( wnode.left >= 0 && depth+1 < maxdepth )
325
int w_pidx = wnode.parent;
326
while( w_pidx >= 0 && w->wnodes[w_pidx].right == w_nidx )
329
w_pidx = w->wnodes[w_pidx].parent;
331
pidx = nodes[pidx].parent;
338
w_nidx = w->wnodes[w_pidx].right;
339
CV_Assert( w_nidx >= 0 );
342
roots.push_back(root);
346
void DTreesImpl::setDParams(const TreeParams& _params)
351
int DTreesImpl::addNodeAndTrySplit( int parent, const vector<int>& sidx )
353
w->wnodes.push_back(WNode());
354
int nidx = (int)(w->wnodes.size() - 1);
355
WNode& node = w->wnodes.back();
357
node.parent = parent;
358
node.depth = parent >= 0 ? w->wnodes[parent].depth + 1 : 0;
359
int nfolds = params.getCVFolds();
363
w->cv_Tn.resize((nidx+1)*nfolds);
364
w->cv_node_error.resize((nidx+1)*nfolds);
365
w->cv_node_risk.resize((nidx+1)*nfolds);
368
int i, n = node.sample_count = (int)sidx.size();
369
bool can_split = true;
370
vector<int> sleft, sright;
372
calcValue( nidx, sidx );
374
if( n <= params.getMinSampleCount() || node.depth >= params.getMaxDepth() )
376
else if( _isClassifier )
378
const int* responses = &w->cat_responses[0];
379
const int* s = &sidx[0];
380
int first = responses[s[0]];
381
for( i = 1; i < n; i++ )
382
if( responses[s[i]] != first )
389
if( sqrt(node.node_risk) < params.getRegressionAccuracy() )
394
node.split = findBestSplit( sidx );
396
//printf("depth=%d, nidx=%d, parent=%d, n=%d, %s, value=%.1f, risk=%.1f\n", node.depth, nidx, node.parent, n, (node.split < 0 ? "leaf" : varType[w->wsplits[node.split].varIdx] == VAR_CATEGORICAL ? "cat" : "ord"), node.value, node.node_risk);
398
if( node.split >= 0 )
400
node.defaultDir = calcDir( node.split, sidx, sleft, sright );
401
if( params.useSurrogates )
402
CV_Error( CV_StsNotImplemented, "surrogate splits are not implemented yet");
404
int left = addNodeAndTrySplit( nidx, sleft );
405
int right = addNodeAndTrySplit( nidx, sright );
406
w->wnodes[nidx].left = left;
407
w->wnodes[nidx].right = right;
408
CV_Assert( w->wnodes[nidx].left > 0 && w->wnodes[nidx].right > 0 );
414
int DTreesImpl::findBestSplit( const vector<int>& _sidx )
416
const vector<int>& activeVars = getActiveVars();
418
int vi_, nv = (int)activeVars.size();
419
AutoBuffer<int> buf(w->maxSubsetSize*2);
420
int *subset = buf, *best_subset = subset + w->maxSubsetSize;
421
WSplit split, best_split;
422
best_split.quality = 0.;
424
for( vi_ = 0; vi_ < nv; vi_++ )
426
int vi = activeVars[vi_];
427
if( varType[vi] == VAR_CATEGORICAL )
430
split = findSplitCatClass(vi, _sidx, 0, subset);
432
split = findSplitCatReg(vi, _sidx, 0, subset);
437
split = findSplitOrdClass(vi, _sidx, 0);
439
split = findSplitOrdReg(vi, _sidx, 0);
441
if( split.quality > best_split.quality )
444
std::swap(subset, best_subset);
448
if( best_split.quality > 0 )
450
int best_vi = best_split.varIdx;
451
CV_Assert( compVarIdx[best_split.varIdx] >= 0 && best_vi >= 0 );
452
int i, prevsz = (int)w->wsubsets.size(), ssize = getSubsetSize(best_vi);
453
w->wsubsets.resize(prevsz + ssize);
454
for( i = 0; i < ssize; i++ )
455
w->wsubsets[prevsz + i] = best_subset[i];
456
best_split.subsetOfs = prevsz;
457
w->wsplits.push_back(best_split);
458
splitidx = (int)(w->wsplits.size()-1);
464
void DTreesImpl::calcValue( int nidx, const vector<int>& _sidx )
466
WNode* node = &w->wnodes[nidx];
467
int i, j, k, n = (int)_sidx.size(), cv_n = params.getCVFolds();
468
int m = (int)classLabels.size();
470
cv::AutoBuffer<double> buf(std::max(m, 3)*(cv_n+1));
474
size_t sz = w->cv_Tn.size();
475
w->cv_Tn.resize(sz + cv_n);
476
w->cv_node_risk.resize(sz + cv_n);
477
w->cv_node_error.resize(sz + cv_n);
482
// in case of classification tree:
483
// * node value is the label of the class that has the largest weight in the node.
484
// * node risk is the weighted number of misclassified samples,
485
// * j-th cross-validation fold value and risk are calculated as above,
486
// but using the samples with cv_labels(*)!=j.
487
// * j-th cross-validation fold error is calculated as the weighted number of
488
// misclassified samples with cv_labels(*)==j.
490
// compute the number of instances of each class
491
double* cls_count = buf;
492
double* cv_cls_count = cls_count + m;
494
double max_val = -1, total_weight = 0;
497
for( k = 0; k < m; k++ )
502
for( i = 0; i < n; i++ )
505
cls_count[w->cat_responses[si]] += w->sample_weights[si];
510
for( j = 0; j < cv_n; j++ )
511
for( k = 0; k < m; k++ )
512
cv_cls_count[j*m + k] = 0;
514
for( i = 0; i < n; i++ )
517
j = w->cv_labels[si]; k = w->cat_responses[si];
518
cv_cls_count[j*m + k] += w->sample_weights[si];
521
for( j = 0; j < cv_n; j++ )
522
for( k = 0; k < m; k++ )
523
cls_count[k] += cv_cls_count[j*m + k];
526
for( k = 0; k < m; k++ )
528
double val = cls_count[k];
537
node->class_idx = max_k;
538
node->value = classLabels[max_k];
539
node->node_risk = total_weight - max_val;
541
for( j = 0; j < cv_n; j++ )
543
double sum_k = 0, sum = 0, max_val_k = 0;
544
max_val = -1; max_k = -1;
546
for( k = 0; k < m; k++ )
548
double val_k = cv_cls_count[j*m + k];
549
double val = cls_count[k] - val_k;
560
w->cv_Tn[nidx*cv_n + j] = INT_MAX;
561
w->cv_node_risk[nidx*cv_n + j] = sum - max_val;
562
w->cv_node_error[nidx*cv_n + j] = sum_k - max_val_k;
567
// in case of regression tree:
568
// * node value is 1/n*sum_i(Y_i), where Y_i is i-th response,
569
// n is the number of samples in the node.
570
// * node risk is the sum of squared errors: sum_i((Y_i - <node_value>)^2)
571
// * j-th cross-validation fold value and risk are calculated as above,
572
// but using the samples with cv_labels(*)!=j.
573
// * j-th cross-validation fold error is calculated
574
// using samples with cv_labels(*)==j as the test subset:
575
// error_j = sum_(i,cv_labels(i)==j)((Y_i - <node_value_j>)^2),
576
// where node_value_j is the node value calculated
577
// as described in the previous bullet, and summation is done
578
// over the samples with cv_labels(*)==j.
579
double sum = 0, sum2 = 0, sumw = 0;
583
for( i = 0; i < n; i++ )
586
double wval = w->sample_weights[si];
587
double t = w->ord_responses[si];
595
double *cv_sum = buf, *cv_sum2 = cv_sum + cv_n;
596
double* cv_count = (double*)(cv_sum2 + cv_n);
598
for( j = 0; j < cv_n; j++ )
600
cv_sum[j] = cv_sum2[j] = 0.;
604
for( i = 0; i < n; i++ )
607
j = w->cv_labels[si];
608
double wval = w->sample_weights[si];
609
double t = w->ord_responses[si];
611
cv_sum2[j] += t*t*wval;
615
for( j = 0; j < cv_n; j++ )
622
for( j = 0; j < cv_n; j++ )
624
double s = sum - cv_sum[j], si = sum - s;
625
double s2 = sum2 - cv_sum2[j], s2i = sum2 - s2;
626
double c = cv_count[j], ci = sumw - c;
627
double r = si/std::max(ci, DBL_EPSILON);
628
w->cv_node_risk[nidx*cv_n + j] = s2i - r*r*ci;
629
w->cv_node_error[nidx*cv_n + j] = s2 - 2*r*s + c*r*r;
630
w->cv_Tn[nidx*cv_n + j] = INT_MAX;
634
node->node_risk = sum2 - (sum/sumw)*sum;
635
node->value = sum/sumw;
639
DTreesImpl::WSplit DTreesImpl::findSplitOrdClass( int vi, const vector<int>& _sidx, double initQuality )
641
const double epsilon = FLT_EPSILON*2;
642
int n = (int)_sidx.size();
643
int m = (int)classLabels.size();
645
cv::AutoBuffer<uchar> buf(n*(sizeof(float) + sizeof(int)) + m*2*sizeof(double));
646
const int* sidx = &_sidx[0];
647
const int* responses = &w->cat_responses[0];
648
const double* weights = &w->sample_weights[0];
649
double* lcw = (double*)(uchar*)buf;
650
double* rcw = lcw + m;
651
float* values = (float*)(rcw + m);
652
int* sorted_idx = (int*)(values + n);
654
double best_val = initQuality;
656
for( i = 0; i < m; i++ )
657
lcw[i] = rcw[i] = 0.;
659
w->data->getValues( vi, _sidx, values );
661
for( i = 0; i < n; i++ )
665
rcw[responses[si]] += weights[si];
668
std::sort(sorted_idx, sorted_idx + n, cmp_lt_idx<float>(values));
670
double L = 0, R = 0, lsum2 = 0, rsum2 = 0;
671
for( i = 0; i < m; i++ )
673
double wval = rcw[i];
678
for( i = 0; i < n - 1; i++ )
680
int curr = sorted_idx[i];
681
int next = sorted_idx[i+1];
683
double wval = weights[si], w2 = wval*wval;
684
L += wval; R -= wval;
685
int idx = responses[si];
686
double lv = lcw[idx], rv = rcw[idx];
687
lsum2 += 2*lv*wval + w2;
688
rsum2 -= 2*rv*wval - w2;
689
lcw[idx] = lv + wval; rcw[idx] = rv - wval;
691
if( values[curr] + epsilon < values[next] )
693
double val = (lsum2*R + rsum2*L)/(L*R);
706
split.c = (values[sorted_idx[best_i]] + values[sorted_idx[best_i+1]])*0.5f;
707
split.inversed = false;
708
split.quality = (float)best_val;
713
// simple k-means, slightly modified to take into account the "weight" (L1-norm) of each vector.
714
void DTreesImpl::clusterCategories( const double* vectors, int n, int m, double* csums, int k, int* labels )
716
int iters = 0, max_iters = 100;
718
cv::AutoBuffer<double> buf(n + k);
719
double *v_weights = buf, *c_weights = buf + n;
720
bool modified = true;
723
// assign labels randomly
724
for( i = 0; i < n; i++ )
727
const double* v = vectors + i*m;
728
labels[i] = i < k ? i : r.uniform(0, k);
730
// compute weight of each vector
731
for( j = 0; j < m; j++ )
733
v_weights[i] = sum ? 1./sum : 0.;
736
for( i = 0; i < n; i++ )
738
int i1 = r.uniform(0, n);
739
int i2 = r.uniform(0, n);
740
std::swap( labels[i1], labels[i2] );
743
for( iters = 0; iters <= max_iters; iters++ )
746
for( i = 0; i < k; i++ )
748
for( j = 0; j < m; j++ )
752
for( i = 0; i < n; i++ )
754
const double* v = vectors + i*m;
755
double* s = csums + labels[i]*m;
756
for( j = 0; j < m; j++ )
760
// exit the loop here, when we have up-to-date csums
761
if( iters == max_iters || !modified )
766
// calculate weight of each cluster
767
for( i = 0; i < k; i++ )
769
const double* s = csums + i*m;
771
for( j = 0; j < m; j++ )
773
c_weights[i] = sum ? 1./sum : 0;
776
// now for each vector determine the closest cluster
777
for( i = 0; i < n; i++ )
779
const double* v = vectors + i*m;
780
double alpha = v_weights[i];
781
double min_dist2 = DBL_MAX;
784
for( idx = 0; idx < k; idx++ )
786
const double* s = csums + idx*m;
787
double dist2 = 0., beta = c_weights[idx];
788
for( j = 0; j < m; j++ )
790
double t = v[j]*alpha - s[j]*beta;
793
if( min_dist2 > dist2 )
800
if( min_idx != labels[i] )
807
DTreesImpl::WSplit DTreesImpl::findSplitCatClass( int vi, const vector<int>& _sidx,
808
double initQuality, int* subset )
810
int _mi = getCatCount(vi), mi = _mi;
811
int n = (int)_sidx.size();
812
int m = (int)classLabels.size();
814
int base_size = m*(3 + mi) + mi + 1;
815
if( m > 2 && mi > params.getMaxCategories() )
816
base_size += m*std::min(params.getMaxCategories(), n) + mi;
819
AutoBuffer<double> buf(base_size + n);
821
double* lc = (double*)buf;
823
double* _cjk = rc + m*2, *cjk = _cjk;
824
double* c_weights = cjk + m*mi;
826
int* labels = (int*)(buf + base_size);
827
w->data->getNormCatValues(vi, _sidx, labels);
828
const int* responses = &w->cat_responses[0];
829
const double* weights = &w->sample_weights[0];
831
int* cluster_labels = 0;
832
double** dbl_ptr = 0;
833
int i, j, k, si, idx;
835
double best_val = initQuality;
836
int prevcode = 0, best_subset = -1, subset_i, subset_n, subtract = 0;
838
// init array of counters:
839
// c_{jk} - number of samples that have vi-th input variable = j and response = k.
840
for( j = -1; j < mi; j++ )
841
for( k = 0; k < m; k++ )
844
for( i = 0; i < n; i++ )
849
cjk[j*m + k] += weights[si];
854
if( mi > params.getMaxCategories() )
856
mi = std::min(params.getMaxCategories(), n);
857
cjk = c_weights + _mi;
858
cluster_labels = (int*)(cjk + m*mi);
859
clusterCategories( _cjk, _mi, m, cjk, mi, cluster_labels );
867
dbl_ptr = (double**)(c_weights + _mi);
868
for( j = 0; j < mi; j++ )
869
dbl_ptr[j] = cjk + j*2 + 1;
870
std::sort(dbl_ptr, dbl_ptr + mi, cmp_lt_ptr<double>());
875
for( k = 0; k < m; k++ )
878
for( j = 0; j < mi; j++ )
885
for( j = 0; j < mi; j++ )
888
for( k = 0; k < m; k++ )
894
for( ; subset_i < subset_n; subset_i++ )
896
double lsum2 = 0, rsum2 = 0;
899
idx = (int)(dbl_ptr[subset_i] - cjk)/2;
902
int graycode = (subset_i>>1)^subset_i;
903
int diff = graycode ^ prevcode;
905
// determine index of the changed bit.
907
idx = diff >= (1 << 16) ? 16 : 0;
908
u.f = (float)(((diff >> 16) | diff) & 65535);
909
idx += (u.i >> 23) - 127;
910
subtract = graycode < prevcode;
914
double* crow = cjk + idx*m;
915
double weight = c_weights[idx];
916
if( weight < FLT_EPSILON )
921
for( k = 0; k < m; k++ )
924
double lval = lc[k] + t;
925
double rval = rc[k] - t;
928
lc[k] = lval; rc[k] = rval;
935
for( k = 0; k < m; k++ )
938
double lval = lc[k] - t;
939
double rval = rc[k] + t;
942
lc[k] = lval; rc[k] = rval;
948
if( L > FLT_EPSILON && R > FLT_EPSILON )
950
double val = (lsum2*R + rsum2*L)/(L*R);
954
best_subset = subset_i;
960
if( best_subset >= 0 )
963
split.quality = (float)best_val;
964
memset( subset, 0, getSubsetSize(vi) * sizeof(int) );
967
for( i = 0; i <= best_subset; i++ )
969
idx = (int)(dbl_ptr[i] - cjk) >> 1;
970
subset[idx >> 5] |= 1 << (idx & 31);
975
for( i = 0; i < _mi; i++ )
977
idx = cluster_labels ? cluster_labels[i] : i;
978
if( best_subset & (1 << idx) )
979
subset[i >> 5] |= 1 << (i & 31);
986
DTreesImpl::WSplit DTreesImpl::findSplitOrdReg( int vi, const vector<int>& _sidx, double initQuality )
988
const float epsilon = FLT_EPSILON*2;
989
const double* weights = &w->sample_weights[0];
990
int n = (int)_sidx.size();
992
AutoBuffer<uchar> buf(n*(sizeof(int) + sizeof(float)));
994
float* values = (float*)(uchar*)buf;
995
int* sorted_idx = (int*)(values + n);
996
w->data->getValues(vi, _sidx, values);
997
const double* responses = &w->ord_responses[0];
999
int i, si, best_i = -1;
1000
double L = 0, R = 0;
1001
double best_val = initQuality, lsum = 0, rsum = 0;
1003
for( i = 0; i < n; i++ )
1008
rsum += weights[si]*responses[si];
1011
std::sort(sorted_idx, sorted_idx + n, cmp_lt_idx<float>(values));
1013
// find the optimal split
1014
for( i = 0; i < n - 1; i++ )
1016
int curr = sorted_idx[i];
1017
int next = sorted_idx[i+1];
1019
double wval = weights[si];
1020
double t = responses[si]*wval;
1021
L += wval; R -= wval;
1022
lsum += t; rsum -= t;
1024
if( values[curr] + epsilon < values[next] )
1026
double val = (lsum*lsum*R + rsum*rsum*L)/(L*R);
1027
if( best_val < val )
1039
split.c = (values[sorted_idx[best_i]] + values[sorted_idx[best_i+1]])*0.5f;
1040
split.inversed = false;
1041
split.quality = (float)best_val;
1046
DTreesImpl::WSplit DTreesImpl::findSplitCatReg( int vi, const vector<int>& _sidx,
1047
double initQuality, int* subset )
1049
const double* weights = &w->sample_weights[0];
1050
const double* responses = &w->ord_responses[0];
1051
int n = (int)_sidx.size();
1052
int mi = getCatCount(vi);
1054
AutoBuffer<double> buf(3*mi + 3 + n);
1055
double* sum = (double*)buf + 1;
1056
double* counts = sum + mi + 1;
1057
double** sum_ptr = (double**)(counts + mi);
1058
int* cat_labels = (int*)(sum_ptr + mi);
1060
w->data->getNormCatValues(vi, _sidx, cat_labels);
1062
double L = 0, R = 0, best_val = initQuality, lsum = 0, rsum = 0;
1063
int i, si, best_subset = -1, subset_i;
1065
for( i = -1; i < mi; i++ )
1066
sum[i] = counts[i] = 0;
1068
// calculate sum response and weight of each category of the input var
1069
for( i = 0; i < n; i++ )
1071
int idx = cat_labels[i];
1073
double wval = weights[si];
1074
sum[idx] += responses[si]*wval;
1075
counts[idx] += wval;
1078
// calculate average response in each category
1079
for( i = 0; i < mi; i++ )
1083
sum[i] = fabs(counts[i]) > DBL_EPSILON ? sum[i]/counts[i] : 0;
1084
sum_ptr[i] = sum + i;
1087
std::sort(sum_ptr, sum_ptr + mi, cmp_lt_ptr<double>());
1089
// revert back to unnormalized sums
1090
// (there should be a very little loss in accuracy)
1091
for( i = 0; i < mi; i++ )
1092
sum[i] *= counts[i];
1094
for( subset_i = 0; subset_i < mi-1; subset_i++ )
1096
int idx = (int)(sum_ptr[subset_i] - sum);
1097
double ni = counts[idx];
1099
if( ni > FLT_EPSILON )
1101
double s = sum[idx];
1105
if( L > FLT_EPSILON && R > FLT_EPSILON )
1107
double val = (lsum*lsum*R + rsum*rsum*L)/(L*R);
1108
if( best_val < val )
1111
best_subset = subset_i;
1118
if( best_subset >= 0 )
1121
split.quality = (float)best_val;
1122
memset( subset, 0, getSubsetSize(vi) * sizeof(int));
1123
for( i = 0; i <= best_subset; i++ )
1125
int idx = (int)(sum_ptr[i] - sum);
1126
subset[idx >> 5] |= 1 << (idx & 31);
1132
int DTreesImpl::calcDir( int splitidx, const vector<int>& _sidx,
1133
vector<int>& _sleft, vector<int>& _sright )
1135
WSplit split = w->wsplits[splitidx];
1136
int i, si, n = (int)_sidx.size(), vi = split.varIdx;
1142
AutoBuffer<float> buf(n);
1143
int mi = getCatCount(vi);
1144
double wleft = 0, wright = 0;
1145
const double* weights = &w->sample_weights[0];
1147
if( mi <= 0 ) // split on an ordered variable
1150
float* values = buf;
1151
w->data->getValues(vi, _sidx, values);
1153
for( i = 0; i < n; i++ )
1156
if( values[i] <= c )
1158
_sleft.push_back(si);
1159
wleft += weights[si];
1163
_sright.push_back(si);
1164
wright += weights[si];
1170
const int* subset = &w->wsubsets[split.subsetOfs];
1171
int* cat_labels = (int*)(float*)buf;
1172
w->data->getNormCatValues(vi, _sidx, cat_labels);
1174
for( i = 0; i < n; i++ )
1177
unsigned u = cat_labels[i];
1178
if( CV_DTREE_CAT_DIR(u, subset) < 0 )
1180
_sleft.push_back(si);
1181
wleft += weights[si];
1185
_sright.push_back(si);
1186
wright += weights[si];
1190
CV_Assert( (int)_sleft.size() < n && (int)_sright.size() < n );
1191
return wleft > wright ? -1 : 1;
1194
int DTreesImpl::pruneCV( int root )
1198
// 1. build tree sequence for each cv fold, calculate error_{Tj,beta_k}.
1199
// 2. choose the best tree index (if need, apply 1SE rule).
1200
// 3. store the best index and cut the branches.
1202
int ti, tree_count = 0, j, cv_n = params.getCVFolds(), n = w->wnodes[root].sample_count;
1203
// currently, 1SE for regression is not implemented
1204
bool use_1se = params.use1SERule != 0 && _isClassifier;
1205
double min_err = 0, min_err_se = 0;
1208
// build the main tree sequence, calculate alpha's
1211
double min_alpha = updateTreeRNC(root, tree_count, -1);
1212
if( cutTree(root, tree_count, -1, min_alpha) )
1215
ab.push_back(min_alpha);
1218
if( tree_count > 0 )
1222
for( ti = 1; ti < tree_count-1; ti++ )
1223
ab[ti] = std::sqrt(ab[ti]*ab[ti+1]);
1224
ab[tree_count-1] = DBL_MAX*0.5;
1226
Mat err_jk(cv_n, tree_count, CV_64F);
1228
for( j = 0; j < cv_n; j++ )
1231
for( ; tj < tree_count; tj++ )
1233
double min_alpha = updateTreeRNC(root, tj, j);
1234
if( cutTree(root, tj, j, min_alpha) )
1235
min_alpha = DBL_MAX;
1237
for( ; tk < tree_count; tk++ )
1239
if( ab[tk] > min_alpha )
1241
err_jk.at<double>(j, tk) = w->wnodes[root].tree_error;
1246
for( ti = 0; ti < tree_count; ti++ )
1249
for( j = 0; j < cv_n; j++ )
1250
sum_err += err_jk.at<double>(j, ti);
1251
if( ti == 0 || sum_err < min_err )
1256
min_err_se = sqrt( sum_err*(n - sum_err) );
1258
else if( sum_err < min_err + min_err_se )
1266
double DTreesImpl::updateTreeRNC( int root, double T, int fold )
1268
int nidx = root, pidx = -1, cv_n = params.getCVFolds();
1269
double min_alpha = DBL_MAX;
1273
WNode *node = 0, *parent = 0;
1277
node = &w->wnodes[nidx];
1278
double t = fold >= 0 ? w->cv_Tn[nidx*cv_n + fold] : node->Tn;
1279
if( t <= T || node->left < 0 )
1281
node->complexity = 1;
1282
node->tree_risk = node->node_risk;
1283
node->tree_error = 0.;
1286
node->tree_risk = w->cv_node_risk[nidx*cv_n + fold];
1287
node->tree_error = w->cv_node_error[nidx*cv_n + fold];
1294
for( pidx = node->parent; pidx >= 0 && w->wnodes[pidx].right == nidx;
1295
nidx = pidx, pidx = w->wnodes[pidx].parent )
1297
node = &w->wnodes[nidx];
1298
parent = &w->wnodes[pidx];
1299
parent->complexity += node->complexity;
1300
parent->tree_risk += node->tree_risk;
1301
parent->tree_error += node->tree_error;
1303
parent->alpha = ((fold >= 0 ? w->cv_node_risk[pidx*cv_n + fold] : parent->node_risk)
1304
- parent->tree_risk)/(parent->complexity - 1);
1305
min_alpha = std::min( min_alpha, parent->alpha );
1311
node = &w->wnodes[nidx];
1312
parent = &w->wnodes[pidx];
1313
parent->complexity = node->complexity;
1314
parent->tree_risk = node->tree_risk;
1315
parent->tree_error = node->tree_error;
1316
nidx = parent->right;
1322
bool DTreesImpl::cutTree( int root, double T, int fold, double min_alpha )
1324
int cv_n = params.getCVFolds(), nidx = root, pidx = -1;
1325
WNode* node = &w->wnodes[root];
1326
if( node->left < 0 )
1333
node = &w->wnodes[nidx];
1334
double t = fold >= 0 ? w->cv_Tn[nidx*cv_n + fold] : node->Tn;
1335
if( t <= T || node->left < 0 )
1337
if( node->alpha <= min_alpha + FLT_EPSILON )
1340
w->cv_Tn[nidx*cv_n + fold] = T;
1350
for( pidx = node->parent; pidx >= 0 && w->wnodes[pidx].right == nidx;
1351
nidx = pidx, pidx = w->wnodes[pidx].parent )
1357
nidx = w->wnodes[pidx].right;
1363
float DTreesImpl::predictTrees( const Range& range, const Mat& sample, int flags ) const
1365
CV_Assert( sample.type() == CV_32F );
1367
int predictType = flags & PREDICT_MASK;
1368
int nvars = (int)varIdx.size();
1370
nvars = (int)varType.size();
1371
int i, ncats = (int)catOfs.size(), nclasses = (int)classLabels.size();
1372
int catbufsize = ncats > 0 ? nvars : 0;
1373
AutoBuffer<int> buf(nclasses + catbufsize + 1);
1375
int* catbuf = votes + nclasses;
1376
const int* cvidx = (flags & (COMPRESSED_INPUT|PREPROCESSED_INPUT)) == 0 && !varIdx.empty() ? &compVarIdx[0] : 0;
1377
const uchar* vtype = &varType[0];
1378
const Vec2i* cofs = !catOfs.empty() ? &catOfs[0] : 0;
1379
const int* cmap = !catMap.empty() ? &catMap[0] : 0;
1380
const float* psample = sample.ptr<float>();
1381
const float* missingSubstPtr = !missingSubst.empty() ? &missingSubst[0] : 0;
1382
size_t sstep = sample.isContinuous() ? 1 : sample.step/sizeof(float);
1384
int lastClassIdx = -1;
1385
const float MISSED_VAL = TrainData::missingValue();
1387
for( i = 0; i < catbufsize; i++ )
1390
if( predictType == PREDICT_AUTO )
1392
predictType = !_isClassifier || (classLabels.size() == 2 && (flags & RAW_OUTPUT) != 0) ?
1393
PREDICT_SUM : PREDICT_MAX_VOTE;
1396
if( predictType == PREDICT_MAX_VOTE )
1398
for( i = 0; i < nclasses; i++ )
1402
for( int ridx = range.start; ridx < range.end; ridx++ )
1404
int nidx = roots[ridx], prev = nidx, c = 0;
1409
const Node& node = nodes[nidx];
1410
if( node.split < 0 )
1412
const Split& split = splits[node.split];
1413
int vi = split.varIdx;
1414
int ci = cvidx ? cvidx[vi] : vi;
1415
float val = psample[ci*sstep];
1416
if( val == MISSED_VAL )
1418
if( !missingSubstPtr )
1420
nidx = node.defaultDir < 0 ? node.left : node.right;
1423
val = missingSubstPtr[vi];
1426
if( vtype[vi] == VAR_ORDERED )
1427
nidx = val <= split.c ? node.left : node.right;
1430
if( flags & PREPROCESSED_INPUT )
1437
int a = c = cofs[vi][0];
1438
int b = cofs[vi][1];
1440
int ival = cvRound(val);
1442
CV_Error( CV_StsBadArg,
1443
"one of input categorical variable is not an integer" );
1448
if( ival < cmap[c] )
1450
else if( ival > cmap[c] )
1456
CV_Assert( c >= 0 && ival == cmap[c] );
1461
const int* subset = &subsets[split.subsetOfs];
1463
nidx = CV_DTREE_CAT_DIR(u, subset) < 0 ? node.left : node.right;
1468
if( predictType == PREDICT_SUM )
1469
sum += nodes[prev].value;
1472
lastClassIdx = nodes[prev].classIdx;
1473
votes[lastClassIdx]++;
1477
if( predictType == PREDICT_MAX_VOTE )
1479
int best_idx = lastClassIdx;
1480
if( range.end - range.start > 1 )
1483
for( i = 1; i < nclasses; i++ )
1484
if( votes[best_idx] < votes[i] )
1487
sum = (flags & RAW_OUTPUT) ? (float)best_idx : classLabels[best_idx];
1494
float DTreesImpl::predict( InputArray _samples, OutputArray _results, int flags ) const
1496
CV_Assert( !roots.empty() );
1497
Mat samples = _samples.getMat(), results;
1498
int i, nsamples = samples.rows;
1500
bool needresults = _results.needed();
1502
bool iscls = isClassifier();
1503
float scale = !iscls ? 1.f/(int)roots.size() : 1.f;
1505
if( iscls && (flags & PREDICT_MASK) == PREDICT_MAX_VOTE )
1510
_results.create(nsamples, 1, rtype);
1511
results = _results.getMat();
1514
nsamples = std::min(nsamples, 1);
1516
for( i = 0; i < nsamples; i++ )
1518
float val = predictTrees( Range(0, (int)roots.size()), samples.row(i), flags )*scale;
1521
if( rtype == CV_32F )
1522
results.at<float>(i) = val;
1524
results.at<int>(i) = cvRound(val);
1532
void DTreesImpl::writeTrainingParams(FileStorage& fs) const
1534
fs << "use_surrogates" << (params.useSurrogates ? 1 : 0);
1535
fs << "max_categories" << params.getMaxCategories();
1536
fs << "regression_accuracy" << params.getRegressionAccuracy();
1538
fs << "max_depth" << params.getMaxDepth();
1539
fs << "min_sample_count" << params.getMinSampleCount();
1540
fs << "cross_validation_folds" << params.getCVFolds();
1542
if( params.getCVFolds() > 1 )
1543
fs << "use_1se_rule" << (params.use1SERule ? 1 : 0);
1545
if( !params.priors.empty() )
1546
fs << "priors" << params.priors;
1549
void DTreesImpl::writeParams(FileStorage& fs) const
1551
fs << "is_classifier" << isClassifier();
1552
fs << "var_all" << (int)varType.size();
1553
fs << "var_count" << getVarCount();
1555
int ord_var_count = 0, cat_var_count = 0;
1556
int i, n = (int)varType.size();
1557
for( i = 0; i < n; i++ )
1558
if( varType[i] == VAR_ORDERED )
1562
fs << "ord_var_count" << ord_var_count;
1563
fs << "cat_var_count" << cat_var_count;
1565
fs << "training_params" << "{";
1566
writeTrainingParams(fs);
1570
if( !varIdx.empty() )
1572
fs << "global_var_idx" << 1;
1573
fs << "var_idx" << varIdx;
1576
fs << "var_type" << varType;
1578
if( !catOfs.empty() )
1579
fs << "cat_ofs" << catOfs;
1580
if( !catMap.empty() )
1581
fs << "cat_map" << catMap;
1582
if( !classLabels.empty() )
1583
fs << "class_labels" << classLabels;
1584
if( !missingSubst.empty() )
1585
fs << "missing_subst" << missingSubst;
1588
void DTreesImpl::writeSplit( FileStorage& fs, int splitidx ) const
1590
const Split& split = splits[splitidx];
1594
int vi = split.varIdx;
1596
fs << "quality" << split.quality;
1598
if( varType[vi] == VAR_CATEGORICAL ) // split on a categorical var
1600
int i, n = getCatCount(vi), to_right = 0;
1601
const int* subset = &subsets[split.subsetOfs];
1602
for( i = 0; i < n; i++ )
1603
to_right += CV_DTREE_CAT_DIR(i, subset) > 0;
1605
// ad-hoc rule when to use inverse categorical split notation
1606
// to achieve more compact and clear representation
1607
int default_dir = to_right <= 1 || to_right <= std::min(3, n/2) || to_right <= n/3 ? -1 : 1;
1609
fs << (default_dir*(split.inversed ? -1 : 1) > 0 ? "in" : "not_in") << "[:";
1611
for( i = 0; i < n; i++ )
1613
int dir = CV_DTREE_CAT_DIR(i, subset);
1614
if( dir*default_dir < 0 )
1621
fs << (!split.inversed ? "le" : "gt") << split.c;
1626
void DTreesImpl::writeNode( FileStorage& fs, int nidx, int depth ) const
1628
const Node& node = nodes[nidx];
1630
fs << "depth" << depth;
1631
fs << "value" << node.value;
1634
fs << "norm_class_idx" << node.classIdx;
1636
if( node.split >= 0 )
1638
fs << "splits" << "[";
1640
for( int splitidx = node.split; splitidx >= 0; splitidx = splits[splitidx].next )
1641
writeSplit( fs, splitidx );
1649
void DTreesImpl::writeTree( FileStorage& fs, int root ) const
1651
fs << "nodes" << "[";
1653
int nidx = root, pidx = 0, depth = 0;
1654
const Node *node = 0;
1656
// traverse the tree and save all the nodes in depth-first order
1661
writeNode( fs, nidx, depth );
1662
node = &nodes[nidx];
1663
if( node->left < 0 )
1669
for( pidx = node->parent; pidx >= 0 && nodes[pidx].right == nidx;
1670
nidx = pidx, pidx = nodes[pidx].parent )
1676
nidx = nodes[pidx].right;
1682
void DTreesImpl::write( FileStorage& fs ) const
1685
writeTree(fs, roots[0]);
1688
void DTreesImpl::readParams( const FileNode& fn )
1690
_isClassifier = (int)fn["is_classifier"] != 0;
1691
/*int var_all = (int)fn["var_all"];
1692
int var_count = (int)fn["var_count"];
1693
int cat_var_count = (int)fn["cat_var_count"];
1694
int ord_var_count = (int)fn["ord_var_count"];*/
1696
FileNode tparams_node = fn["training_params"];
1698
TreeParams params0 = TreeParams();
1700
if( !tparams_node.empty() ) // training parameters are not necessary
1702
params0.useSurrogates = (int)tparams_node["use_surrogates"] != 0;
1703
params0.setMaxCategories((int)(tparams_node["max_categories"].empty() ? 16 : tparams_node["max_categories"]));
1704
params0.setRegressionAccuracy((float)tparams_node["regression_accuracy"]);
1705
params0.setMaxDepth((int)tparams_node["max_depth"]);
1706
params0.setMinSampleCount((int)tparams_node["min_sample_count"]);
1707
params0.setCVFolds((int)tparams_node["cross_validation_folds"]);
1709
if( params0.getCVFolds() > 1 )
1711
params.use1SERule = (int)tparams_node["use_1se_rule"] != 0;
1714
tparams_node["priors"] >> params0.priors;
1717
readVectorOrMat(fn["var_idx"], varIdx);
1718
fn["var_type"] >> varType;
1721
fn["format"] >> format;
1722
bool isLegacy = format < 3;
1724
int varAll = (int)fn["var_all"];
1725
if (isLegacy && (int)varType.size() <= varAll)
1727
std::vector<uchar> extendedTypes(varAll + 1, 0);
1730
if (!varIdx.empty())
1732
n = (int)varIdx.size();
1735
int var = varIdx[i];
1736
extendedTypes[var] = varType[i];
1741
n = (int)varType.size();
1744
extendedTypes[i] = varType[i];
1747
extendedTypes[varAll] = (uchar)(_isClassifier ? VAR_CATEGORICAL : VAR_ORDERED);
1748
extendedTypes.swap(varType);
1751
readVectorOrMat(fn["cat_map"], catMap);
1755
// generating "catOfs" from "cat_count"
1757
classLabels.clear();
1758
std::vector<int> counts;
1759
readVectorOrMat(fn["cat_count"], counts);
1760
unsigned int i = 0, j = 0, curShift = 0, size = (int)varType.size() - 1;
1761
for (; i < size; ++i)
1763
Vec2i newOffsets(0, 0);
1764
if (varType[i] == VAR_CATEGORICAL) // only categorical vars are represented in catMap
1766
newOffsets[0] = curShift;
1767
curShift += counts[j];
1768
newOffsets[1] = curShift;
1771
catOfs.push_back(newOffsets);
1773
// other elements in "catMap" are "classLabels"
1774
if (curShift < catMap.size())
1776
classLabels.insert(classLabels.end(), catMap.begin() + curShift, catMap.end());
1777
catMap.erase(catMap.begin() + curShift, catMap.end());
1782
fn["cat_ofs"] >> catOfs;
1783
fn["missing_subst"] >> missingSubst;
1784
fn["class_labels"] >> classLabels;
1787
// init var mapping for node reading (var indexes or varIdx indexes)
1788
bool globalVarIdx = false;
1789
fn["global_var_idx"] >> globalVarIdx;
1790
if (globalVarIdx || varIdx.empty())
1791
setRangeVector(varMapping, (int)varType.size());
1793
varMapping = varIdx;
1796
setDParams(params0);
1799
int DTreesImpl::readSplit( const FileNode& fn )
1803
int vi = (int)fn["var"];
1804
CV_Assert( 0 <= vi && vi <= (int)varType.size() );
1805
vi = varMapping[vi]; // convert to varIdx if needed
1808
if( varType[vi] == VAR_CATEGORICAL ) // split on categorical var
1810
int i, val, ssize = getSubsetSize(vi);
1811
split.subsetOfs = (int)subsets.size();
1812
for( i = 0; i < ssize; i++ )
1813
subsets.push_back(0);
1814
int* subset = &subsets[split.subsetOfs];
1815
FileNode fns = fn["in"];
1819
split.inversed = true;
1825
subset[val >> 5] |= 1 << (val & 31);
1829
FileNodeIterator it = fns.begin();
1830
int n = (int)fns.size();
1831
for( i = 0; i < n; i++, ++it )
1834
subset[val >> 5] |= 1 << (val & 31);
1838
// for categorical splits we do not use inversed splits,
1839
// instead we inverse the variable set in the split
1840
if( split.inversed )
1842
for( i = 0; i < ssize; i++ )
1844
split.inversed = false;
1849
FileNode cmpNode = fn["le"];
1850
if( cmpNode.empty() )
1853
split.inversed = true;
1855
split.c = (float)cmpNode;
1858
split.quality = (float)fn["quality"];
1859
splits.push_back(split);
1861
return (int)(splits.size() - 1);
1864
int DTreesImpl::readNode( const FileNode& fn )
1867
node.value = (double)fn["value"];
1870
node.classIdx = (int)fn["norm_class_idx"];
1872
FileNode sfn = fn["splits"];
1875
int i, n = (int)sfn.size(), prevsplit = -1;
1876
FileNodeIterator it = sfn.begin();
1878
for( i = 0; i < n; i++, ++it )
1880
int splitidx = readSplit(*it);
1884
node.split = splitidx;
1886
splits[prevsplit].next = splitidx;
1887
prevsplit = splitidx;
1890
nodes.push_back(node);
1891
return (int)(nodes.size() - 1);
1894
int DTreesImpl::readTree( const FileNode& fn )
1896
int i, n = (int)fn.size(), root = -1, pidx = -1;
1897
FileNodeIterator it = fn.begin();
1899
for( i = 0; i < n; i++, ++it )
1901
int nidx = readNode(*it);
1904
Node& node = nodes[nidx];
1910
Node& parent = nodes[pidx];
1911
if( parent.left < 0 )
1914
parent.right = nidx;
1916
if( node.split >= 0 )
1920
while( pidx >= 0 && nodes[pidx].right >= 0 )
1921
pidx = nodes[pidx].parent;
1924
roots.push_back(root);
1928
void DTreesImpl::read( const FileNode& fn )
1933
FileNode fnodes = fn["nodes"];
1934
CV_Assert( !fnodes.empty() );
1938
Ptr<DTrees> DTrees::create()
1940
return makePtr<DTreesImpl>();