svm-train.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <ctype.h>
  5. #include <errno.h>
  6. #include "svm.h"
  7. #define Malloc(type, n) (type *)malloc((n)*sizeof(type))
  8. void print_null(const char *s) {}
  9. void exit_with_help() {
  10. printf(
  11. "Usage: svm-train [options] training_set_file [model_file]\n"
  12. "options:\n"
  13. "-s svm_type : set type of SVM (default 0)\n"
  14. " 0 -- C-SVC (multi-class classification)\n"
  15. " 1 -- nu-SVC (multi-class classification)\n"
  16. " 2 -- one-class SVM\n"
  17. " 3 -- epsilon-SVR (regression)\n"
  18. " 4 -- nu-SVR (regression)\n"
  19. "-t kernel_type : set type of kernel function (default 2)\n"
  20. " 0 -- linear: u'*v\n"
  21. " 1 -- polynomial: (gamma*u'*v + coef0)^degree\n"
  22. " 2 -- radial basis function: exp(-gamma*|u-v|^2)\n"
  23. " 3 -- sigmoid: tanh(gamma*u'*v + coef0)\n"
  24. " 4 -- precomputed kernel (kernel values in training_set_file)\n"
  25. "-d degree : set degree in kernel function (default 3)\n"
  26. "-g gamma : set gamma in kernel function (default 1/num_features)\n"
  27. "-r coef0 : set coef0 in kernel function (default 0)\n"
  28. "-c cost : set the parameter C of C-SVC, epsilon-SVR, and nu-SVR (default 1)\n"
  29. "-n nu : set the parameter nu of nu-SVC, one-class SVM, and nu-SVR (default 0.5)\n"
  30. "-p epsilon : set the epsilon in loss function of epsilon-SVR (default 0.1)\n"
  31. "-m cachesize : set cache memory size in MB (default 100)\n"
  32. "-e epsilon : set tolerance of termination criterion (default 0.001)\n"
  33. "-h shrinking : whether to use the shrinking heuristics, 0 or 1 (default 1)\n"
  34. "-b probability_estimates : whether to train a SVC or SVR model for probability estimates, 0 or 1 (default 0)\n"
  35. "-wi weight : set the parameter C of class i to weight*C, for C-SVC (default 1)\n"
  36. "-v n: n-fold cross validation mode\n"
  37. "-q : quiet mode (no outputs)\n"
  38. );
  39. exit(1);
  40. }
  41. void exit_input_error(int line_num) {
  42. fprintf(stderr, "Wrong input format at line %d\n", line_num);
  43. exit(1);
  44. }
  45. void parse_command_line(int argc, char **argv, char *input_file_name, char *model_file_name);
  46. void read_problem(const char *filename);
  47. void do_cross_validation();
  48. struct svm_parameter param; // set by parse_command_line
  49. struct svm_problem prob; // set by read_problem
  50. struct svm_model *model;
  51. struct svm_node *x_space;
  52. int cross_validation;
  53. int nr_fold;
  54. static char *line = NULL;
  55. static int max_line_len;
  56. static char *readline(FILE *input) {
  57. int len;
  58. if (fgets(line, max_line_len, input) == NULL)
  59. return NULL;
  60. while (strrchr(line, '\n') == NULL) {
  61. max_line_len *= 2;
  62. line = (char *) realloc(line, max_line_len);
  63. len = (int) strlen(line);
  64. if (fgets(line + len, max_line_len - len, input) == NULL)
  65. break;
  66. }
  67. return line;
  68. }
  69. int main(int argc, char **argv) {
  70. char input_file_name[1024];
  71. char model_file_name[1024];
  72. const char *error_msg;
  73. parse_command_line(argc, argv, input_file_name, model_file_name);
  74. read_problem(input_file_name);
  75. error_msg = svm_check_parameter(&prob, &param);
  76. if (error_msg) {
  77. fprintf(stderr, "ERROR: %s\n", error_msg);
  78. exit(1);
  79. }
  80. if (cross_validation) {
  81. do_cross_validation();
  82. } else {
  83. model = svm_train(&prob, &param);
  84. if (svm_save_model(model_file_name, model)) {
  85. fprintf(stderr, "can't save model to file %s\n", model_file_name);
  86. exit(1);
  87. }
  88. svm_free_and_destroy_model(&model);
  89. }
  90. svm_destroy_param(&param);
  91. free(prob.y);
  92. free(prob.x);
  93. free(x_space);
  94. free(line);
  95. return 0;
  96. }
  97. void do_cross_validation() {
  98. int i;
  99. int total_correct = 0;
  100. double total_error = 0;
  101. double sumv = 0, sumy = 0, sumvv = 0, sumyy = 0, sumvy = 0;
  102. double *target = Malloc(double, prob.l);
  103. svm_cross_validation(&prob, &param, nr_fold, target);
  104. if (param.svm_type == EPSILON_SVR ||
  105. param.svm_type == NU_SVR) {
  106. for (i = 0; i < prob.l; i++) {
  107. double y = prob.y[i];
  108. double v = target[i];
  109. total_error += (v - y) * (v - y);
  110. sumv += v;
  111. sumy += y;
  112. sumvv += v * v;
  113. sumyy += y * y;
  114. sumvy += v * y;
  115. }
  116. printf("Cross Validation Mean squared error = %g\n", total_error / prob.l);
  117. printf("Cross Validation Squared correlation coefficient = %g\n",
  118. ((prob.l * sumvy - sumv * sumy) * (prob.l * sumvy - sumv * sumy)) /
  119. ((prob.l * sumvv - sumv * sumv) * (prob.l * sumyy - sumy * sumy))
  120. );
  121. } else {
  122. for (i = 0; i < prob.l; i++)
  123. if (target[i] == prob.y[i])
  124. ++total_correct;
  125. printf("Cross Validation Accuracy = %g%%\n", 100.0 * total_correct / prob.l);
  126. }
  127. free(target);
  128. }
  129. void parse_command_line(int argc, char **argv, char *input_file_name, char *model_file_name) {
  130. int i;
  131. void (*print_func)(const char *) = NULL; // default printing to stdout
  132. // default values
  133. param.svm_type = C_SVC;
  134. param.kernel_type = RBF;
  135. param.degree = 3;
  136. param.gamma = 0; // 1/num_features
  137. param.coef0 = 0;
  138. param.nu = 0.5;
  139. param.cache_size = 100;
  140. param.C = 1;
  141. param.eps = 1e-3;
  142. param.p = 0.1;
  143. param.shrinking = 1;
  144. param.probability = 0;
  145. param.nr_weight = 0;
  146. param.weight_label = NULL;
  147. param.weight = NULL;
  148. cross_validation = 0;
  149. // parse options
  150. for (i = 1; i < argc; i++) {
  151. if (argv[i][0] != '-') break;
  152. if (++i >= argc)
  153. exit_with_help();
  154. switch (argv[i - 1][1]) {
  155. case 's':
  156. param.svm_type = atoi(argv[i]);
  157. break;
  158. case 't':
  159. param.kernel_type = atoi(argv[i]);
  160. break;
  161. case 'd':
  162. param.degree = atoi(argv[i]);
  163. break;
  164. case 'g':
  165. param.gamma = atof(argv[i]);
  166. break;
  167. case 'r':
  168. param.coef0 = atof(argv[i]);
  169. break;
  170. case 'n':
  171. param.nu = atof(argv[i]);
  172. break;
  173. case 'm':
  174. param.cache_size = atof(argv[i]);
  175. break;
  176. case 'c':
  177. param.C = atof(argv[i]);
  178. break;
  179. case 'e':
  180. param.eps = atof(argv[i]);
  181. break;
  182. case 'p':
  183. param.p = atof(argv[i]);
  184. break;
  185. case 'h':
  186. param.shrinking = atoi(argv[i]);
  187. break;
  188. case 'b':
  189. param.probability = atoi(argv[i]);
  190. break;
  191. case 'q':
  192. print_func = &print_null;
  193. i--;
  194. break;
  195. case 'v':
  196. cross_validation = 1;
  197. nr_fold = atoi(argv[i]);
  198. if (nr_fold < 2) {
  199. fprintf(stderr, "n-fold cross validation: n must >= 2\n");
  200. exit_with_help();
  201. }
  202. break;
  203. case 'w':
  204. ++param.nr_weight;
  205. param.weight_label = (int *) realloc(param.weight_label, sizeof(int) * param.nr_weight);
  206. param.weight = (double *) realloc(param.weight, sizeof(double) * param.nr_weight);
  207. param.weight_label[param.nr_weight - 1] = atoi(&argv[i - 1][2]);
  208. param.weight[param.nr_weight - 1] = atof(argv[i]);
  209. break;
  210. default:
  211. fprintf(stderr, "Unknown option: -%c\n", argv[i - 1][1]);
  212. exit_with_help();
  213. }
  214. }
  215. svm_set_print_string_function(print_func);
  216. // determine filenames
  217. if (i >= argc)
  218. exit_with_help();
  219. strcpy(input_file_name, argv[i]);
  220. if (i < argc - 1)
  221. strcpy(model_file_name, argv[i + 1]);
  222. else {
  223. char *p = strrchr(argv[i], '/');
  224. if (p == NULL)
  225. p = argv[i];
  226. else
  227. ++p;
  228. sprintf(model_file_name, "%s.model", p);
  229. }
  230. }
  231. // read in a problem (in svmlight format)
  232. void read_problem(const char *filename) {
  233. int max_index, inst_max_index, i;
  234. size_t elements, j;
  235. FILE *fp = fopen(filename, "r");
  236. char *endptr;
  237. char *idx, *val, *label;
  238. if (fp == NULL) {
  239. fprintf(stderr, "can't open input file %s\n", filename);
  240. exit(1);
  241. }
  242. prob.l = 0;
  243. elements = 0;
  244. max_line_len = 1024;
  245. line = Malloc(char, max_line_len);
  246. while (readline(fp) != NULL) {
  247. char *p = strtok(line, " \t"); // label
  248. // features
  249. while (1) {
  250. p = strtok(NULL, " \t");
  251. if (p == NULL || *p == '\n') // check '\n' as ' ' may be after the last feature
  252. break;
  253. ++elements;
  254. }
  255. ++elements;
  256. ++prob.l;
  257. }
  258. rewind(fp);
  259. prob.y = Malloc(double, prob.l);
  260. prob.x = Malloc(struct svm_node *, prob.l);
  261. x_space = Malloc(struct svm_node, elements);
  262. max_index = 0;
  263. j = 0;
  264. for (i = 0; i < prob.l; i++) {
  265. inst_max_index = -1; // strtol gives 0 if wrong format, and precomputed kernel has <index> start from 0
  266. readline(fp);
  267. prob.x[i] = &x_space[j];
  268. label = strtok(line, " \t\n");
  269. if (label == NULL) // empty line
  270. exit_input_error(i + 1);
  271. prob.y[i] = strtod(label, &endptr);
  272. if (endptr == label || *endptr != '\0')
  273. exit_input_error(i + 1);
  274. while (1) {
  275. idx = strtok(NULL, ":");
  276. val = strtok(NULL, " \t");
  277. if (val == NULL)
  278. break;
  279. errno = 0;
  280. x_space[j].index = (int) strtol(idx, &endptr, 10);
  281. if (endptr == idx || errno != 0 || *endptr != '\0' || x_space[j].index <= inst_max_index)
  282. exit_input_error(i + 1);
  283. else
  284. inst_max_index = x_space[j].index;
  285. errno = 0;
  286. x_space[j].value = strtod(val, &endptr);
  287. if (endptr == val || errno != 0 || (*endptr != '\0' && !isspace(*endptr)))
  288. exit_input_error(i + 1);
  289. ++j;
  290. }
  291. if (inst_max_index > max_index)
  292. max_index = inst_max_index;
  293. x_space[j++].index = -1;
  294. }
  295. if (param.gamma == 0 && max_index > 0)
  296. param.gamma = 1.0 / max_index;
  297. if (param.kernel_type == PRECOMPUTED)
  298. for (i = 0; i < prob.l; i++) {
  299. if (prob.x[i][0].index != 0) {
  300. fprintf(stderr, "Wrong input format: first column must be 0:sample_serial_number\n");
  301. exit(1);
  302. }
  303. if ((int) prob.x[i][0].value <= 0 || (int) prob.x[i][0].value > max_index) {
  304. fprintf(stderr, "Wrong input format: sample_serial_number out of range\n");
  305. exit(1);
  306. }
  307. }
  308. fclose(fp);
  309. }