rtrees.cpp 28.5 KB
Newer Older
wester committed
1 2 3 4 5 6 7 8 9
/*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.
//
//
wester committed
10
//                        Intel License Agreement
wester committed
11 12 13 14 15 16 17 18 19 20 21 22 23 24
//
// 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.
//
wester committed
25
//   * The name of Intel Corporation may not be used to endorse or promote products
wester committed
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
//     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*/

#include "precomp.hpp"
a  
Kai Westerkamp committed
42

wester committed
43 44 45 46
CvForestTree::CvForestTree()
{
    forest = NULL;
}
wester committed
47

wester committed
48 49 50 51 52 53 54 55 56 57

CvForestTree::~CvForestTree()
{
    clear();
}


bool CvForestTree::train( CvDTreeTrainData* _data,
                          const CvMat* _subsample_idx,
                          CvRTrees* _forest )
wester committed
58
{
wester committed
59 60 61 62 63 64
    clear();
    forest = _forest;

    data = _data;
    data->shared = true;
    return do_train(_subsample_idx);
wester committed
65 66
}

wester committed
67 68 69 70

bool
CvForestTree::train( const CvMat*, int, const CvMat*, const CvMat*,
                    const CvMat*, const CvMat*, const CvMat*, CvDTreeParams )
wester committed
71
{
wester committed
72 73
    assert(0);
    return false;
wester committed
74 75 76
}


wester committed
77 78
bool
CvForestTree::train( CvDTreeTrainData*, const CvMat* )
wester committed
79
{
wester committed
80 81 82 83 84 85 86 87 88 89 90 91 92 93
    assert(0);
    return false;
}



namespace cv
{

ForestTreeBestSplitFinder::ForestTreeBestSplitFinder( CvForestTree* _tree, CvDTreeNode* _node ) :
    DTreeBestSplitFinder(_tree, _node) {}

ForestTreeBestSplitFinder::ForestTreeBestSplitFinder( const ForestTreeBestSplitFinder& finder, Split spl ) :
    DTreeBestSplitFinder( finder, spl ) {}
wester committed
94

wester committed
95 96 97 98 99 100 101 102 103 104 105
void ForestTreeBestSplitFinder::operator()(const BlockedRange& range)
{
    int vi, vi1 = range.begin(), vi2 = range.end();
    int n = node->sample_count;
    CvDTreeTrainData* data = tree->get_data();
    AutoBuffer<uchar> inn_buf(2*n*(sizeof(int) + sizeof(float)));

    CvForestTree* ftree = (CvForestTree*)tree;
    const CvMat* active_var_mask = ftree->forest->get_active_var_mask();

    for( vi = vi1; vi < vi2; vi++ )
wester committed
106
    {
wester committed
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
        CvDTreeSplit *res;
        int ci = data->var_type->data.i[vi];
        if( node->num_valid[vi] <= 1
            || (active_var_mask && !active_var_mask->data.ptr[vi]) )
            continue;

        if( data->is_classifier )
        {
            if( ci >= 0 )
                res = ftree->find_split_cat_class( node, vi, bestSplit->quality, split, (uchar*)inn_buf );
            else
                res = ftree->find_split_ord_class( node, vi, bestSplit->quality, split, (uchar*)inn_buf );
        }
        else
        {
            if( ci >= 0 )
                res = ftree->find_split_cat_reg( node, vi, bestSplit->quality, split, (uchar*)inn_buf );
            else
                res = ftree->find_split_ord_reg( node, vi, bestSplit->quality, split, (uchar*)inn_buf );
        }

        if( res && bestSplit->quality < split->quality )
                memcpy( (CvDTreeSplit*)bestSplit, (CvDTreeSplit*)split, splitSize );
wester committed
130
    }
wester committed
131 132
}
}
wester committed
133

