test_mltests2.cpp 29.1 KB
Newer Older
wester committed
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
/*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
//                For Open Source Computer Vision Library
//
// 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*/

#include "test_precomp.hpp"

using namespace cv;
using namespace std;

wester committed
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
// auxiliary functions
// 1. nbayes
void nbayes_check_data( CvMLData* _data )
{
    if( _data->get_missing() )
        CV_Error( CV_StsBadArg, "missing values are not supported" );
    const CvMat* var_types = _data->get_var_types();
    bool is_classifier = var_types->data.ptr[var_types->cols-1] == CV_VAR_CATEGORICAL;
    if( ( fabs( cvNorm( var_types, 0, CV_L1 ) -
        (var_types->rows + var_types->cols - 2)*CV_VAR_ORDERED - CV_VAR_CATEGORICAL ) > FLT_EPSILON ) ||
        !is_classifier )
        CV_Error( CV_StsBadArg, "incorrect types of predictors or responses" );
}
bool nbayes_train( CvNormalBayesClassifier* nbayes, CvMLData* _data )
{
    nbayes_check_data( _data );
    const CvMat* values = _data->get_values();
    const CvMat* responses = _data->get_responses();
    const CvMat* train_sidx = _data->get_train_sample_idx();
    const CvMat* var_idx = _data->get_var_idx();
    return nbayes->train( values, responses, var_idx, train_sidx );
}
float nbayes_calc_error( CvNormalBayesClassifier* nbayes, CvMLData* _data, int type, vector<float> *resp )
{
    float err = 0;
    nbayes_check_data( _data );
    const CvMat* values = _data->get_values();
    const CvMat* response = _data->get_responses();
    const CvMat* sample_idx = (type == CV_TEST_ERROR) ? _data->get_test_sample_idx() : _data->get_train_sample_idx();
    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);
    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]);
    }

    for( int i = 0; i < sample_count; i++ )
    {
        CvMat sample;
        int si = sidx ? sidx[i] : i;
        cvGetRow( values, &sample, si );
        float r = (float)nbayes->predict( &sample, 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;
    }
    err = sample_count ? err / (float)sample_count * 100 : -FLT_MAX;
    return err;
}

