Monday, January 24, 2011

SVM in OpenCV

   

0.1,0.12,0.43,0.11,0.13,0
0.1,0.2,0.4,0.1,0.3,0
0.12,0.22,0.41,0.12,0.32,0
0.31,0.23,0.44,0.21,0.23,0
0.13,0.23,0.43,0.13,0.23,0
0.14,0.24,0.44,0.14,0.34,0
0.14,0.42,0.44,0.14,0.34,0
0.51,0.52,0.54,0.51,0.53,0
0.51,0.52,0.54,0.51,0.53,1
0.52,0.58,0.57,0.54,0.55,1
0.53,0.54,0.55,0.56,0.54,1
0.53,0.57,0.59,0.59,0.59,1
0.69,0.62,0.69,0.69,0.53,2
0.61,0.62,0.54,0.59,0.53,2
0.71,0.72,0.74,0.51,0.53,2
0.81,0.82,0.84,0.81,0.83,2
0.85,0.82,0.85,0.81,0.83,2
0.85,0.92,0.85,0.81,0.93,2
0.95,0.82,0.85,0.91,0.83,2

- last columns represent classes and first columns represent features


vector> descriptor;
    vector classes;
    ifstream f;
    f.open("c:\\bayes.txt");
    while(f)
    {
        string str = "";
        f>>str;
        vector desc;
        size_t found = str.find(",");
        while(found<100 && found>0)
        {
            string t = str.substr(0,found);
            desc.push_back(strtod(t.c_str(), NULL));
            str = str.substr(found+1);
            found = str.find(",");
        }
        if(desc.size()>0)
        {
            descriptor.push_back(desc);
            classes.push_back(strtod(str.c_str(), NULL));
        }
    }
    f.close();
   
    vector v;
    v.push_back(0.9481);
    v.push_back(0.9432);
    v.push_back(0.434);
    v.push_back(0.0531);
    v.push_back(0.533);
   
    int num_samples = descriptor.size();
    int num_features = descriptor[0].size();
   
    CvMat* data = cvCreateMat( num_samples, num_features, CV_32F );
    CvMat* responses = cvCreateMat( descriptor.size(), 1, CV_32F );
   
    for(int i=0;i
        {
          for(int j=0;j
             CV_MAT_ELEM(*data,float,i,j)=descriptor[i][j];
         CV_MAT_ELEM(*responses,float,i,0)=classes[i];
        }
       
       
   // initialize parameters
   CvTermCriteria crit;
   crit.epsilon = CV_TERMCRIT_EPS;
   crit.max_iter = 1000;
   crit.type = 1;
  
   CvSVMParams params;
  
   params.svm_type = CvSVM::C_SVC;
   params.kernel_type = CvSVM::RBF;
   params.gamma = 0.1;
   params.C = 3;
   params.nu = 0.1;
   params.term_crit = crit;
    

   CvMat* sample = cvCreateMat( 1,num_features, CV_32F );
   for(int j=0;j
             CV_MAT_ELEM(*sample,float,0,j)=v[j];

   CvSVM SVM;
   SVM.train(data,responses,0,0,params);
   float   r = SVM.predict( sample );
  
  
   SVM.clear();
   cvReleaseMat(&sample);
   cvReleaseMat(&data);
   cvReleaseMat(&responses); 

No comments:

Post a Comment