5 The sample demonstrates how to build a decision tree for classifying mushrooms.
6 It uses the sample base agaricus-lepiota.data from UCI Repository, here is the link:
8 Newman, D.J. & Hettich, S. & Blake, C.L. & Merz, C.J. (1998).
9 UCI Repository of machine learning databases
10 [http://www.ics.uci.edu/~mlearn/MLRepository.html].
11 Irvine, CA: University of California, Department of Information and Computer Science.
14 // loads the mushroom database, which is a text file, containing
15 // one training sample per row, all the input variables and the output variable are categorical,
16 // the values are encoded by characters.
17 int mushroom_read_database( const char* filename, CvMat** data, CvMat** missing, CvMat** responses )
20 FILE* f = fopen( filename, "rt" );
21 CvMemStorage* storage;
26 int i, j, var_count = 0;
31 // read the first line and determine the number of variables
32 if( !fgets( buf, M, f ))
38 for( ptr = buf; *ptr != '\0'; ptr++ )
39 var_count += *ptr == ',';
40 assert( ptr - buf == (var_count+1)*2 );
42 // create temporary memory storage to store the whole database
43 el_ptr = new float[var_count+1];
44 storage = cvCreateMemStorage();
45 seq = cvCreateSeq( 0, sizeof(*seq), (var_count+1)*sizeof(float), storage );
49 for( i = 0; i <= var_count; i++ )
52 el_ptr[i] = c == '?' ? -1.f : (float)c;
54 if( i != var_count+1 )
56 cvSeqPush( seq, el_ptr );
57 if( !fgets( buf, M, f ) || !strchr( buf, ',' ) )
62 // allocate the output matrices and copy the base there
63 *data = cvCreateMat( seq->total, var_count, CV_32F );
64 *missing = cvCreateMat( seq->total, var_count, CV_8U );
65 *responses = cvCreateMat( seq->total, 1, CV_32F );
67 cvStartReadSeq( seq, &reader );
69 for( i = 0; i < seq->total; i++ )
71 const float* sdata = (float*)reader.ptr + 1;
72 float* ddata = data[0]->data.fl + var_count*i;
73 float* dr = responses[0]->data.fl + i;
74 uchar* dm = missing[0]->data.ptr + var_count*i;
76 for( j = 0; j < var_count; j++ )
82 CV_NEXT_SEQ_ELEM( seq->elem_size, reader );
85 cvReleaseMemStorage( &storage );
91 CvDTree* mushroom_create_dtree( const CvMat* data, const CvMat* missing,
92 const CvMat* responses, float p_weight )
96 int i, hr1 = 0, hr2 = 0, p_total = 0;
97 float priors[] = { 1, p_weight };
99 var_type = cvCreateMat( data->cols + 1, 1, CV_8U );
100 cvSet( var_type, cvScalarAll(CV_VAR_CATEGORICAL) ); // all the variables are categorical
104 dtree->train( data, CV_ROW_SAMPLE, responses, 0, 0, var_type, missing,
105 CvDTreeParams( 8, // max depth
106 10, // min sample count
107 0, // regression accuracy: N/A here
108 true, // compute surrogate split, as we have missing data
109 15, // max number of categories (use sub-optimal algorithm for larger numbers)
110 10, // the number of cross-validation folds
111 true, // use 1SE rule => smaller tree
112 true, // throw away the pruned tree branches
113 priors // the array of priors, the bigger p_weight, the more attention
114 // to the poisonous mushrooms
115 // (a mushroom will be judjed to be poisonous with bigger chance)
118 // compute hit-rate on the training database, demonstrates predict usage.
119 for( i = 0; i < data->rows; i++ )
122 cvGetRow( data, &sample, i );
123 cvGetRow( missing, &mask, i );
124 double r = dtree->predict( &sample, &mask )->value;
125 int d = fabs(r - responses->data.fl[i]) >= FLT_EPSILON;
133 p_total += responses->data.fl[i] == 'p';
136 printf( "Results on the training database:\n"
137 "\tPoisonous mushrooms mis-predicted: %d (%g%%)\n"
138 "\tFalse-alarms: %d (%g%%)\n", hr1, (double)hr1*100/p_total,
139 hr2, (double)hr2*100/(data->rows - p_total) );
141 cvReleaseMat( &var_type );
147 static const char* var_desc[] =
149 "cap shape (bell=b,conical=c,convex=x,flat=f)",
150 "cap surface (fibrous=f,grooves=g,scaly=y,smooth=s)",
151 "cap color (brown=n,buff=b,cinnamon=c,gray=g,green=r,\n\tpink=p,purple=u,red=e,white=w,yellow=y)",
152 "bruises? (bruises=t,no=f)",
153 "odor (almond=a,anise=l,creosote=c,fishy=y,foul=f,\n\tmusty=m,none=n,pungent=p,spicy=s)",
154 "gill attachment (attached=a,descending=d,free=f,notched=n)",
155 "gill spacing (close=c,crowded=w,distant=d)",
156 "gill size (broad=b,narrow=n)",
157 "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)",
158 "stalk shape (enlarging=e,tapering=t)",
159 "stalk root (bulbous=b,club=c,cup=u,equal=e,rhizomorphs=z,rooted=r)",
160 "stalk surface above ring (ibrous=f,scaly=y,silky=k,smooth=s)",
161 "stalk surface below ring (ibrous=f,scaly=y,silky=k,smooth=s)",
162 "stalk color above ring (brown=n,buff=b,cinnamon=c,gray=g,orange=o,\n\tpink=p,red=e,white=w,yellow=y)",
163 "stalk color below ring (brown=n,buff=b,cinnamon=c,gray=g,orange=o,\n\tpink=p,red=e,white=w,yellow=y)",
164 "veil type (partial=p,universal=u)",
165 "veil color (brown=n,orange=o,white=w,yellow=y)",
166 "ring number (none=n,one=o,two=t)",
167 "ring type (cobwebby=c,evanescent=e,flaring=f,large=l,\n\tnone=n,pendant=p,sheathing=s,zone=z)",
168 "spore print color (black=k,brown=n,buff=b,chocolate=h,green=r,\n\torange=o,purple=u,white=w,yellow=y)",
169 "population (abundant=a,clustered=c,numerous=n,\n\tscattered=s,several=v,solitary=y)",
170 "habitat (grasses=g,leaves=l,meadows=m,paths=p\n\turban=u,waste=w,woods=d)",
175 void print_variable_importance( CvDTree* dtree, const char** var_desc )
177 const CvMat* var_importance = dtree->get_var_importance();
181 if( !var_importance )
183 printf( "Error: Variable importance can not be retrieved\n" );
187 printf( "Print variable importance information? (y/n) " );
188 scanf( "%1s", input );
189 if( input[0] != 'y' && input[0] != 'Y' )
192 for( i = 0; i < var_importance->cols*var_importance->rows; i++ )
194 double val = var_importance->data.db[i];
198 int len = strchr( var_desc[i], '(' ) - var_desc[i] - 1;
199 strncpy( buf, var_desc[i], len );
204 printf( "var #%d", i );
205 printf( ": %g%%\n", val*100. );
209 void interactive_classification( CvDTree* dtree, const char** var_desc )
212 const CvDTreeNode* root;
213 CvDTreeTrainData* data;
218 root = dtree->get_root();
219 data = dtree->get_data();
223 const CvDTreeNode* node;
225 printf( "Start/Proceed with interactive mushroom classification (y/n): " );
226 scanf( "%1s", input );
227 if( input[0] != 'y' && input[0] != 'Y' )
229 printf( "Enter 1-letter answers, '?' for missing/unknown value...\n" );
231 // custom version of predict
235 CvDTreeSplit* split = node->split;
238 if( !node->left || node->Tn <= dtree->get_pruned_tree_idx() || !node->split )
243 int vi = split->var_idx, j;
244 int count = data->cat_count->data.i[vi];
245 const int* map = data->cat_map->data.i + data->cat_ofs->data.i[vi];
247 printf( "%s: ", var_desc[vi] );
248 scanf( "%1s", input );
250 if( input[0] == '?' )
256 // convert the input character to the normalized value of the variable
257 for( j = 0; j < count; j++ )
258 if( map[j] == input[0] )
262 dir = (split->subset[j>>5] & (1 << (j&31))) ? -1 : 1;
263 if( split->inversed )
268 printf( "Error: unrecognized value\n" );
273 printf( "Impossible to classify the sample\n");
277 node = dir < 0 ? node->left : node->right;
281 printf( "Prediction result: the mushroom is %s\n",
282 node->class_idx == 0 ? "EDIBLE" : "POISONOUS" );
283 printf( "\n-----------------------------\n" );
288 int main( int argc, char** argv )
290 CvMat *data = 0, *missing = 0, *responses = 0;
292 const char* base_path = argc >= 2 ? argv[1] : "agaricus-lepiota.data";
294 if( !mushroom_read_database( base_path, &data, &missing, &responses ) )
296 printf( "Unable to load the training database\n"
297 "Pass it as a parameter: dtree <path to agaricus-lepiota.data>\n" );
302 dtree = mushroom_create_dtree( data, missing, responses,
303 10 // poisonous mushrooms will have 10x higher weight in the decision tree
305 cvReleaseMat( &data );
306 cvReleaseMat( &missing );
307 cvReleaseMat( &responses );
309 print_variable_importance( dtree, var_desc );
310 interactive_classification( dtree, var_desc );