// 2. knearest
void knearest_check_data_and_get_predictors( CvMLData* _data, CvMat* _predictors )
{
    const CvMat* values = _data->get_values();
    const CvMat* var_idx = _data->get_var_idx();
    if( var_idx->cols + var_idx->rows != values->cols )
        CV_Error( CV_StsBadArg, "var_idx is not supported" );
    if( _data->get_missing() )
        CV_Error( CV_StsBadArg, "missing values are not supported" );
    int resp_idx = _data->get_response_idx();
    if( resp_idx == 0)
        cvGetCols( values, _predictors, 1, values->cols );
    else if( resp_idx == values->cols - 1 )
        cvGetCols( values, _predictors, 0, values->cols - 1 );
    else
        CV_Error( CV_StsBadArg, "responses must be in the first or last column; other cases are not supported" );
}
bool knearest_train( CvKNearest* knearest, CvMLData* _data )
{
    const CvMat* responses = _data->get_responses();
    const CvMat* train_sidx = _data->get_train_sample_idx();
    bool is_regression = _data->get_var_type( _data->get_response_idx() ) == CV_VAR_ORDERED;
    CvMat predictors;
    knearest_check_data_and_get_predictors( _data, &predictors );
    return knearest->train( &predictors, responses, train_sidx, is_regression );
}
float knearest_calc_error( CvKNearest* knearest, CvMLData* _data, int k, int type, vector<float> *resp )
{
    float err = 0;
    const CvMat* response = _data->get_responses();
    const CvMat* sample_idx = (type == CV_TEST_ERROR) ? _data->get_test_sample_idx() : _data->get_train_sample_idx();
    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_regression = _data->get_var_type( _data->get_response_idx() ) == CV_VAR_ORDERED;
    CvMat predictors;
    knearest_check_data_and_get_predictors( _data, &predictors );
    int sample_count = sample_idx ? sample_idx->cols : 0;
    sample_count = (type == CV_TRAIN_ERROR && sample_count == 0) ? predictors.rows : sample_count;
    float* pred_resp = 0;
    if( resp && (sample_count > 0) )
    {
        resp->resize( sample_count );
        pred_resp = &((*resp)[0]);
    }
    if ( !is_regression )
    {
        for( int i = 0; i < sample_count; i++ )
        {
            CvMat sample;
            int si = sidx ? sidx[i] : i;
            cvGetRow( &predictors, &sample, si );
            float r = knearest->find_nearest( &sample, k );
            if( pred_resp )
                pred_resp[i] = r;
            int d = fabs((double)r - response->data.fl[si*r_step]) <= FLT_EPSILON ? 0 : 1;
            err += d;
        }
        err = sample_count ? err / (float)sample_count * 100 : -FLT_MAX;
    }
    else
    {
        for( int i = 0; i < sample_count; i++ )
        {
            CvMat sample;
            int si = sidx ? sidx[i] : i;
            cvGetRow( &predictors, &sample, si );
            float r = knearest->find_nearest( &sample, k );
            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;
    }
    return err;
}

// 3. svm
int str_to_svm_type(string& str)
wester committed
183 184
{
    if( !str.compare("C_SVC") )
wester committed
185
        return CvSVM::C_SVC;
wester committed
186
    if( !str.compare("NU_SVC") )
wester committed
187
        return CvSVM::NU_SVC;
wester committed
188
    if( !str.compare("ONE_CLASS") )
wester committed
189
        return CvSVM::ONE_CLASS;
wester committed
190
    if( !str.compare("EPS_SVR") )
wester committed
191
        return CvSVM::EPS_SVR;
wester committed
192
    if( !str.compare("NU_SVR") )
wester committed
193
        return CvSVM::NU_SVR;
wester committed
194 195 196
    CV_Error( CV_StsBadArg, "incorrect svm type string" );
    return -1;
}
wester committed
197
int str_to_svm_kernel_type( string& str )
wester committed
198 199
{
    if( !str.compare("LINEAR") )
wester committed
200
        return CvSVM::LINEAR;
wester committed
201
    if( !str.compare("POLY") )
wester committed
202
        return CvSVM::POLY;
wester committed
203
    if( !str.compare("RBF") )
wester committed
204
        return CvSVM::RBF;
wester committed
205
    if( !str.compare("SIGMOID") )
wester committed
206
        return CvSVM::SIGMOID;
wester committed
207 208 209
    CV_Error( CV_StsBadArg, "incorrect svm type string" );
    return -1;
}
wester committed
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
void svm_check_data( CvMLData* _data )
{
    if( _data->get_missing() )
        CV_Error( CV_StsBadArg, "missing values are not supported" );
    const CvMat* var_types = _data->get_var_types();
    for( int i = 0; i < var_types->cols-1; i++ )
        if (var_types->data.ptr[i] == CV_VAR_CATEGORICAL)
        {
            char msg[50];
            sprintf( msg, "incorrect type of %d-predictor", i );
            CV_Error( CV_StsBadArg, msg );
        }
}
bool svm_train( CvSVM* svm, CvMLData* _data, CvSVMParams _params )
{
    svm_check_data(_data);
    const CvMat* _train_data = _data->get_values();
    const CvMat* _responses = _data->get_responses();
    const CvMat* _var_idx = _data->get_var_idx();
    const CvMat* _sample_idx = _data->get_train_sample_idx();
    return svm->train( _train_data, _responses, _var_idx, _sample_idx, _params );
}
bool svm_train_auto( CvSVM* svm, CvMLData* _data, CvSVMParams _params,
                    int k_fold, CvParamGrid C_grid, CvParamGrid gamma_grid,
                    CvParamGrid p_grid, CvParamGrid nu_grid, CvParamGrid coef_grid,
                    CvParamGrid degree_grid )
{
    svm_check_data(_data);
    const CvMat* _train_data = _data->get_values();
    const CvMat* _responses = _data->get_responses();
    const CvMat* _var_idx = _data->get_var_idx();
    const CvMat* _sample_idx = _data->get_train_sample_idx();
    return svm->train_auto( _train_data, _responses, _var_idx,
        _sample_idx, _params, k_fold, C_grid, gamma_grid, p_grid, nu_grid, coef_grid, degree_grid );
}
float svm_calc_error( CvSVM* svm, CvMLData* _data, int type, vector<float> *resp )
{
    svm_check_data(_data);
    float err = 0;
    const CvMat* values = _data->get_values();
    const CvMat* response = _data->get_responses();
    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++ )
        {
            CvMat sample;
            int si = sidx ? sidx[i] : i;
            cvGetRow( values, &sample, si );
            float r = svm->predict( &sample );
            if( pred_resp )
                pred_resp[i] = r;
            int d = fabs((double)r - response->data.fl[si*r_step]) <= FLT_EPSILON ? 0 : 1;
            err += d;
        }
        err = sample_count ? err / (float)sample_count * 100 : -FLT_MAX;
    }
    else
    {
        for( int i = 0; i < sample_count; i++ )
        {
            CvMat sample;
            int si = sidx ? sidx[i] : i;
            cvGetRow( values, &sample, si );
            float r = svm->predict( &sample );
            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;
    }
    return err;
}
wester committed
297 298 299

