| 27 | |
| 28 | |
| 29 | int main() try |
| 30 | { |
| 31 | // The svm functions use column vectors to contain a lot of the data on which they |
| 32 | // operate. So the first thing we do here is declare a convenient typedef. |
| 33 | |
| 34 | // This typedef declares a matrix with 2 rows and 1 column. It will be the |
| 35 | // object that contains each of our 2 dimensional samples. |
| 36 | typedef matrix<double, 2, 1> sample_type; |
| 37 | |
| 38 | |
| 39 | |
| 40 | // Now we make objects to contain our samples and their respective labels. |
| 41 | std::vector<sample_type> samples; |
| 42 | std::vector<double> labels; |
| 43 | |
| 44 | // Now let's put some data into our samples and labels objects. We do this |
| 45 | // by looping over a bunch of points and labeling them according to their |
| 46 | // distance from the origin. |
| 47 | for (double r = -20; r <= 20; r += 0.8) |
| 48 | { |
| 49 | for (double c = -20; c <= 20; c += 0.8) |
| 50 | { |
| 51 | sample_type samp; |
| 52 | samp(0) = r; |
| 53 | samp(1) = c; |
| 54 | samples.push_back(samp); |
| 55 | |
| 56 | // if this point is less than 10 from the origin |
| 57 | if (sqrt(r*r + c*c) <= 10) |
| 58 | labels.push_back(+1); |
| 59 | else |
| 60 | labels.push_back(-1); |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | cout << "Generated " << samples.size() << " points" << endl; |
| 65 | |
| 66 | |
| 67 | // Here we normalize all the samples by subtracting their mean and dividing by their |
| 68 | // standard deviation. This is generally a good idea since it often heads off |
| 69 | // numerical stability problems and also prevents one large feature from smothering |
| 70 | // others. Doing this doesn't matter much in this example so I'm just doing this here |
| 71 | // so you can see an easy way to accomplish this with the library. |
| 72 | vector_normalizer<sample_type> normalizer; |
| 73 | // let the normalizer learn the mean and standard deviation of the samples |
| 74 | normalizer.train(samples); |
| 75 | // now normalize each sample |
| 76 | for (unsigned long i = 0; i < samples.size(); ++i) |
| 77 | samples[i] = normalizer(samples[i]); |
| 78 | |
| 79 | |
| 80 | // Now that we have some data we want to train on it. We are going to train a |
| 81 | // binary SVM with the RBF kernel to classify the data. However, there are |
| 82 | // three parameters to the training. These are the SVM C parameters for each |
| 83 | // class and the RBF kernel's gamma parameter. Our choice for these |
| 84 | // parameters will influence how good the resulting decision function is. To |
| 85 | // test how good a particular choice of these parameters is we can use the |
| 86 | // cross_validate_trainer() function to perform n-fold cross validation on our |
nothing calls this directly
no test coverage detected