wester committed
134 135 136 137
CvDTreeSplit* CvForestTree::find_best_split( CvDTreeNode* node )
{
    CvMat* active_var_mask = 0;
    if( forest )
wester committed
138
    {
wester committed
139 140 141 142 143 144 145 146 147
        int var_count;
        CvRNG* rng = forest->get_rng();

        active_var_mask = forest->get_active_var_mask();
        var_count = active_var_mask->cols;

        CV_Assert( var_count == data->var_count );

        for( int vi = 0; vi < var_count; vi++ )
wester committed
148
        {
wester committed
149 150 151 152 153
            uchar temp;
            int i1 = cvRandInt(rng) % var_count;
            int i2 = cvRandInt(rng) % var_count;
            CV_SWAP( active_var_mask->data.ptr[i1],
                active_var_mask->data.ptr[i2], temp );
wester committed
154 155 156
        }
    }

wester committed
157 158 159 160 161 162
    cv::ForestTreeBestSplitFinder finder( this, node );

    cv::parallel_reduce(cv::BlockedRange(0, data->var_count), finder);

    CvDTreeSplit *bestSplit = 0;
    if( finder.bestSplit->quality > 0 )
wester committed
163
    {
wester committed
164 165
        bestSplit = data->new_split_cat( 0, -1.0f );
        memcpy( bestSplit, finder.bestSplit, finder.splitSize );
wester committed
166 167
    }

wester committed
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
    return bestSplit;
}

void CvForestTree::read( CvFileStorage* fs, CvFileNode* fnode, CvRTrees* _forest, CvDTreeTrainData* _data )
{
    CvDTree::read( fs, fnode, _data );
    forest = _forest;
}


void CvForestTree::read( CvFileStorage*, CvFileNode* )
{
    assert(0);
}

void CvForestTree::read( CvFileStorage* _fs, CvFileNode* _node,
                         CvDTreeTrainData* _data )
{
    CvDTree::read( _fs, _node, _data );
}


//////////////////////////////////////////////////////////////////////////////////////////
//                                  Random trees                                        //
//////////////////////////////////////////////////////////////////////////////////////////
CvRTParams::CvRTParams() : CvDTreeParams( 5, 10, 0, false, 10, 0, false, false, 0 ),
    calc_var_importance(false), nactive_vars(0)
{
    term_crit = cvTermCriteria( CV_TERMCRIT_ITER+CV_TERMCRIT_EPS, 50, 0.1 );
}

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 ) :
    CvDTreeParams( _max_depth, _min_sample_count, _regression_accuracy,
                   _use_surrogates, _max_categories, 0,
                   false, false, _priors ),
    calc_var_importance(_calc_var_importance),
    nactive_vars(_nactive_vars)
{
    term_crit = cvTermCriteria(termcrit_type,
        max_num_of_trees_in_the_forest, forest_accuracy);
}

CvRTrees::CvRTrees()
{
    nclasses         = 0;
    oob_error        = 0;
    ntrees           = 0;
    trees            = NULL;
    data             = NULL;
    active_var_mask  = NULL;
    var_importance   = NULL;
    rng = &cv::theRNG();
    default_model_name = "my_random_trees";
}


void CvRTrees::clear()
{
    int k;
    for( k = 0; k < ntrees; k++ )
        delete trees[k];
    cvFree( &trees );

    delete data;
    data = 0;

    cvReleaseMat( &active_var_mask );
    cvReleaseMat( &var_importance );
    ntrees = 0;
}


CvRTrees::~CvRTrees()
{
    clear();
}

std::string CvRTrees::getName() const
{
    return CV_TYPE_NAME_ML_RTREES;
}

CvMat* CvRTrees::get_active_var_mask()
{
    return active_var_mask;
}


CvRNG* CvRTrees::get_rng()
{
    return &rng->state;
}