// 4. em
// 5. ann
wester committed
300
int str_to_ann_train_method( string& str )
wester committed
301 302
{
    if( !str.compare("BACKPROP") )
wester committed
303
        return CvANN_MLP_TrainParams::BACKPROP;
wester committed
304
    if( !str.compare("RPROP") )
wester committed
305
        return CvANN_MLP_TrainParams::RPROP;
wester committed
306 307 308
    CV_Error( CV_StsBadArg, "incorrect ann train method string" );
    return -1;
}
wester committed
309
void ann_check_data_and_get_predictors( CvMLData* _data, CvMat* _inputs )
wester committed
310
{
wester committed
311 312 313
    const CvMat* values = _data->get_values();
    const CvMat* var_idx = _data->get_var_idx();
    if( var_idx->cols + var_idx->rows != values->cols )
wester committed
314
        CV_Error( CV_StsBadArg, "var_idx is not supported" );
wester committed
315
    if( _data->get_missing() )
wester committed
316
        CV_Error( CV_StsBadArg, "missing values are not supported" );
wester committed
317 318 319 320 321 322 323
    int resp_idx = _data->get_response_idx();
    if( resp_idx == 0)
        cvGetCols( values, _inputs, 1, values->cols );
    else if( resp_idx == values->cols - 1 )
        cvGetCols( values, _inputs, 0, values->cols - 1 );
    else
        CV_Error( CV_StsBadArg, "outputs must be in the first or last column; other cases are not supported" );
wester committed
324
}
wester committed
325
void ann_get_new_responses( CvMLData* _data, Mat& new_responses, map<int, int>& cls_map )
wester committed
326
{
wester committed
327 328 329 330 331 332
    const CvMat* train_sidx = _data->get_train_sample_idx();
    int* train_sidx_ptr = train_sidx->data.i;
    const CvMat* responses = _data->get_responses();
    float* responses_ptr = responses->data.fl;
    int r_step = CV_IS_MAT_CONT(responses->type) ?
        1 : responses->step / CV_ELEM_SIZE(responses->type);
wester committed
333 334 335
    int cls_count = 0;
    // construct cls_map
    cls_map.clear();
wester committed
336
    for( int si = 0; si < train_sidx->cols; si++ )
wester committed
337
    {
wester committed
338 339 340 341 342 343
        int sidx = train_sidx_ptr[si];
        int r = cvRound(responses_ptr[sidx*r_step]);
        CV_DbgAssert( fabs(responses_ptr[sidx*r_step]-r) < FLT_EPSILON );
        int cls_map_size = (int)cls_map.size();
        cls_map[r];
        if ( (int)cls_map.size() > cls_map_size )
wester committed
344 345
            cls_map[r] = cls_count++;
    }
wester committed
346 347 348
    new_responses.create( responses->rows, cls_count, CV_32F );
    new_responses.setTo( 0 );
    for( int si = 0; si < train_sidx->cols; si++ )
wester committed
349
    {
wester committed
350 351
        int sidx = train_sidx_ptr[si];
        int r = cvRound(responses_ptr[sidx*r_step]);
wester committed
352
        int cidx = cls_map[r];
wester committed
353
        new_responses.ptr<float>(sidx)[cidx] = 1;
wester committed
354 355
    }
}
wester committed
356 357 358 359 360 361 362 363 364
int ann_train( CvANN_MLP* ann, CvMLData* _data, Mat& new_responses, CvANN_MLP_TrainParams _params, int flags = 0 )
{
    const CvMat* train_sidx = _data->get_train_sample_idx();
    CvMat predictors;
    ann_check_data_and_get_predictors( _data, &predictors );
    CvMat _new_responses = CvMat( new_responses );
    return ann->train( &predictors, &_new_responses, 0, train_sidx, _params, flags );
}
float ann_calc_error( CvANN_MLP* ann, CvMLData* _data, map<int, int>& cls_map, int type , vector<float> *resp_labels )
wester committed
365 366
{
    float err = 0;
wester committed
367 368 369 370 371 372 373 374 375
    const CvMat* responses = _data->get_responses();
    const CvMat* sample_idx = (type == CV_TEST_ERROR) ? _data->get_test_sample_idx() : _data->get_train_sample_idx();
    int* sidx = sample_idx ? sample_idx->data.i : 0;
    int r_step = CV_IS_MAT_CONT(responses->type) ?
        1 : responses->step / CV_ELEM_SIZE(responses->type);
    CvMat predictors;
    ann_check_data_and_get_predictors( _data, &predictors );
    int sample_count = sample_idx ? sample_idx->cols : 0;
    sample_count = (type == CV_TRAIN_ERROR && sample_count == 0) ? predictors.rows : sample_count;
wester committed
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
    float* pred_resp = 0;
    vector<float> innresp;
    if( sample_count > 0 )
    {
        if( resp_labels )
        {
            resp_labels->resize( sample_count );
            pred_resp = &((*resp_labels)[0]);
        }
        else
        {
            innresp.resize( sample_count );
            pred_resp = &(innresp[0]);
        }
    }
    int cls_count = (int)cls_map.size();
    Mat output( 1, cls_count, CV_32FC1 );
wester committed
393
    CvMat _output = CvMat(output);
wester committed
394 395
    for( int i = 0; i < sample_count; i++ )
    {
wester committed
396
        CvMat sample;
wester committed
397
        int si = sidx ? sidx[i] : i;
wester committed
398 399 400 401 402 403
        cvGetRow( &predictors, &sample, si );
        ann->predict( &sample, &_output );
        CvPoint best_cls = {0,0};
        cvMinMaxLoc( &_output, 0, 0, 0, &best_cls, 0 );
        int r = cvRound(responses->data.fl[si*r_step]);
        CV_DbgAssert( fabs(responses->data.fl[si*r_step]-r) < FLT_EPSILON );
wester committed
404 405 406 407 408 409 410 411 412 413 414
        r = cls_map[r];
        int d = best_cls.x == r ? 0 : 1;
        err += d;
        pred_resp[i] = (float)best_cls.x;
    }
    err = sample_count ? err / (float)sample_count * 100 : -FLT_MAX;
    return err;
}

