You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

svm-train.c 9.0 kB

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

A Python package for graph kernels, graph edit distances and graph pre-image problem.