bool CvRTrees::train( const CvMat* _train_data, int _tflag,
                        const CvMat* _responses, const CvMat* _var_idx,
                        const CvMat* _sample_idx, const CvMat* _var_type,
                        const CvMat* _missing_mask, CvRTParams params )
{
    clear();

    CvDTreeParams tree_params( params.max_depth, params.min_sample_count,
        params.regression_accuracy, params.use_surrogates, params.max_categories,
        params.cv_folds, params.use_1se_rule, false, params.priors );

    data = new CvDTreeTrainData();
    data->set_data( _train_data, _tflag, _responses, _var_idx,
        _sample_idx, _var_type, _missing_mask, tree_params, true);

    int var_count = data->var_count;
    if( params.nactive_vars > var_count )
        params.nactive_vars = var_count;
    else if( params.nactive_vars == 0 )
        params.nactive_vars = (int)sqrt((double)var_count);
    else if( params.nactive_vars < 0 )
        CV_Error( CV_StsBadArg, "<nactive_vars> must be non-negative" );

    // Create mask of active variables at the tree nodes
    active_var_mask = cvCreateMat( 1, var_count, CV_8UC1 );
    if( params.calc_var_importance )
wester committed
291
    {
wester committed
292 293 294 295 296 297 298 299 300 301 302 303 304
        var_importance  = cvCreateMat( 1, var_count, CV_32FC1 );
        cvZero(var_importance);
    }
    { // initialize active variables mask
        CvMat submask1, submask2;
        CV_Assert( (active_var_mask->cols >= 1) && (params.nactive_vars > 0) && (params.nactive_vars <= active_var_mask->cols) );
        cvGetCols( active_var_mask, &submask1, 0, params.nactive_vars );
        cvSet( &submask1, cvScalar(1) );
        if( params.nactive_vars < active_var_mask->cols )
        {
            cvGetCols( active_var_mask, &submask2, params.nactive_vars, var_count );
            cvZero( &submask2 );
        }
wester committed
305 306
    }

wester committed
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
    return grow_forest( params.term_crit );
}

bool CvRTrees::train( CvMLData* _data, CvRTParams params )
{
    const CvMat* values = _data->get_values();
    const CvMat* response = _data->get_responses();
    const CvMat* missing = _data->get_missing();
    const CvMat* var_types = _data->get_var_types();
    const CvMat* train_sidx = _data->get_train_sample_idx();
    const CvMat* var_idx = _data->get_var_idx();

    return train( values, CV_ROW_SAMPLE, response, var_idx,
                  train_sidx, var_types, missing, params );
}