// 6. dtree
// 7. boost
wester committed
415
int str_to_boost_type( string& str )
wester committed
416 417
{
    if ( !str.compare("DISCRETE") )
wester committed
418
        return CvBoost::DISCRETE;
wester committed
419
    if ( !str.compare("REAL") )
wester committed
420
        return CvBoost::REAL;
wester committed
421
    if ( !str.compare("LOGIT") )
wester committed
422
        return CvBoost::LOGIT;
wester committed
423
    if ( !str.compare("GENTLE") )
wester committed
424
        return CvBoost::GENTLE;
wester committed
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
    CV_Error( CV_StsBadArg, "incorrect boost type string" );
    return -1;
}

// 8. rtrees
// 9. ertrees

// ---------------------------------- MLBaseTest ---------------------------------------------------

CV_MLBaseTest::CV_MLBaseTest(const char* _modelName)
{
    int64 seeds[] = { CV_BIG_INT(0x00009fff4f9c8d52),
                      CV_BIG_INT(0x0000a17166072c7c),
                      CV_BIG_INT(0x0201b32115cd1f9a),
                      CV_BIG_INT(0x0513cb37abcd1234),
                      CV_BIG_INT(0x0001a2b3c4d5f678)
                    };

    int seedCount = sizeof(seeds)/sizeof(seeds[0]);
    RNG& rng = theRNG();

    initSeed = rng.state;
wester committed
447

wester committed
448 449 450
    rng.state = seeds[rng(seedCount)];

    modelName = _modelName;
wester committed
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
    nbayes = 0;
    knearest = 0;
    svm = 0;
    ann = 0;
    dtree = 0;
    boost = 0;
    rtrees = 0;
    ertrees = 0;
    if( !modelName.compare(CV_NBAYES) )
        nbayes = new CvNormalBayesClassifier;
    else if( !modelName.compare(CV_KNEAREST) )
        knearest = new CvKNearest;
    else if( !modelName.compare(CV_SVM) )
        svm = new CvSVM;
    else if( !modelName.compare(CV_ANN) )
        ann = new CvANN_MLP;
    else if( !modelName.compare(CV_DTREE) )
        dtree = new CvDTree;
    else if( !modelName.compare(CV_BOOST) )
        boost = new CvBoost;
    else if( !modelName.compare(CV_RTREES) )
        rtrees = new CvRTrees;
    else if( !modelName.compare(CV_ERTREES) )
        ertrees = new CvERTrees;
wester committed
475 476 477 478 479 480
}

