5 The sample demonstrates how to train Random Trees classifier
6 (or Boosting classifier, or MLP - see main()) using the provided dataset.
8 We use the sample database letter-recognition.data
9 from UCI Repository, here is the link:
11 Newman, D.J. & Hettich, S. & Blake, C.L. & Merz, C.J. (1998).
12 UCI Repository of machine learning databases
13 [http://www.ics.uci.edu/~mlearn/MLRepository.html].
14 Irvine, CA: University of California, Department of Information and Computer Science.
16 The dataset consists of 20000 feature vectors along with the
17 responses - capital latin letters A..Z.
18 The first 16000 (10000 for boosting)) samples are used for training
19 and the remaining 4000 (10000 for boosting) - to test the classifier.
22 // This function reads data and responses from the file <filename>
24 read_num_class_data( const char* filename, int var_count,
25 CvMat** data, CvMat** responses )
28 FILE* f = fopen( filename, "rt" );
29 CvMemStorage* storage;
39 el_ptr = new float[var_count+1];
40 storage = cvCreateMemStorage();
41 seq = cvCreateSeq( 0, sizeof(*seq), (var_count+1)*sizeof(float), storage );
46 if( !fgets( buf, M, f ) || !strchr( buf, ',' ) )
50 for( i = 1; i <= var_count; i++ )
53 sscanf( ptr, "%f%n", el_ptr + i, &n );
58 cvSeqPush( seq, el_ptr );
62 *data = cvCreateMat( seq->total, var_count, CV_32F );
63 *responses = cvCreateMat( seq->total, 1, CV_32F );
65 cvStartReadSeq( seq, &reader );
67 for( i = 0; i < seq->total; i++ )
69 const float* sdata = (float*)reader.ptr + 1;
70 float* ddata = data[0]->data.fl + var_count*i;
71 float* dr = responses[0]->data.fl + i;
73 for( j = 0; j < var_count; j++ )
76 CV_NEXT_SEQ_ELEM( seq->elem_size, reader );
79 cvReleaseMemStorage( &storage );
85 int build_rtrees_classifier( char* data_filename,
86 char* filename_to_save, char* filename_to_load )
91 CvMat* sample_idx = 0;
93 int ok = read_num_class_data( data_filename, 16, &data, &responses );
94 int nsamples_all = 0, ntrain_samples = 0;
96 double train_hr = 0, test_hr = 0;
98 CvMat* var_importance = 0;
102 printf( "Could not read the database %s\n", data_filename );
106 printf( "The database %s is loaded.\n", data_filename );
107 nsamples_all = data->rows;
108 ntrain_samples = (int)(nsamples_all*0.8);
110 // Create or load Random Trees classifier
111 if( filename_to_load )
113 // load classifier from the specified file
114 forest.load( filename_to_load );
116 if( forest.get_tree_count() == 0 )
118 printf( "Could not read the classifier %s\n", filename_to_load );
121 printf( "The classifier %s is loaded.\n", data_filename );
125 // create classifier by using <data> and <responses>
126 printf( "Training the classifier ...");
128 // 1. create type mask
129 var_type = cvCreateMat( data->cols + 1, 1, CV_8U );
130 cvSet( var_type, cvScalarAll(CV_VAR_ORDERED) );
131 cvSetReal1D( var_type, data->cols, CV_VAR_CATEGORICAL );
133 // 2. create sample_idx
134 sample_idx = cvCreateMat( 1, nsamples_all, CV_8UC1 );
137 cvGetCols( sample_idx, &mat, 0, ntrain_samples );
138 cvSet( &mat, cvRealScalar(1) );
140 cvGetCols( sample_idx, &mat, ntrain_samples, nsamples_all );
144 // 3. train classifier
145 forest.train( data, CV_ROW_SAMPLE, responses, 0, sample_idx, var_type, 0,
146 CvRTParams(10,10,0,false,15,0,true,4,100,0.01f,CV_TERMCRIT_ITER));
150 // compute prediction error on train and test data
151 for( i = 0; i < nsamples_all; i++ )
155 cvGetRow( data, &sample, i );
157 r = forest.predict( &sample );
158 r = fabs((double)r - responses->data.fl[i]) <= FLT_EPSILON ? 1 : 0;
160 if( i < ntrain_samples )
166 test_hr /= (double)(nsamples_all-ntrain_samples);
167 train_hr /= (double)ntrain_samples;
168 printf( "Recognition rate: train = %.1f%%, test = %.1f%%\n",
169 train_hr*100., test_hr*100. );
171 printf( "Number of trees: %d\n", forest.get_tree_count() );
173 // Print variable importance
174 var_importance = (CvMat*)forest.get_var_importance();
177 double rt_imp_sum = cvSum( var_importance ).val[0];
178 printf("var#\timportance (in %%):\n");
179 for( i = 0; i < var_importance->cols; i++ )
180 printf( "%-2d\t%-4.1f\n", i,
181 100.f*var_importance->data.fl[i]/rt_imp_sum);
184 //Print some proximitites
185 printf( "Proximities between some samples corresponding to the letter 'T':\n" );
187 CvMat sample1, sample2;
188 const int pairs[][2] = {{0,103}, {0,106}, {106,103}, {-1,-1}};
190 for( i = 0; pairs[i][0] >= 0; i++ )
192 cvGetRow( data, &sample1, pairs[i][0] );
193 cvGetRow( data, &sample2, pairs[i][1] );
194 printf( "proximity(%d,%d) = %.1f%%\n", pairs[i][0], pairs[i][1],
195 forest.get_proximity( &sample1, &sample2 )*100. );
199 // Save Random Trees classifier to file if needed
200 if( filename_to_save )
201 forest.save( filename_to_save );
203 cvReleaseMat( &sample_idx );
204 cvReleaseMat( &var_type );
205 cvReleaseMat( &data );
206 cvReleaseMat( &responses );
213 int build_boost_classifier( char* data_filename,
214 char* filename_to_save, char* filename_to_load )
216 const int class_count = 26;
218 CvMat* responses = 0;
220 CvMat* temp_sample = 0;
221 CvMat* weak_responses = 0;
223 int ok = read_num_class_data( data_filename, 16, &data, &responses );
224 int nsamples_all = 0, ntrain_samples = 0;
227 double train_hr = 0, test_hr = 0;
232 printf( "Could not read the database %s\n", data_filename );
236 printf( "The database %s is loaded.\n", data_filename );
237 nsamples_all = data->rows;
238 ntrain_samples = (int)(nsamples_all*0.5);
239 var_count = data->cols;
241 // Create or load Boosted Tree classifier
242 if( filename_to_load )
244 // load classifier from the specified file
245 boost.load( filename_to_load );
247 if( !boost.get_weak_predictors() )
249 printf( "Could not read the classifier %s\n", filename_to_load );
252 printf( "The classifier %s is loaded.\n", data_filename );
256 // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
258 // As currently boosted tree classifier in MLL can only be trained
259 // for 2-class problems, we transform the training database by
260 // "unrolling" each training sample as many times as the number of
261 // classes (26) that we have.
263 // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
265 CvMat* new_data = cvCreateMat( ntrain_samples*class_count, var_count + 1, CV_32F );
266 CvMat* new_responses = cvCreateMat( ntrain_samples*class_count, 1, CV_32S );
268 // 1. unroll the database type mask
269 printf( "Unrolling the database...\n");
270 for( i = 0; i < ntrain_samples; i++ )
272 float* data_row = (float*)(data->data.ptr + data->step*i);
273 for( j = 0; j < class_count; j++ )
275 float* new_data_row = (float*)(new_data->data.ptr +
276 new_data->step*(i*class_count+j));
277 for( k = 0; k < var_count; k++ )
278 new_data_row[k] = data_row[k];
279 new_data_row[var_count] = (float)j;
280 new_responses->data.i[i*class_count + j] = responses->data.fl[i] == j+'A';
284 // 2. create type mask
285 var_type = cvCreateMat( var_count + 2, 1, CV_8U );
286 cvSet( var_type, cvScalarAll(CV_VAR_ORDERED) );
287 // the last indicator variable, as well
288 // as the new (binary) response are categorical
289 cvSetReal1D( var_type, var_count, CV_VAR_CATEGORICAL );
290 cvSetReal1D( var_type, var_count+1, CV_VAR_CATEGORICAL );
292 // 3. train classifier
293 printf( "Training the classifier (may take a few minutes)...");
294 boost.train( new_data, CV_ROW_SAMPLE, new_responses, 0, 0, var_type, 0,
295 CvBoostParams(CvBoost::REAL, 100, 0.95, 5, false, 0 ));
296 cvReleaseMat( &new_data );
297 cvReleaseMat( &new_responses );
301 temp_sample = cvCreateMat( 1, var_count + 1, CV_32F );
302 weak_responses = cvCreateMat( 1, boost.get_weak_predictors()->total, CV_32F );
304 // compute prediction error on train and test data
305 for( i = 0; i < nsamples_all; i++ )
308 double max_sum = -DBL_MAX;
311 cvGetRow( data, &sample, i );
312 for( k = 0; k < var_count; k++ )
313 temp_sample->data.fl[k] = sample.data.fl[k];
315 for( j = 0; j < class_count; j++ )
317 temp_sample->data.fl[var_count] = (float)j;
318 boost.predict( temp_sample, 0, weak_responses );
319 double sum = cvSum( weak_responses ).val[0];
323 best_class = j + 'A';
327 r = fabs(best_class - responses->data.fl[i]) < FLT_EPSILON ? 1 : 0;
329 if( i < ntrain_samples )
335 test_hr /= (double)(nsamples_all-ntrain_samples);
336 train_hr /= (double)ntrain_samples;
337 printf( "Recognition rate: train = %.1f%%, test = %.1f%%\n",
338 train_hr*100., test_hr*100. );
340 printf( "Number of trees: %d\n", boost.get_weak_predictors()->total );
342 // Save classifier to file if needed
343 if( filename_to_save )
344 boost.save( filename_to_save );
346 cvReleaseMat( &temp_sample );
347 cvReleaseMat( &weak_responses );
348 cvReleaseMat( &var_type );
349 cvReleaseMat( &data );
350 cvReleaseMat( &responses );
357 int build_mlp_classifier( char* data_filename,
358 char* filename_to_save, char* filename_to_load )
360 const int class_count = 26;
363 CvMat* responses = 0;
364 CvMat* mlp_response = 0;
366 int ok = read_num_class_data( data_filename, 16, &data, &responses );
367 int nsamples_all = 0, ntrain_samples = 0;
369 double train_hr = 0, test_hr = 0;
374 printf( "Could not read the database %s\n", data_filename );
378 printf( "The database %s is loaded.\n", data_filename );
379 nsamples_all = data->rows;
380 ntrain_samples = (int)(nsamples_all*0.8);
382 // Create or load MLP classifier
383 if( filename_to_load )
385 // load classifier from the specified file
386 mlp.load( filename_to_load );
388 if( !mlp.get_layer_count() )
390 printf( "Could not read the classifier %s\n", filename_to_load );
393 printf( "The classifier %s is loaded.\n", data_filename );
397 // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
399 // MLP does not support categorical variables by explicitly.
400 // So, instead of the output class label, we will use
401 // a binary vector of <class_count> components for training and,
402 // therefore, MLP will give us a vector of "probabilities" at the
405 // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
407 CvMat* new_responses = cvCreateMat( ntrain_samples, class_count, CV_32F );
409 // 1. unroll the responses
410 printf( "Unrolling the responses...\n");
411 for( i = 0; i < ntrain_samples; i++ )
413 int cls_label = cvRound(responses->data.fl[i]) - 'A';
414 float* bit_vec = (float*)(new_responses->data.ptr + i*new_responses->step);
415 for( j = 0; j < class_count; j++ )
417 bit_vec[cls_label] = 1.f;
419 cvGetRows( data, &train_data, 0, ntrain_samples );
421 // 2. train classifier
422 int layer_sz[] = { data->cols, 100, 100, class_count };
424 cvMat( 1, (int)(sizeof(layer_sz)/sizeof(layer_sz[0])), CV_32S, layer_sz );
425 mlp.create( &layer_sizes );
426 printf( "Training the classifier (may take a few minutes)...");
427 mlp.train( &train_data, new_responses, 0, 0,
428 CvANN_MLP_TrainParams(cvTermCriteria(CV_TERMCRIT_ITER,300,0.01),
429 CvANN_MLP_TrainParams::RPROP,0.01));
430 cvReleaseMat( &new_responses );
434 mlp_response = cvCreateMat( 1, class_count, CV_32F );
436 // compute prediction error on train and test data
437 for( i = 0; i < nsamples_all; i++ )
441 cvGetRow( data, &sample, i );
442 CvPoint max_loc = {0,0};
443 mlp.predict( &sample, mlp_response );
444 cvMinMaxLoc( mlp_response, 0, 0, 0, &max_loc, 0 );
445 best_class = max_loc.x + 'A';
447 int r = fabs((double)best_class - responses->data.fl[i]) < FLT_EPSILON ? 1 : 0;
449 if( i < ntrain_samples )
455 test_hr /= (double)(nsamples_all-ntrain_samples);
456 train_hr /= (double)ntrain_samples;
457 printf( "Recognition rate: train = %.1f%%, test = %.1f%%\n",
458 train_hr*100., test_hr*100. );
460 // Save classifier to file if needed
461 if( filename_to_save )
462 mlp.save( filename_to_save );
464 cvReleaseMat( &mlp_response );
465 cvReleaseMat( &data );
466 cvReleaseMat( &responses );
472 int main( int argc, char *argv[] )
474 char* filename_to_save = 0;
475 char* filename_to_load = 0;
476 char default_data_filename[] = "./letter-recognition.data";
477 char* data_filename = default_data_filename;
481 for( i = 1; i < argc; i++ )
483 if( strcmp(argv[i],"-data") == 0 ) // flag "-data letter_recognition.xml"
486 data_filename = argv[i];
488 else if( strcmp(argv[i],"-save") == 0 ) // flag "-save filename.xml"
491 filename_to_save = argv[i];
493 else if( strcmp(argv[i],"-load") == 0) // flag "-load filename.xml"
496 filename_to_load = argv[i];
498 else if( strcmp(argv[i],"-boost") == 0)
502 else if( strcmp(argv[i],"-mlp") == 0 )
512 build_rtrees_classifier( data_filename, filename_to_save, filename_to_load ) :
514 build_boost_classifier( data_filename, filename_to_save, filename_to_load ) :
516 build_mlp_classifier( data_filename, filename_to_save, filename_to_load ) :
519 printf("This is letter recognition sample.\n"
520 "The usage: letter_recog [-data <path to letter-recognition.data>] \\\n"
521 " [-save <output XML file for the classifier>] \\\n"
522 " [-load <XML file with the pre-trained classifier>] \\\n"
523 " [-boost|-mlp] # to use boost/mlp classifier instead of default Random Trees\n" );