bool CvRTrees::grow_forest( const CvTermCriteria term_crit )
{
    CvMat* sample_idx_mask_for_tree = 0;
    CvMat* sample_idx_for_tree      = 0;

    const int max_ntrees = term_crit.max_iter;
    const double max_oob_err = term_crit.epsilon;

    const int dims = data->var_count;
    float maximal_response = 0;

    CvMat* oob_sample_votes    = 0;
    CvMat* oob_responses       = 0;

    float* oob_samples_perm_ptr= 0;

    float* samples_ptr     = 0;
    uchar* missing_ptr     = 0;
    float* true_resp_ptr   = 0;
    bool is_oob_or_vimportance = (max_oob_err > 0 && term_crit.type != CV_TERMCRIT_ITER) || var_importance;

    // oob_predictions_sum[i] = sum of predicted values for the i-th sample
    // oob_num_of_predictions[i] = number of summands
    //                            (number of predictions for the i-th sample)
    // initialize these variable to avoid warning C4701
    CvMat oob_predictions_sum = cvMat( 1, 1, CV_32FC1 );
    CvMat oob_num_of_predictions = cvMat( 1, 1, CV_32FC1 );

    nsamples = data->sample_count;
    nclasses = data->get_num_classes();

    if ( is_oob_or_vimportance )
wester committed
355
    {
wester committed
356
        if( data->is_classifier )
wester committed
357
        {
wester committed
358 359
            oob_sample_votes = cvCreateMat( nsamples, nclasses, CV_32SC1 );
            cvZero(oob_sample_votes);
wester committed
360
        }
wester committed
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
        else
        {
            // oob_responses[0,i] = oob_predictions_sum[i]
            //    = sum of predicted values for the i-th sample
            // oob_responses[1,i] = oob_num_of_predictions[i]
            //    = number of summands (number of predictions for the i-th sample)
            oob_responses = cvCreateMat( 2, nsamples, CV_32FC1 );
            cvZero(oob_responses);
            cvGetRow( oob_responses, &oob_predictions_sum, 0 );
            cvGetRow( oob_responses, &oob_num_of_predictions, 1 );
        }

        oob_samples_perm_ptr     = (float*)cvAlloc( sizeof(float)*nsamples*dims );
        samples_ptr              = (float*)cvAlloc( sizeof(float)*nsamples*dims );
        missing_ptr              = (uchar*)cvAlloc( sizeof(uchar)*nsamples*dims );
        true_resp_ptr            = (float*)cvAlloc( sizeof(float)*nsamples );

        data->get_vectors( 0, samples_ptr, missing_ptr, true_resp_ptr );

        double minval, maxval;
        CvMat responses = cvMat(1, nsamples, CV_32FC1, true_resp_ptr);
        cvMinMaxLoc( &responses, &minval, &maxval );
        maximal_response = (float)MAX( MAX( fabs(minval), fabs(maxval) ), 0 );
    }

    trees = (CvForestTree**)cvAlloc( sizeof(trees[0])*max_ntrees );
    memset( trees, 0, sizeof(trees[0])*max_ntrees );
wester committed
388

wester committed
389 390
    sample_idx_mask_for_tree = cvCreateMat( 1, nsamples, CV_8UC1 );
    sample_idx_for_tree      = cvCreateMat( 1, nsamples, CV_32SC1 );
wester committed
391

wester committed
392 393 394 395 396 397 398 399 400
    ntrees = 0;
    while( ntrees < max_ntrees )
    {
        int i, oob_samples_count = 0;
        double ncorrect_responses = 0; // used for estimation of variable importance
        CvForestTree* tree = 0;

        cvZero( sample_idx_mask_for_tree );
        for(i = 0; i < nsamples; i++ ) //form sample for creation one tree
wester committed
401
        {
wester committed
402 403 404 405
            int idx = (*rng)(nsamples);
            sample_idx_for_tree->data.i[i] = idx;
            sample_idx_mask_for_tree->data.ptr[idx] = 0xFF;
        }
wester committed
406

wester committed
407 408 409
        trees[ntrees] = new CvForestTree();
        tree = trees[ntrees];
        tree->train( data, sample_idx_for_tree, this );
wester committed
410

wester committed
411 412 413 414 415 416 417 418 419 420
        if ( is_oob_or_vimportance )
        {
            CvMat sample, missing;
            // form array of OOB samples indices and get these samples
            sample   = cvMat( 1, dims, CV_32FC1, samples_ptr );
            missing  = cvMat( 1, dims, CV_8UC1,  missing_ptr );

            oob_error = 0;
            for( i = 0; i < nsamples; i++,
                sample.data.fl += dims, missing.data.ptr += dims )
wester committed
421
            {
wester committed
422 423 424
                CvDTreeNode* predicted_node = 0;
                // check if the sample is OOB
                if( sample_idx_mask_for_tree->data.ptr[i] )
wester committed
425 426
                    continue;

wester committed
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
                // predict oob samples
                if( !predicted_node )
                    predicted_node = tree->predict(&sample, &missing, true);

                if( !data->is_classifier ) //regression
                {
                    double avg_resp, resp = predicted_node->value;
                    oob_predictions_sum.data.fl[i] += (float)resp;
                    oob_num_of_predictions.data.fl[i] += 1;

                    // compute oob error
                    avg_resp = oob_predictions_sum.data.fl[i]/oob_num_of_predictions.data.fl[i];
                    avg_resp -= true_resp_ptr[i];
                    oob_error += avg_resp*avg_resp;
                    resp = (resp - true_resp_ptr[i])/maximal_response;
                    ncorrect_responses += exp( -resp*resp );
                }
                else //classification
wester committed
445
                {
wester committed
446 447 448
                    double prdct_resp;
                    CvPoint max_loc;
                    CvMat votes;
wester committed
449

wester committed
450 451 452 453 454 455 456 457 458 459
                    cvGetRow(oob_sample_votes, &votes, i);
                    votes.data.i[predicted_node->class_idx]++;

                    // compute oob error
                    cvMinMaxLoc( &votes, 0, 0, 0, &max_loc );

                    prdct_resp = data->cat_map->data.i[max_loc.x];
                    oob_error += (fabs(prdct_resp - true_resp_ptr[i]) < FLT_EPSILON) ? 0 : 1;

                    ncorrect_responses += cvRound(predicted_node->value - true_resp_ptr[i]) == 0;
wester committed
460
                }
wester committed
461 462 463 464 465 466 467 468 469
                oob_samples_count++;
            }
            if( oob_samples_count > 0 )
                oob_error /= (double)oob_samples_count;

            // estimate variable importance
            if( var_importance && oob_samples_count > 0 )
            {
                int m;
wester committed
470

wester committed
471 472
                memcpy( oob_samples_perm_ptr, samples_ptr, dims*nsamples*sizeof(float));
                for( m = 0; m < dims; m++ )
wester committed
473
                {
wester committed
474 475 476 477 478
                    double ncorrect_responses_permuted = 0;
                    // randomly permute values of the m-th variable in the oob samples
                    float* mth_var_ptr = oob_samples_perm_ptr + m;

                    for( i = 0; i < nsamples; i++ )
wester committed
479
                    {
wester committed
480 481 482 483 484 485 486 487 488 489 490 491 492
                        int i1, i2;
                        float temp;

                        if( sample_idx_mask_for_tree->data.ptr[i] ) //the sample is not OOB
                            continue;
                        i1 = (*rng)(nsamples);
                        i2 = (*rng)(nsamples);
                        CV_SWAP( mth_var_ptr[i1*dims], mth_var_ptr[i2*dims], temp );

                        // turn values of (m-1)-th variable, that were permuted
                        // at the previous iteration, untouched
                        if( m > 1 )
                            oob_samples_perm_ptr[i*dims+m-1] = samples_ptr[i*dims+m-1];
wester committed
493 494
                    }

wester committed
495 496 497 498 499 500
                    // predict "permuted" cases and calculate the number of votes for the
                    // correct class in the variable-m-permuted oob data
                    sample  = cvMat( 1, dims, CV_32FC1, oob_samples_perm_ptr );
                    missing = cvMat( 1, dims, CV_8UC1, missing_ptr );
                    for( i = 0; i < nsamples; i++,
                        sample.data.fl += dims, missing.data.ptr += dims )
wester committed
501
                    {
wester committed
502 503 504 505
                        double predct_resp, true_resp;

                        if( sample_idx_mask_for_tree->data.ptr[i] ) //the sample is not OOB
                            continue;
wester committed
506

wester committed
507 508 509 510 511
                        predct_resp = tree->predict(&sample, &missing, true)->value;
                        true_resp   = true_resp_ptr[i];
                        if( data->is_classifier )
                            ncorrect_responses_permuted += cvRound(true_resp - predct_resp) == 0;
                        else
wester committed
512
                        {
wester committed
513 514
                            true_resp = (true_resp - predct_resp)/maximal_response;
                            ncorrect_responses_permuted += exp( -true_resp*true_resp );
wester committed
515 516
                        }
                    }
wester committed
517 518
                    var_importance->data.fl[m] += (float)(ncorrect_responses
                        - ncorrect_responses_permuted);
wester committed
519 520 521
                }
            }
        }
wester committed
522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
        ntrees++;
        if( term_crit.type != CV_TERMCRIT_ITER && oob_error < max_oob_err )
            break;
    }

    if( var_importance )
    {
        for ( int vi = 0; vi < var_importance->cols; vi++ )
                var_importance->data.fl[vi] = ( var_importance->data.fl[vi] > 0 ) ?
                    var_importance->data.fl[vi] : 0;
        cvNormalize( var_importance, var_importance, 1., 0, CV_L1 );
    }

    cvFree( &oob_samples_perm_ptr );
    cvFree( &samples_ptr );
    cvFree( &missing_ptr );
    cvFree( &true_resp_ptr );
wester committed
539

wester committed
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
    cvReleaseMat( &sample_idx_mask_for_tree );
    cvReleaseMat( &sample_idx_for_tree );

    cvReleaseMat( &oob_sample_votes );
    cvReleaseMat( &oob_responses );

    return true;
}