CV_MLBaseTest::~CV_MLBaseTest()
{
    if( validationFS.isOpened() )
        validationFS.release();
wester committed
481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
    if( nbayes )
        delete nbayes;
    if( knearest )
        delete knearest;
    if( svm )
        delete svm;
    if( ann )
        delete ann;
    if( dtree )
        delete dtree;
    if( boost )
        delete boost;
    if( rtrees )
        delete rtrees;
    if( ertrees )
        delete ertrees;
wester committed
497 498 499
    theRNG().state = initSeed;
}

wester committed
500
int CV_MLBaseTest::read_params( CvFileStorage* _fs )
wester committed
501
{
wester committed
502
    if( !_fs )
wester committed
503 504 505
        test_case_count = -1;
    else
    {
wester committed
506 507 508 509 510
        CvFileNode* fn = cvGetRootFileNode( _fs, 0 );
        fn = (CvFileNode*)cvGetSeqElem( fn->data.seq, 0 );
        fn = cvGetFileNodeByName( _fs, fn, "run_params" );
        CvSeq* dataSetNamesSeq = cvGetFileNodeByName( _fs, fn, modelName.c_str() )->data.seq;
        test_case_count = dataSetNamesSeq ? dataSetNamesSeq->total : -1;
wester committed
511 512 513
        if( test_case_count > 0 )
        {
            dataSetNames.resize( test_case_count );
wester committed
514 515 516
            vector<string>::iterator it = dataSetNames.begin();
            for( int i = 0; i < test_case_count; i++, it++ )
                *it = ((CvFileNode*)cvGetSeqElem( dataSetNamesSeq, i ))->data.str.ptr;
wester committed
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
        }
    }
    return cvtest::TS::OK;;
}

void CV_MLBaseTest::run( int )
{
    string filename = ts->get_data_path();
    filename += get_validation_filename();
    validationFS.open( filename, FileStorage::READ );
    read_params( *validationFS );

    int code = cvtest::TS::OK;
    for (int i = 0; i < test_case_count; i++)
    {
        int temp_code = run_test_case( i );
        if (temp_code == cvtest::TS::OK)
            temp_code = validate_test_results( i );
        if (temp_code != cvtest::TS::OK)
            code = temp_code;
    }
    if ( test_case_count <= 0)
    {
        ts->printf( cvtest::TS::LOG, "validation file is not determined or not correct" );
        code = cvtest::TS::FAIL_INVALID_TEST_DATA;
    }
    ts->set_failed_test_info( code );
}

