| 14 | { |
| 15 | |
| 16 | normalized_function<decision_function<radial_basis_kernel<matrix<double,0,1>>>> auto_train_rbf_classifier ( |
| 17 | std::vector<matrix<double,0,1>> x, |
| 18 | std::vector<double> y, |
| 19 | const std::chrono::nanoseconds max_runtime, |
| 20 | bool be_verbose |
| 21 | ) |
| 22 | { |
| 23 | const auto num_positive_training_samples = sum(mat(y)>0); |
| 24 | const auto num_negative_training_samples = sum(mat(y)<0); |
| 25 | DLIB_CASSERT(num_positive_training_samples >= 6 && num_negative_training_samples >= 6, |
| 26 | "You must provide at least 6 examples of each class to this training routine."); |
| 27 | // make sure requires clause is not broken |
| 28 | DLIB_CASSERT(is_binary_classification_problem(x,y) == true, |
| 29 | "\tdecision_function svm_c_trainer::train(x,y)" |
| 30 | << "\n\t invalid inputs were given to this function" |
| 31 | << "\n\t x.size(): " << x.size() |
| 32 | << "\n\t y.size(): " << y.size() |
| 33 | << "\n\t is_binary_classification_problem(x,y): " << is_binary_classification_problem(x,y) |
| 34 | ); |
| 35 | |
| 36 | |
| 37 | randomize_samples(x,y); |
| 38 | |
| 39 | using kernel_type = radial_basis_kernel<matrix<double,0,1>>; |
| 40 | normalized_function<decision_function<kernel_type>> df; |
| 41 | // let the normalizer learn the mean and standard deviation of the samples |
| 42 | df.normalizer.train(x); |
| 43 | for (auto& samp : x) |
| 44 | samp = df.normalizer(samp); |
| 45 | |
| 46 | |
| 47 | std::mutex m; |
| 48 | auto cross_validation_score = [&](const double gamma, const double c1, const double c2) |
| 49 | { |
| 50 | svm_c_trainer<kernel_type> trainer; |
| 51 | trainer.set_kernel(kernel_type(gamma)); |
| 52 | trainer.set_c_class1(c1); |
| 53 | trainer.set_c_class2(c2); |
| 54 | |
| 55 | // Finally, perform 6-fold cross validation and then print and return the results. |
| 56 | matrix<double> result = cross_validate_trainer(trainer, x, y, 6); |
| 57 | if (be_verbose) |
| 58 | { |
| 59 | std::lock_guard<std::mutex> lock(m); |
| 60 | std::cout << "gamma: " << std::setw(11) << gamma << " c1: " << std::setw(11) << c1 << " c2: " << std::setw(11) << c2 << " cross validation accuracy: " << result << std::flush; |
| 61 | } |
| 62 | |
| 63 | // return the f1 score plus a penalty for picking large parameter settings |
| 64 | // since those are, a priori less likely to generalize. |
| 65 | return 2*prod(result)/sum(result) - std::max(c1,c2)/1e12 - gamma/1e8; |
| 66 | }; |
| 67 | |
| 68 | |
| 69 | if (be_verbose) |
| 70 | std::cout << "Searching for best RBF-SVM training parameters..." << std::endl; |
| 71 | auto result = find_max_global( |
| 72 | default_thread_pool(), |
| 73 | cross_validation_score, |
no test coverage detected