const CvMat* CvRTrees::get_var_importance()
{
    return var_importance;
}


float CvRTrees::get_proximity( const CvMat* sample1, const CvMat* sample2,
                              const CvMat* missing1, const CvMat* missing2 ) const
{
    float result = 0;

    for( int i = 0; i < ntrees; i++ )
        result += trees[i]->predict( sample1, missing1 ) ==
        trees[i]->predict( sample2, missing2 ) ?  1 : 0;
    result = result/(float)ntrees;

    return result;
}

float CvRTrees::calc_error( CvMLData* _data, int type , std::vector<float> *resp )
{
    float err = 0;
    const CvMat* values = _data->get_values();
    const CvMat* response = _data->get_responses();
    const CvMat* missing = _data->get_missing();
    const CvMat* sample_idx = (type == CV_TEST_ERROR) ? _data->get_test_sample_idx() : _data->get_train_sample_idx();
    const CvMat* var_types = _data->get_var_types();
    int* sidx = sample_idx ? sample_idx->data.i : 0;
    int r_step = CV_IS_MAT_CONT(response->type) ?
                1 : response->step / CV_ELEM_SIZE(response->type);
    bool is_classifier = var_types->data.ptr[var_types->cols-1] == CV_VAR_CATEGORICAL;
    int sample_count = sample_idx ? sample_idx->cols : 0;
    sample_count = (type == CV_TRAIN_ERROR && sample_count == 0) ? values->rows : sample_count;
    float* pred_resp = 0;
    if( resp && (sample_count > 0) )
    {
        resp->resize( sample_count );
        pred_resp = &((*resp)[0]);
    }
    if ( is_classifier )
    {
        for( int i = 0; i < sample_count; i++ )
wester committed
592
        {
wester committed
593 594 595 596 597 598 599 600 601 602
            CvMat sample, miss;
            int si = sidx ? sidx[i] : i;
            cvGetRow( values, &sample, si );
            if( missing )
                cvGetRow( missing, &miss, si );
            float r = (float)predict( &sample, missing ? &miss : 0 );
            if( pred_resp )
                pred_resp[i] = r;
            int d = fabs((double)r - response->data.fl[si*r_step]) <= FLT_EPSILON ? 0 : 1;
            err += d;
wester committed
603
        }
wester committed
604
        err = sample_count ? err / (float)sample_count * 100 : -FLT_MAX;
wester committed
605
    }
wester committed
606
    else
wester committed
607
    {
wester committed
608 609 610 611 612 613 614 615 616 617 618 619 620 621
        for( int i = 0; i < sample_count; i++ )
        {
            CvMat sample, miss;
            int si = sidx ? sidx[i] : i;
            cvGetRow( values, &sample, si );
            if( missing )
                cvGetRow( missing, &miss, si );
            float r = (float)predict( &sample, missing ? &miss : 0 );
            if( pred_resp )
                pred_resp[i] = r;
            float d = r - response->data.fl[si*r_step];
            err += d*d;
        }
        err = sample_count ? err / (float)sample_count : -FLT_MAX;
wester committed
622
    }
wester committed
623 624 625 626 627 628 629 630 631 632 633 634 635 636 637
    return err;
}