int CV_MLBaseTest::prepare_test_case( int test_case_idx )
{
wester committed
548 549
    int trainSampleCount, respIdx;
    string varTypes;
wester committed
550 551 552 553 554 555 556 557 558 559 560
    clear();

    string dataPath = ts->get_data_path();
    if ( dataPath.empty() )
    {
        ts->printf( cvtest::TS::LOG, "data path is empty" );
        return cvtest::TS::FAIL_INVALID_TEST_DATA;
    }

    string dataName = dataSetNames[test_case_idx],
        filename = dataPath + dataName + ".data";
wester committed
561 562 563 564 565 566 567
    if ( data.read_csv( filename.c_str() ) != 0)
    {
        char msg[100];
        sprintf( msg, "file %s can not be read", filename.c_str() );
        ts->printf( cvtest::TS::LOG, msg );
        return cvtest::TS::FAIL_INVALID_TEST_DATA;
    }
wester committed
568 569 570 571 572

    FileNode dataParamsNode = validationFS.getFirstTopLevelNode()["validation"][modelName][dataName]["data_params"];
    CV_DbgAssert( !dataParamsNode.empty() );

    CV_DbgAssert( !dataParamsNode["LS"].empty() );
wester committed
573 574 575
    dataParamsNode["LS"] >> trainSampleCount;
    CvTrainTestSplit spl( trainSampleCount );
    data.set_train_test_split( &spl );
wester committed
576 577

    CV_DbgAssert( !dataParamsNode["resp_idx"].empty() );
wester committed
578 579
    dataParamsNode["resp_idx"] >> respIdx;
    data.set_response_idx( respIdx );
wester committed
580 581

    CV_DbgAssert( !dataParamsNode["types"].empty() );
wester committed
582 583
    dataParamsNode["types"] >> varTypes;
    data.set_var_types( varTypes.c_str() );
wester committed
584 585 586 587 588 589 590 591 592 593 594 595 596 597 598

    return cvtest::TS::OK;
}

string& CV_MLBaseTest::get_validation_filename()
{
    return validationFN;
}

