1 #include "opencv2/core/core_c.h"
2 #include "opencv2/ml/ml.hpp"
7 printf("\nThis program demonstrated the use of OpenCV's decision tree function for learning and predicting data\n"
9 "./mushroom <path to agaricus-lepiota.data>\n"
11 "The sample demonstrates how to build a decision tree for classifying mushrooms.\n"
12 "It uses the sample base agaricus-lepiota.data from UCI Repository, here is the link:\n"
14 "Newman, D.J. & Hettich, S. & Blake, C.L. & Merz, C.J. (1998).\n"
15 "UCI Repository of machine learning databases\n"
16 "[http://www.ics.uci.edu/~mlearn/MLRepository.html].\n"
17 "Irvine, CA: University of California, Department of Information and Computer Science.\n"
19 "// loads the mushroom database, which is a text file, containing\n"
20 "// one training sample per row, all the input variables and the output variable are categorical,\n"
21 "// the values are encoded by characters.\n\n");
24 int mushroom_read_database( const char* filename, CvMat** data, CvMat** missing, CvMat** responses )
27 FILE* f = fopen( filename, "rt" );
28 CvMemStorage* storage;
33 int i, j, var_count = 0;
38 // read the first line and determine the number of variables
39 if( !fgets( buf, M, f ))
45 for( ptr = buf; *ptr != '\0'; ptr++ )
46 var_count += *ptr == ',';
47 assert( ptr - buf == (var_count+1)*2 );
49 // create temporary memory storage to store the whole database
50 el_ptr = new float[var_count+1];
51 storage = cvCreateMemStorage();
52 seq = cvCreateSeq( 0, sizeof(*seq), (var_count+1)*sizeof(float), storage );
56 for( i = 0; i <= var_count; i++ )
59 el_ptr[i] = c == '?' ? -1.f : (float)c;
61 if( i != var_count+1 )
63 cvSeqPush( seq, el_ptr );
64 if( !fgets( buf, M, f ) || !strchr( buf, ',' ) )
69 // allocate the output matrices and copy the base there
70 *data = cvCreateMat( seq->total, var_count, CV_32F );
71 *missing = cvCreateMat( seq->total, var_count, CV_8U );
72 *responses = cvCreateMat( seq->total, 1, CV_32F );
74 cvStartReadSeq( seq, &reader );
76 for( i = 0; i < seq->total; i++ )
78 const float* sdata = (float*)reader.ptr + 1;
79 float* ddata = data[0]->data.fl + var_count*i;
80 float* dr = responses[0]->data.fl + i;
81 uchar* dm = missing[0]->data.ptr + var_count*i;
83 for( j = 0; j < var_count; j++ )
89 CV_NEXT_SEQ_ELEM( seq->elem_size, reader );
92 cvReleaseMemStorage( &storage );
98 CvDTree* mushroom_create_dtree( const CvMat* data, const CvMat* missing,
99 const CvMat* responses, float p_weight )
103 int i, hr1 = 0, hr2 = 0, p_total = 0;
104 float priors[] = { 1, p_weight };
106 var_type = cvCreateMat( data->cols + 1, 1, CV_8U );
107 cvSet( var_type, cvScalarAll(CV_VAR_CATEGORICAL) ); // all the variables are categorical
111 dtree->train( data, CV_ROW_SAMPLE, responses, 0, 0, var_type, missing,
112 CvDTreeParams( 8, // max depth
113 10, // min sample count
114 0, // regression accuracy: N/A here
115 true, // compute surrogate split, as we have missing data
116 15, // max number of categories (use sub-optimal algorithm for larger numbers)
117 10, // the number of cross-validation folds
118 true, // use 1SE rule => smaller tree
119 true, // throw away the pruned tree branches
120 priors // the array of priors, the bigger p_weight, the more attention
121 // to the poisonous mushrooms
122 // (a mushroom will be judjed to be poisonous with bigger chance)
125 // compute hit-rate on the training database, demonstrates predict usage.
126 for( i = 0; i < data->rows; i++ )
129 cvGetRow( data, &sample, i );
130 cvGetRow( missing, &mask, i );
131 double r = dtree->predict( &sample, &mask )->value;
132 int d = fabs(r - responses->data.fl[i]) >= FLT_EPSILON;
140 p_total += responses->data.fl[i] == 'p';
143 printf( "Results on the training database:\n"
144 "\tPoisonous mushrooms mis-predicted: %d (%g%%)\n"
145 "\tFalse-alarms: %d (%g%%)\n", hr1, (double)hr1*100/p_total,
146 hr2, (double)hr2*100/(data->rows - p_total) );
148 cvReleaseMat( &var_type );
154 static const char* var_desc[] =
156 "cap shape (bell=b,conical=c,convex=x,flat=f)",
157 "cap surface (fibrous=f,grooves=g,scaly=y,smooth=s)",
158 "cap color (brown=n,buff=b,cinnamon=c,gray=g,green=r,\n\tpink=p,purple=u,red=e,white=w,yellow=y)",
159 "bruises? (bruises=t,no=f)",
160 "odor (almond=a,anise=l,creosote=c,fishy=y,foul=f,\n\tmusty=m,none=n,pungent=p,spicy=s)",
161 "gill attachment (attached=a,descending=d,free=f,notched=n)",
162 "gill spacing (close=c,crowded=w,distant=d)",
163 "gill size (broad=b,narrow=n)",
164 "gill color (black=k,brown=n,buff=b,chocolate=h,gray=g,\n\tgreen=r,orange=o,pink=p,purple=u,red=e,white=w,yellow=y)",
165 "stalk shape (enlarging=e,tapering=t)",
166 "stalk root (bulbous=b,club=c,cup=u,equal=e,rhizomorphs=z,rooted=r)",
167 "stalk surface above ring (ibrous=f,scaly=y,silky=k,smooth=s)",
168 "stalk surface below ring (ibrous=f,scaly=y,silky=k,smooth=s)",
169 "stalk color above ring (brown=n,buff=b,cinnamon=c,gray=g,orange=o,\n\tpink=p,red=e,white=w,yellow=y)",
170 "stalk color below ring (brown=n,buff=b,cinnamon=c,gray=g,orange=o,\n\tpink=p,red=e,white=w,yellow=y)",
171 "veil type (partial=p,universal=u)",
172 "veil color (brown=n,orange=o,white=w,yellow=y)",
173 "ring number (none=n,one=o,two=t)",
174 "ring type (cobwebby=c,evanescent=e,flaring=f,large=l,\n\tnone=n,pendant=p,sheathing=s,zone=z)",
175 "spore print color (black=k,brown=n,buff=b,chocolate=h,green=r,\n\torange=o,purple=u,white=w,yellow=y)",
176 "population (abundant=a,clustered=c,numerous=n,\n\tscattered=s,several=v,solitary=y)",
177 "habitat (grasses=g,leaves=l,meadows=m,paths=p\n\turban=u,waste=w,woods=d)",
182 void print_variable_importance( CvDTree* dtree, const char** var_desc )
184 const CvMat* var_importance = dtree->get_var_importance();
188 if( !var_importance )
190 printf( "Error: Variable importance can not be retrieved\n" );
194 printf( "Print variable importance information? (y/n) " );
195 scanf( "%1s", input );
196 if( input[0] != 'y' && input[0] != 'Y' )
199 for( i = 0; i < var_importance->cols*var_importance->rows; i++ )
201 double val = var_importance->data.db[i];
205 int len = (int)(strchr( var_desc[i], '(' ) - var_desc[i] - 1);
206 strncpy( buf, var_desc[i], len );
211 printf( "var #%d", i );
212 printf( ": %g%%\n", val*100. );
216 void interactive_classification( CvDTree* dtree, const char** var_desc )
219 const CvDTreeNode* root;
220 CvDTreeTrainData* data;
225 root = dtree->get_root();
226 data = dtree->get_data();
230 const CvDTreeNode* node;
232 printf( "Start/Proceed with interactive mushroom classification (y/n): " );
233 scanf( "%1s", input );
234 if( input[0] != 'y' && input[0] != 'Y' )
236 printf( "Enter 1-letter answers, '?' for missing/unknown value...\n" );
238 // custom version of predict
242 CvDTreeSplit* split = node->split;
245 if( !node->left || node->Tn <= dtree->get_pruned_tree_idx() || !node->split )
250 int vi = split->var_idx, j;
251 int count = data->cat_count->data.i[vi];
252 const int* map = data->cat_map->data.i + data->cat_ofs->data.i[vi];
254 printf( "%s: ", var_desc[vi] );
255 scanf( "%1s", input );
257 if( input[0] == '?' )
263 // convert the input character to the normalized value of the variable
264 for( j = 0; j < count; j++ )
265 if( map[j] == input[0] )
269 dir = (split->subset[j>>5] & (1 << (j&31))) ? -1 : 1;
270 if( split->inversed )
275 printf( "Error: unrecognized value\n" );
280 printf( "Impossible to classify the sample\n");
284 node = dir < 0 ? node->left : node->right;
288 printf( "Prediction result: the mushroom is %s\n",
289 node->class_idx == 0 ? "EDIBLE" : "POISONOUS" );
290 printf( "\n-----------------------------\n" );
295 int main( int argc, char** argv )
297 CvMat *data = 0, *missing = 0, *responses = 0;
299 const char* base_path = argc >= 2 ? argv[1] : "agaricus-lepiota.data";
303 if( !mushroom_read_database( base_path, &data, &missing, &responses ) )
305 printf( "\nUnable to load the training database\n\n");
310 dtree = mushroom_create_dtree( data, missing, responses,
311 10 // poisonous mushrooms will have 10x higher weight in the decision tree
313 cvReleaseMat( &data );
314 cvReleaseMat( &missing );
315 cvReleaseMat( &responses );
317 print_variable_importance( dtree, var_desc );
318 interactive_classification( dtree, var_desc );