Move the sources to trunk
[opencv] / samples / c / mushroom.cpp
1 #include "ml.h"
2 #include <stdio.h>
3
4 /*
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:
7
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.
12 */
13
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 )
18 {
19     const int M = 1024;
20     FILE* f = fopen( filename, "rt" );
21     CvMemStorage* storage;
22     CvSeq* seq;
23     char buf[M+2], *ptr;
24     float* el_ptr;
25     CvSeqReader reader;
26     int i, j, var_count = 0;
27
28     if( !f )
29         return 0;
30
31     // read the first line and determine the number of variables
32     if( !fgets( buf, M, f ))
33     {
34         fclose(f);
35         return 0;
36     }
37
38     for( ptr = buf; *ptr != '\0'; ptr++ )
39         var_count += *ptr == ',';
40     assert( ptr - buf == (var_count+1)*2 );
41
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 );
46
47     for(;;)
48     {
49         for( i = 0; i <= var_count; i++ )
50         {
51             int c = buf[i*2];
52             el_ptr[i] = c == '?' ? -1.f : (float)c;
53         }
54         if( i != var_count+1 )
55             break;
56         cvSeqPush( seq, el_ptr );
57         if( !fgets( buf, M, f ) || !strchr( buf, ',' ) )
58             break;
59     }
60     fclose(f);
61
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 );
66
67     cvStartReadSeq( seq, &reader );
68
69     for( i = 0; i < seq->total; i++ )
70     {
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;
75
76         for( j = 0; j < var_count; j++ )
77         {
78             ddata[j] = sdata[j];
79             dm[j] = sdata[j] < 0;
80         }
81         *dr = sdata[-1];
82         CV_NEXT_SEQ_ELEM( seq->elem_size, reader );
83     }
84
85     cvReleaseMemStorage( &storage );
86     delete el_ptr;
87     return 1;
88 }
89
90
91 CvDTree* mushroom_create_dtree( const CvMat* data, const CvMat* missing,
92                                 const CvMat* responses, float p_weight )
93 {
94     CvDTree* dtree;
95     CvMat* var_type;
96     int i, hr1 = 0, hr2 = 0, p_total = 0;
97     float priors[] = { 1, p_weight };
98
99     var_type = cvCreateMat( data->cols + 1, 1, CV_8U );
100     cvSet( var_type, cvScalarAll(CV_VAR_CATEGORICAL) ); // all the variables are categorical
101
102     dtree = new CvDTree;
103     
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)
116                                  ));
117
118     // compute hit-rate on the training database, demonstrates predict usage.
119     for( i = 0; i < data->rows; i++ )
120     {
121         CvMat sample, mask;
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;
126         if( d )
127         {
128             if( r != 'p' )
129                 hr1++;
130             else
131                 hr2++;
132         }
133         p_total += responses->data.fl[i] == 'p';
134     }
135
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) );
140
141     cvReleaseMat( &var_type );
142
143     return dtree;
144 }
145
146
147 static const char* var_desc[] =
148 {
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)",
171     0
172 };
173
174
175 void print_variable_importance( CvDTree* dtree, const char** var_desc )
176 {
177     const CvMat* var_importance = dtree->get_var_importance();
178     int i;
179     char input[1000];
180
181     if( !var_importance )
182     {
183         printf( "Error: Variable importance can not be retrieved\n" );
184         return;
185     }
186
187     printf( "Print variable importance information? (y/n) " );
188     scanf( "%1s", input );
189     if( input[0] != 'y' && input[0] != 'Y' )
190         return;
191
192     for( i = 0; i < var_importance->cols*var_importance->rows; i++ )
193     {
194         double val = var_importance->data.db[i];
195         if( var_desc )
196         {
197             char buf[100];
198             int len = strchr( var_desc[i], '(' ) - var_desc[i] - 1;
199             strncpy( buf, var_desc[i], len );
200             buf[len] = '\0';
201             printf( "%s", buf );
202         }
203         else
204             printf( "var #%d", i );
205         printf( ": %g%%\n", val*100. );
206     }
207 }
208
209 void interactive_classification( CvDTree* dtree, const char** var_desc )
210 {
211     char input[1000];
212     const CvDTreeNode* root;
213     CvDTreeTrainData* data;
214
215     if( !dtree )
216         return;
217
218     root = dtree->get_root();
219     data = dtree->get_data();
220
221     for(;;)
222     {
223         const CvDTreeNode* node;
224         
225         printf( "Start/Proceed with interactive mushroom classification (y/n): " );
226         scanf( "%1s", input );
227         if( input[0] != 'y' && input[0] != 'Y' )
228             break;
229         printf( "Enter 1-letter answers, '?' for missing/unknown value...\n" ); 
230
231         // custom version of predict
232         node = root;
233         for(;;)
234         {
235             CvDTreeSplit* split = node->split;
236             int dir = 0;
237             
238             if( !node->left || node->Tn <= dtree->get_pruned_tree_idx() || !node->split )
239                 break;
240
241             for( ; split != 0; )
242             {
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];
246
247                 printf( "%s: ", var_desc[vi] );
248                 scanf( "%1s", input );
249
250                 if( input[0] == '?' )
251                 {
252                     split = split->next;
253                     continue;
254                 }
255
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] )
259                         break;
260                 if( j < count )
261                 {
262                     dir = (split->subset[j>>5] & (1 << (j&31))) ? -1 : 1;
263                     if( split->inversed )
264                         dir = -dir;
265                     break;
266                 }
267                 else
268                     printf( "Error: unrecognized value\n" );
269             }
270             
271             if( !dir )
272             {
273                 printf( "Impossible to classify the sample\n");
274                 node = 0;
275                 break;
276             }
277             node = dir < 0 ? node->left : node->right;
278         }
279
280         if( node )
281             printf( "Prediction result: the mushroom is %s\n",
282                     node->class_idx == 0 ? "EDIBLE" : "POISONOUS" );
283         printf( "\n-----------------------------\n" );
284     }
285 }
286
287
288 int main( int argc, char** argv )
289 {
290     CvMat *data = 0, *missing = 0, *responses = 0;
291     CvDTree* dtree;
292     const char* base_path = argc >= 2 ? argv[1] : "agaricus-lepiota.data";
293
294     if( !mushroom_read_database( base_path, &data, &missing, &responses ) )
295     {
296         printf( "Unable to load the training database\n"
297                 "Pass it as a parameter: dtree <path to agaricus-lepiota.data>\n" );
298         return 0;
299         return -1;
300     }
301
302     dtree = mushroom_create_dtree( data, missing, responses,
303         10 // poisonous mushrooms will have 10x higher weight in the decision tree
304         );
305     cvReleaseMat( &data );
306     cvReleaseMat( &missing );
307     cvReleaseMat( &responses );
308
309     print_variable_importance( dtree, var_desc );
310     interactive_classification( dtree, var_desc );
311     delete dtree;
312
313     return 0;
314 }