float CvRTrees::get_train_error()
{
    float err = -1;

    int sample_count = data->sample_count;
    int var_count = data->var_count;

    float *values_ptr = (float*)cvAlloc( sizeof(float)*sample_count*var_count );
    uchar *missing_ptr = (uchar*)cvAlloc( sizeof(uchar)*sample_count*var_count );
    float *responses_ptr = (float*)cvAlloc( sizeof(float)*sample_count );

    data->get_vectors( 0, values_ptr, missing_ptr, responses_ptr);
wester committed
638

wester committed
639
    if (data->is_classifier)
wester committed
640
    {
wester committed
641 642 643 644 645 646 647 648 649 650 651 652 653 654 655
        int err_count = 0;
        float *vp = values_ptr;
        uchar *mp = missing_ptr;
        for (int si = 0; si < sample_count; si++, vp += var_count, mp += var_count)
        {
            CvMat sample = cvMat( 1, var_count, CV_32FC1, vp );
            CvMat missing = cvMat( 1, var_count, CV_8UC1,  mp );
            float r = predict( &sample, &missing );
            if (fabs(r - responses_ptr[si]) >= FLT_EPSILON)
                err_count++;
        }
        err = (float)err_count / (float)sample_count;
    }
    else
        CV_Error( CV_StsBadArg, "This method is not supported for regression problems" );
wester committed
656

wester committed
657 658 659
    cvFree( &values_ptr );
    cvFree( &missing_ptr );
    cvFree( &responses_ptr );
wester committed
660

wester committed
661 662
    return err;
}
wester committed
663 664