int CV_MLBaseTest::train( int testCaseIdx )
{
    bool is_trained = false;
    FileNode modelParamsNode =
        validationFS.getFirstTopLevelNode()["validation"][modelName][dataSetNames[testCaseIdx]]["model_params"];

wester committed
599 600 601
    if( !modelName.compare(CV_NBAYES) )
        is_trained = nbayes_train( nbayes, &data );
    else if( !modelName.compare(CV_KNEAREST) )
wester committed
602
    {
wester committed
603 604
        assert( 0 );
        //is_trained = knearest->train( &data );
wester committed
605
    }
wester committed
606
    else if( !modelName.compare(CV_SVM) )
wester committed
607
    {
wester committed
608
        string svm_type_str, kernel_type_str;
wester committed
609 610
        modelParamsNode["svm_type"] >> svm_type_str;
        modelParamsNode["kernel_type"] >> kernel_type_str;
wester committed
611 612 613 614 615 616 617 618 619 620
        CvSVMParams params;
        params.svm_type = str_to_svm_type( svm_type_str );
        params.kernel_type = str_to_svm_kernel_type( kernel_type_str );
        modelParamsNode["degree"] >> params.degree;
        modelParamsNode["gamma"] >> params.gamma;
        modelParamsNode["coef0"] >> params.coef0;
        modelParamsNode["C"] >> params.C;
        modelParamsNode["nu"] >> params.nu;
        modelParamsNode["p"] >> params.p;
        is_trained = svm_train( svm, &data, params );
wester committed
621
    }
wester committed
622
    else if( !modelName.compare(CV_EM) )
wester committed
623 624 625
    {
        assert( 0 );
    }
wester committed
626
    else if( !modelName.compare(CV_ANN) )
wester committed
627
    {
wester committed
628
        string train_method_str;
wester committed
629 630 631 632
        double param1, param2;
        modelParamsNode["train_method"] >> train_method_str;
        modelParamsNode["param1"] >> param1;
        modelParamsNode["param2"] >> param2;
wester committed
633 634 635 636 637 638 639 640
        Mat new_responses;
        ann_get_new_responses( &data, new_responses, cls_map );
        int layer_sz[] = { data.get_values()->cols - 1, 100, 100, (int)cls_map.size() };
        CvMat layer_sizes =
            cvMat( 1, (int)(sizeof(layer_sz)/sizeof(layer_sz[0])), CV_32S, layer_sz );
        ann->create( &layer_sizes );
        is_trained = ann_train( ann, &data, new_responses, CvANN_MLP_TrainParams(cvTermCriteria(CV_TERMCRIT_ITER,300,0.01),
            str_to_ann_train_method(train_method_str), param1, param2) ) >= 0;
wester committed
641
    }
wester committed
642
    else if( !modelName.compare(CV_DTREE) )
wester committed
643 644 645
    {
        int MAX_DEPTH, MIN_SAMPLE_COUNT, MAX_CATEGORIES, CV_FOLDS;
        float REG_ACCURACY = 0;
wester committed
646
        bool USE_SURROGATE, IS_PRUNED;
wester committed
647 648
        modelParamsNode["max_depth"] >> MAX_DEPTH;
        modelParamsNode["min_sample_count"] >> MIN_SAMPLE_COUNT;
wester committed
649
        modelParamsNode["use_surrogate"] >> USE_SURROGATE;
wester committed
650 651 652
        modelParamsNode["max_categories"] >> MAX_CATEGORIES;
        modelParamsNode["cv_folds"] >> CV_FOLDS;
        modelParamsNode["is_pruned"] >> IS_PRUNED;
wester committed
653 654 655
        is_trained = dtree->train( &data,
            CvDTreeParams(MAX_DEPTH, MIN_SAMPLE_COUNT, REG_ACCURACY, USE_SURROGATE,
            MAX_CATEGORIES, CV_FOLDS, false, IS_PRUNED, 0 )) != 0;
wester committed
656
    }
wester committed
657
    else if( !modelName.compare(CV_BOOST) )
wester committed
658 659 660
    {
        int BOOST_TYPE, WEAK_COUNT, MAX_DEPTH;
        float WEIGHT_TRIM_RATE;
wester committed
661 662
        bool USE_SURROGATE;
        string typeStr;
wester committed
663 664 665 666 667
        modelParamsNode["type"] >> typeStr;
        BOOST_TYPE = str_to_boost_type( typeStr );
        modelParamsNode["weak_count"] >> WEAK_COUNT;
        modelParamsNode["weight_trim_rate"] >> WEIGHT_TRIM_RATE;
        modelParamsNode["max_depth"] >> MAX_DEPTH;
wester committed
668 669 670
        modelParamsNode["use_surrogate"] >> USE_SURROGATE;
        is_trained = boost->train( &data,
            CvBoostParams(BOOST_TYPE, WEAK_COUNT, WEIGHT_TRIM_RATE, MAX_DEPTH, USE_SURROGATE, 0) ) != 0;
wester committed
671
    }
wester committed
672
    else if( !modelName.compare(CV_RTREES) )
wester committed
673 674 675
    {
        int MAX_DEPTH, MIN_SAMPLE_COUNT, MAX_CATEGORIES, CV_FOLDS, NACTIVE_VARS, MAX_TREES_NUM;
        float REG_ACCURACY = 0, OOB_EPS = 0.0;
wester committed
676
        bool USE_SURROGATE, IS_PRUNED;
wester committed
677 678
        modelParamsNode["max_depth"] >> MAX_DEPTH;
        modelParamsNode["min_sample_count"] >> MIN_SAMPLE_COUNT;
wester committed
679
        modelParamsNode["use_surrogate"] >> USE_SURROGATE;
wester committed
680 681 682 683 684
        modelParamsNode["max_categories"] >> MAX_CATEGORIES;
        modelParamsNode["cv_folds"] >> CV_FOLDS;
        modelParamsNode["is_pruned"] >> IS_PRUNED;
        modelParamsNode["nactive_vars"] >> NACTIVE_VARS;
        modelParamsNode["max_trees_num"] >> MAX_TREES_NUM;
wester committed
685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704
        is_trained = rtrees->train( &data, CvRTParams(  MAX_DEPTH, MIN_SAMPLE_COUNT, REG_ACCURACY,
            USE_SURROGATE, MAX_CATEGORIES, 0, true, // (calc_var_importance == true) <=> RF processes variable importance
            NACTIVE_VARS, MAX_TREES_NUM, OOB_EPS, CV_TERMCRIT_ITER)) != 0;
    }
    else if( !modelName.compare(CV_ERTREES) )
    {
        int MAX_DEPTH, MIN_SAMPLE_COUNT, MAX_CATEGORIES, CV_FOLDS, NACTIVE_VARS, MAX_TREES_NUM;
        float REG_ACCURACY = 0, OOB_EPS = 0.0;
        bool USE_SURROGATE, IS_PRUNED;
        modelParamsNode["max_depth"] >> MAX_DEPTH;
        modelParamsNode["min_sample_count"] >> MIN_SAMPLE_COUNT;
        modelParamsNode["use_surrogate"] >> USE_SURROGATE;
        modelParamsNode["max_categories"] >> MAX_CATEGORIES;
        modelParamsNode["cv_folds"] >> CV_FOLDS;
        modelParamsNode["is_pruned"] >> IS_PRUNED;
        modelParamsNode["nactive_vars"] >> NACTIVE_VARS;
        modelParamsNode["max_trees_num"] >> MAX_TREES_NUM;
        is_trained = ertrees->train( &data, CvRTParams( MAX_DEPTH, MIN_SAMPLE_COUNT, REG_ACCURACY,
            USE_SURROGATE, MAX_CATEGORIES, 0, false, // (calc_var_importance == true) <=> RF processes variable importance
            NACTIVE_VARS, MAX_TREES_NUM, OOB_EPS, CV_TERMCRIT_ITER)) != 0;
wester committed
705 706 707 708 709 710 711 712 713 714
    }

    if( !is_trained )
    {
        ts->printf( cvtest::TS::LOG, "in test case %d model training was failed", testCaseIdx );
        return cvtest::TS::FAIL_INVALID_OUTPUT;
    }
    return cvtest::TS::OK;
}

