| 71 | } |
| 72 | |
| 73 | void SimpleSVM::setup(PredictorMap& predictors, const map<Size, double>& outcomes, bool classification) |
| 74 | { |
| 75 | if (predictors.empty() || predictors.begin()->second.empty()) |
| 76 | { |
| 77 | throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, |
| 78 | "Predictors for SVM must not be empty."); |
| 79 | } |
| 80 | |
| 81 | // count elements for first feature dimension to determine number of observations |
| 82 | Size n_obs = predictors.begin()->second.size(); |
| 83 | n_parts_ = param_.getValue("xval"); |
| 84 | |
| 85 | // clear old models |
| 86 | clear_(); |
| 87 | |
| 88 | scaleData_(predictors); |
| 89 | convertData_(predictors); |
| 90 | |
| 91 | data_.l = outcomes.size(); |
| 92 | data_.x = new svm_node*[data_.l]; |
| 93 | data_.y = new double[data_.l]; |
| 94 | map<double, Size> label_table; |
| 95 | Size index = 0; |
| 96 | for (auto it = outcomes.cbegin(); it != outcomes.cend(); |
| 97 | ++it, ++index) |
| 98 | { |
| 99 | const Size& training_index = it->first; |
| 100 | const double& outcome = it->second; |
| 101 | if (it->first >= n_obs) |
| 102 | { |
| 103 | String msg = "Invalid training index; there are only " + String(n_obs) + |
| 104 | " observations."; |
| 105 | throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, |
| 106 | msg, String(it->first)); |
| 107 | } |
| 108 | data_.x[index] = &(nodes_[training_index][0]); |
| 109 | data_.y[index] = outcome; |
| 110 | label_table[outcome]++; |
| 111 | } |
| 112 | |
| 113 | if (classification) |
| 114 | { |
| 115 | // check for 2 or more classes |
| 116 | if (label_table.size() < 2) |
| 117 | { |
| 118 | throw Exception::MissingInformation(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, |
| 119 | "Need at least two classes (distinct " |
| 120 | "labels) for SVM classification."); |
| 121 | } |
| 122 | |
| 123 | String msg = "Training SVM on " + String(data_.l) + " observations. Classes:"; |
| 124 | for (map<double, Size>::iterator it = label_table.begin(); |
| 125 | it != label_table.end(); ++it) |
| 126 | { |
| 127 | if (it->second < n_parts_) |
| 128 | { |
| 129 | msg = "Not enough observations of class " + String(it->first) + " for " + |
| 130 | String(n_parts_) + "-fold cross-validation."; |