wester committed
665 666 667 668
float CvRTrees::predict( const CvMat* sample, const CvMat* missing ) const
{
    double result = -1;
    int k;
wester committed
669

wester committed
670 671 672 673 674 675
    if( nclasses > 0 ) //classification
    {
        int max_nvotes = 0;
        cv::AutoBuffer<int> _votes(nclasses);
        int* votes = _votes;
        memset( votes, 0, sizeof(*votes)*nclasses );
wester committed
676 677
        for( k = 0; k < ntrees; k++ )
        {
wester committed
678 679 680 681
            CvDTreeNode* predicted_node = trees[k]->predict( sample, missing );
            int nvotes;
            int class_idx = predicted_node->class_idx;
            CV_Assert( 0 <= class_idx && class_idx < nclasses );
wester committed
682

wester committed
683 684 685 686 687 688 689 690 691 692 693 694 695 696
            nvotes = ++votes[class_idx];
            if( nvotes > max_nvotes )
            {
                max_nvotes = nvotes;
                result = predicted_node->value;
            }
        }
    }
    else // regression
    {
        result = 0;
        for( k = 0; k < ntrees; k++ )
            result += trees[k]->predict( sample, missing )->value;
        result /= (double)ntrees;
wester committed
697 698
    }

wester committed
699 700 701 702 703 704
    return (float)result;
}

float CvRTrees::predict_prob( const CvMat* sample, const CvMat* missing) const
{
    if( nclasses == 2 ) //classification
wester committed
705
    {
wester committed
706 707 708 709 710 711 712 713
        cv::AutoBuffer<int> _votes(nclasses);
        int* votes = _votes;
        memset( votes, 0, sizeof(*votes)*nclasses );
        for( int k = 0; k < ntrees; k++ )
        {
            CvDTreeNode* predicted_node = trees[k]->predict( sample, missing );
            int class_idx = predicted_node->class_idx;
            CV_Assert( 0 <= class_idx && class_idx < nclasses );
wester committed
714

wester committed
715 716 717 718
            ++votes[class_idx];
        }

        return float(votes[1])/ntrees;
wester committed
719
    }
wester committed
720 721
    else // regression
        CV_Error(CV_StsBadArg, "This function works for binary classification problems only...");
wester committed
722

wester committed
723 724
    return -1;
}
wester committed
725

wester committed
726 727 728
void CvRTrees::write( CvFileStorage* fs, const char* name ) const
{
    int k;
wester committed
729

wester committed
730 731
    if( ntrees < 1 || !trees || nsamples < 1 )
        CV_Error( CV_StsBadArg, "Invalid CvRTrees object" );
wester committed
732

wester committed
733 734
    std::string modelNodeName = this->getName();
    cvStartWriteStruct( fs, name, CV_NODE_MAP, modelNodeName.c_str() );
wester committed
735

wester committed
736 737 738 739
    cvWriteInt( fs, "nclasses", nclasses );
    cvWriteInt( fs, "nsamples", nsamples );
    cvWriteInt( fs, "nactive_vars", (int)cvSum(active_var_mask).val[0] );
    cvWriteReal( fs, "oob_error", oob_error );
wester committed
740

wester committed
741 742 743 744 745 746 747 748 749 750 751 752 753 754
    if( var_importance )
        cvWrite( fs, "var_importance", var_importance );

    cvWriteInt( fs, "ntrees", ntrees );

    data->write_params( fs );

    cvStartWriteStruct( fs, "trees", CV_NODE_SEQ );

    for( k = 0; k < ntrees; k++ )
    {
        cvStartWriteStruct( fs, 0, CV_NODE_MAP );
        trees[k]->write( fs );
        cvEndWriteStruct( fs );
wester committed
755 756
    }

wester committed
757 758 759
    cvEndWriteStruct( fs ); //trees
    cvEndWriteStruct( fs ); //CV_TYPE_NAME_ML_RTREES
}
wester committed
760 761


