1 ///////////////////////////////////////////////////////////////////////////////////////
2 // sample_logistic_regression.cpp
3 // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
5 // By downloading, copying, installing or using the software you agree to this license.
6 // If you do not agree to this license, do not download, install,
7 // copy or use the software.
9 // This is a sample program demostrating classification of digits 0 and 1 using Logistic Regression
12 // Rahul Kavi rahulkavi[at]live[at]com
17 #include <opencv2/core/core.hpp>
18 #include <opencv2/ml/ml.hpp>
26 Mat data_temp, labels_temp;
28 Mat responses, result;
32 cout<<"*****************************************************************************************"<<endl;
33 cout<<"\"data01.xml\" contains digits 0 and 1 of 20 samples each, collected on an Android device"<<endl;
34 cout<<"Each of the collected images are of size 28 x 28 re-arranged to 1 x 784 matrix"<<endl;
35 cout<<"*****************************************************************************************\n\n"<<endl;
37 cout<<"loading the dataset\n"<<endl;
39 f.open("data01.xml", FileStorage::READ);
41 f["datamat"] >> data_temp;
42 f["labelsmat"] >> labels_temp;
44 data_temp.convertTo(data, CV_32F);
45 labels_temp.convertTo(labels, CV_32F);
47 cout<<"initializing Logisitc Regression Parameters\n"<<endl;
49 CvLR_TrainParams params = CvLR_TrainParams();
52 params.num_iters = 10;
53 params.norm = CvLR::REG_L2;
54 params.regularized = 1;
55 params.train_method = CvLR::BATCH;
57 cout<<"training Logisitc Regression classifier\n"<<endl;
59 CvLR lr_(data, labels, params);
61 cout<<"predicting the trained dataset\n"<<endl;
63 lr_.predict(data, responses);
65 labels.convertTo(labels, CV_32S);
67 cout<<"Original Label :: Predicted Label"<<endl;
68 result = (labels == responses)/255;
69 for(int i=0;i<labels.rows;i++)
71 cout<<labels.at<int>(i,0)<<" :: "<< responses.at<int>(i,0)<<endl;
74 cout<<"accuracy: "<<((double)cv::sum(result)[0]/result.rows)*100<<"%\n";
77 lr_.save("NewLR_Trained.xml");
79 // load the classifier onto new object
81 cout<<"loading a new classifier"<<endl;
83 lr2.load("NewLR_Trained.xml");
87 // predict using loaded classifier
88 cout<<"predicting the dataset using the loaded classfier\n"<<endl;
90 lr2.predict(data, responses2);
93 result = (labels == responses2)/255;
94 cout<<"accuracy using loaded classifier: "<<((double)cv::sum(result)[0]/result.rows)*100<<"%\n";