wester committed
715
float CV_MLBaseTest::get_error( int /*testCaseIdx*/, int type, vector<float> *resp )
wester committed
716 717
{
    float err = 0;
wester committed
718 719 720 721 722 723 724 725 726 727 728 729 730
    if( !modelName.compare(CV_NBAYES) )
        err = nbayes_calc_error( nbayes, &data, type, resp );
    else if( !modelName.compare(CV_KNEAREST) )
    {
        assert( 0 );
        /*testCaseIdx = 0;
        int k = 2;
        validationFS.getFirstTopLevelNode()["validation"][modelName][dataSetNames[testCaseIdx]]["model_params"]["k"] >> k;
        err = knearest->calc_error( &data, k, type, resp );*/
    }
    else if( !modelName.compare(CV_SVM) )
        err = svm_calc_error( svm, &data, type, resp );
    else if( !modelName.compare(CV_EM) )
wester committed
731
        assert( 0 );
wester committed
732 733 734 735 736 737 738 739 740 741
    else if( !modelName.compare(CV_ANN) )
        err = ann_calc_error( ann, &data, cls_map, type, resp );
    else if( !modelName.compare(CV_DTREE) )
        err = dtree->calc_error( &data, type, resp );
    else if( !modelName.compare(CV_BOOST) )
        err = boost->calc_error( &data, type, resp );
    else if( !modelName.compare(CV_RTREES) )
        err = rtrees->calc_error( &data, type, resp );
    else if( !modelName.compare(CV_ERTREES) )
        err = ertrees->calc_error( &data, type, resp );
wester committed
742 743 744 745 746
    return err;
}

void CV_MLBaseTest::save( const char* filename )
{
wester committed
747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762
    if( !modelName.compare(CV_NBAYES) )
        nbayes->save( filename );
    else if( !modelName.compare(CV_KNEAREST) )
        knearest->save( filename );
    else if( !modelName.compare(CV_SVM) )
        svm->save( filename );
    else if( !modelName.compare(CV_ANN) )
        ann->save( filename );
    else if( !modelName.compare(CV_DTREE) )
        dtree->save( filename );
    else if( !modelName.compare(CV_BOOST) )
        boost->save( filename );
    else if( !modelName.compare(CV_RTREES) )
        rtrees->save( filename );
    else if( !modelName.compare(CV_ERTREES) )
        ertrees->save( filename );
wester committed
763 764 765 766
}

void CV_MLBaseTest::load( const char* filename )
{
wester committed
767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786
    if( !modelName.compare(CV_NBAYES) )
        nbayes->load( filename );
    else if( !modelName.compare(CV_KNEAREST) )
        knearest->load( filename );
    else if( !modelName.compare(CV_SVM) )
    {
        delete svm;
        svm = new CvSVM;
        svm->load( filename );
    }
    else if( !modelName.compare(CV_ANN) )
        ann->load( filename );
    else if( !modelName.compare(CV_DTREE) )
        dtree->load( filename );
    else if( !modelName.compare(CV_BOOST) )
        boost->load( filename );
    else if( !modelName.compare(CV_RTREES) )
        rtrees->load( filename );
    else if( !modelName.compare(CV_ERTREES) )
        ertrees->load( filename );
wester committed
787 788 789
}

/* End of file. */