wester committed
762
void CvRTrees::read( CvFileStorage* fs, CvFileNode* fnode )
wester committed
763
{
wester committed
764 765 766
    int nactive_vars, var_count, k;
    CvSeqReader reader;
    CvFileNode* trees_fnode = 0;
wester committed
767

wester committed
768
    clear();
wester committed
769

wester committed
770 771 772 773 774
    nclasses     = cvReadIntByName( fs, fnode, "nclasses", -1 );
    nsamples     = cvReadIntByName( fs, fnode, "nsamples" );
    nactive_vars = cvReadIntByName( fs, fnode, "nactive_vars", -1 );
    oob_error    = cvReadRealByName(fs, fnode, "oob_error", -1 );
    ntrees       = cvReadIntByName( fs, fnode, "ntrees", -1 );
wester committed
775

wester committed
776
    var_importance = (CvMat*)cvReadByName( fs, fnode, "var_importance" );
wester committed
777

wester committed
778 779 780
    if( nclasses < 0 || nsamples <= 0 || nactive_vars < 0 || oob_error < 0 || ntrees <= 0)
        CV_Error( CV_StsParseError, "Some <nclasses>, <nsamples>, <var_count>, "
        "<nactive_vars>, <oob_error>, <ntrees> of tags are missing" );
wester committed
781

wester committed
782
    rng = &cv::theRNG();
wester committed
783

wester committed
784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800
    trees = (CvForestTree**)cvAlloc( sizeof(trees[0])*ntrees );
    memset( trees, 0, sizeof(trees[0])*ntrees );

    data = new CvDTreeTrainData();
    data->read_params( fs, fnode );
    data->shared = true;

    trees_fnode = cvGetFileNodeByName( fs, fnode, "trees" );
    if( !trees_fnode || !CV_NODE_IS_SEQ(trees_fnode->tag) )
        CV_Error( CV_StsParseError, "<trees> tag is missing" );

    cvStartReadSeq( trees_fnode->data.seq, &reader );
    if( reader.seq->total != ntrees )
        CV_Error( CV_StsParseError,
        "<ntrees> is not equal to the number of trees saved in file" );

    for( k = 0; k < ntrees; k++ )
wester committed
801
    {
wester committed
802 803 804
        trees[k] = new CvForestTree();
        trees[k]->read( fs, (CvFileNode*)reader.ptr, this, data );
        CV_NEXT_SEQ_ELEM( reader.seq->elem_size, reader );
wester committed
805 806
    }

wester committed
807 808
    var_count = data->var_count;
    active_var_mask = cvCreateMat( 1, var_count, CV_8UC1 );
wester committed
809
    {
wester committed
810 811 812 813 814 815 816 817 818 819 820
        // initialize active variables mask
        CvMat submask1;
        cvGetCols( active_var_mask, &submask1, 0, nactive_vars );
        cvSet( &submask1, cvScalar(1) );

        if( nactive_vars < var_count )
        {
            CvMat submask2;
            cvGetCols( active_var_mask, &submask2, nactive_vars, var_count );
            cvZero( &submask2 );
        }
wester committed
821
    }
wester committed
822
}
wester committed
823 824


wester committed
825 826 827 828
int CvRTrees::get_tree_count() const
{
    return ntrees;
}
wester committed
829

wester committed
830 831 832 833
CvForestTree* CvRTrees::get_tree(int i) const
{
    return (unsigned)i < (unsigned)ntrees ? trees[i] : 0;
}
wester committed
834

wester committed
835
using namespace cv;
wester committed
836

wester committed
837 838 839 840 841 842 843 844 845 846 847
bool CvRTrees::train( const Mat& _train_data, int _tflag,
                     const Mat& _responses, const Mat& _var_idx,
                     const Mat& _sample_idx, const Mat& _var_type,
                     const Mat& _missing_mask, CvRTParams _params )
{
    CvMat tdata = _train_data, responses = _responses, vidx = _var_idx,
    sidx = _sample_idx, vtype = _var_type, mmask = _missing_mask;
    return train(&tdata, _tflag, &responses, vidx.data.ptr ? &vidx : 0,
                 sidx.data.ptr ? &sidx : 0, vtype.data.ptr ? &vtype : 0,
                 mmask.data.ptr ? &mmask : 0, _params);
}
wester committed
848

wester committed
849 850 851 852 853 854 855 856

float CvRTrees::predict( const Mat& _sample, const Mat& _missing ) const
{
    CvMat sample = _sample, mmask = _missing;
    return predict(&sample, mmask.data.ptr ? &mmask : 0);
}

float CvRTrees::predict_prob( const Mat& _sample, const Mat& _missing) const
wester committed
857
{
wester committed
858 859
    CvMat sample = _sample, mmask = _missing;
    return predict_prob(&sample, mmask.data.ptr ? &mmask : 0);
wester committed
860 861
}

wester committed
862 863 864 865
Mat CvRTrees::getVarImportance()
{
    return Mat(get_var_importance());
}
wester committed
866 867

// End of file.