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.java 8.4 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. import libsvm.*;
  2. import java.io.*;
  3. import java.util.*;
  4. class svm_train {
  5. private svm_parameter param; // set by parse_command_line
  6. private svm_problem prob; // set by read_problem
  7. private svm_model model;
  8. private String input_file_name; // set by parse_command_line
  9. private String model_file_name; // set by parse_command_line
  10. private String error_msg;
  11. private int cross_validation;
  12. private int nr_fold;
  13. private static svm_print_interface svm_print_null = new svm_print_interface()
  14. {
  15. public void print(String s) {}
  16. };
  17. private static void exit_with_help()
  18. {
  19. System.out.print(
  20. "Usage: svm_train [options] training_set_file [model_file]\n"
  21. +"options:\n"
  22. +"-s svm_type : set type of SVM (default 0)\n"
  23. +" 0 -- C-SVC (multi-class classification)\n"
  24. +" 1 -- nu-SVC (multi-class classification)\n"
  25. +" 2 -- one-class SVM\n"
  26. +" 3 -- epsilon-SVR (regression)\n"
  27. +" 4 -- nu-SVR (regression)\n"
  28. +"-t kernel_type : set type of kernel function (default 2)\n"
  29. +" 0 -- linear: u'*v\n"
  30. +" 1 -- polynomial: (gamma*u'*v + coef0)^degree\n"
  31. +" 2 -- radial basis function: exp(-gamma*|u-v|^2)\n"
  32. +" 3 -- sigmoid: tanh(gamma*u'*v + coef0)\n"
  33. +" 4 -- precomputed kernel (kernel values in training_set_file)\n"
  34. +"-d degree : set degree in kernel function (default 3)\n"
  35. +"-g gamma : set gamma in kernel function (default 1/num_features)\n"
  36. +"-r coef0 : set coef0 in kernel function (default 0)\n"
  37. +"-c cost : set the parameter C of C-SVC, epsilon-SVR, and nu-SVR (default 1)\n"
  38. +"-n nu : set the parameter nu of nu-SVC, one-class SVM, and nu-SVR (default 0.5)\n"
  39. +"-p epsilon : set the epsilon in loss function of epsilon-SVR (default 0.1)\n"
  40. +"-m cachesize : set cache memory size in MB (default 100)\n"
  41. +"-e epsilon : set tolerance of termination criterion (default 0.001)\n"
  42. +"-h shrinking : whether to use the shrinking heuristics, 0 or 1 (default 1)\n"
  43. +"-b probability_estimates : whether to train a SVC or SVR model for probability estimates, 0 or 1 (default 0)\n"
  44. +"-wi weight : set the parameter C of class i to weight*C, for C-SVC (default 1)\n"
  45. +"-v n : n-fold cross validation mode\n"
  46. +"-q : quiet mode (no outputs)\n"
  47. );
  48. System.exit(1);
  49. }
  50. private void do_cross_validation()
  51. {
  52. int i;
  53. int total_correct = 0;
  54. double total_error = 0;
  55. double sumv = 0, sumy = 0, sumvv = 0, sumyy = 0, sumvy = 0;
  56. double[] target = new double[prob.l];
  57. svm.svm_cross_validation(prob,param,nr_fold,target);
  58. if(param.svm_type == svm_parameter.EPSILON_SVR ||
  59. param.svm_type == svm_parameter.NU_SVR)
  60. {
  61. for(i=0;i<prob.l;i++)
  62. {
  63. double y = prob.y[i];
  64. double v = target[i];
  65. total_error += (v-y)*(v-y);
  66. sumv += v;
  67. sumy += y;
  68. sumvv += v*v;
  69. sumyy += y*y;
  70. sumvy += v*y;
  71. }
  72. System.out.print("Cross Validation Mean squared error = "+total_error/prob.l+"\n");
  73. System.out.print("Cross Validation Squared correlation coefficient = "+
  74. ((prob.l*sumvy-sumv*sumy)*(prob.l*sumvy-sumv*sumy))/
  75. ((prob.l*sumvv-sumv*sumv)*(prob.l*sumyy-sumy*sumy))+"\n"
  76. );
  77. }
  78. else
  79. {
  80. for(i=0;i<prob.l;i++)
  81. if(target[i] == prob.y[i])
  82. ++total_correct;
  83. System.out.print("Cross Validation Accuracy = "+100.0*total_correct/prob.l+"%\n");
  84. }
  85. }
  86. private void run(String argv[]) throws IOException
  87. {
  88. parse_command_line(argv);
  89. read_problem();
  90. error_msg = svm.svm_check_parameter(prob,param);
  91. if(error_msg != null)
  92. {
  93. System.err.print("ERROR: "+error_msg+"\n");
  94. System.exit(1);
  95. }
  96. if(cross_validation != 0)
  97. {
  98. do_cross_validation();
  99. }
  100. else
  101. {
  102. model = svm.svm_train(prob,param);
  103. svm.svm_save_model(model_file_name,model);
  104. }
  105. }
  106. public static void main(String argv[]) throws IOException
  107. {
  108. svm_train t = new svm_train();
  109. t.run(argv);
  110. }
  111. private static double atof(String s)
  112. {
  113. double d = Double.valueOf(s).doubleValue();
  114. if (Double.isNaN(d) || Double.isInfinite(d))
  115. {
  116. System.err.print("NaN or Infinity in input\n");
  117. System.exit(1);
  118. }
  119. return(d);
  120. }
  121. private static int atoi(String s)
  122. {
  123. return Integer.parseInt(s);
  124. }
  125. private void parse_command_line(String argv[])
  126. {
  127. int i;
  128. svm_print_interface print_func = null; // default printing to stdout
  129. param = new svm_parameter();
  130. // default values
  131. param.svm_type = svm_parameter.C_SVC;
  132. param.kernel_type = svm_parameter.RBF;
  133. param.degree = 3;
  134. param.gamma = 0; // 1/num_features
  135. param.coef0 = 0;
  136. param.nu = 0.5;
  137. param.cache_size = 100;
  138. param.C = 1;
  139. param.eps = 1e-3;
  140. param.p = 0.1;
  141. param.shrinking = 1;
  142. param.probability = 0;
  143. param.nr_weight = 0;
  144. param.weight_label = new int[0];
  145. param.weight = new double[0];
  146. cross_validation = 0;
  147. // parse options
  148. for(i=0;i<argv.length;i++)
  149. {
  150. if(argv[i].charAt(0) != '-') break;
  151. if(++i>=argv.length)
  152. exit_with_help();
  153. switch(argv[i-1].charAt(1))
  154. {
  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 = svm_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. {
  200. System.err.print("n-fold cross validation: n must >= 2\n");
  201. exit_with_help();
  202. }
  203. break;
  204. case 'w':
  205. ++param.nr_weight;
  206. {
  207. int[] old = param.weight_label;
  208. param.weight_label = new int[param.nr_weight];
  209. System.arraycopy(old,0,param.weight_label,0,param.nr_weight-1);
  210. }
  211. {
  212. double[] old = param.weight;
  213. param.weight = new double[param.nr_weight];
  214. System.arraycopy(old,0,param.weight,0,param.nr_weight-1);
  215. }
  216. param.weight_label[param.nr_weight-1] = atoi(argv[i-1].substring(2));
  217. param.weight[param.nr_weight-1] = atof(argv[i]);
  218. break;
  219. default:
  220. System.err.print("Unknown option: " + argv[i-1] + "\n");
  221. exit_with_help();
  222. }
  223. }
  224. svm.svm_set_print_string_function(print_func);
  225. // determine filenames
  226. if(i>=argv.length)
  227. exit_with_help();
  228. input_file_name = argv[i];
  229. if(i<argv.length-1)
  230. model_file_name = argv[i+1];
  231. else
  232. {
  233. int p = argv[i].lastIndexOf('/');
  234. ++p; // whew...
  235. model_file_name = argv[i].substring(p)+".model";
  236. }
  237. }
  238. // read in a problem (in svmlight format)
  239. private void read_problem() throws IOException
  240. {
  241. BufferedReader fp = new BufferedReader(new FileReader(input_file_name));
  242. Vector<Double> vy = new Vector<Double>();
  243. Vector<svm_node[]> vx = new Vector<svm_node[]>();
  244. int max_index = 0;
  245. while(true)
  246. {
  247. String line = fp.readLine();
  248. if(line == null) break;
  249. StringTokenizer st = new StringTokenizer(line," \t\n\r\f:");
  250. vy.addElement(atof(st.nextToken()));
  251. int m = st.countTokens()/2;
  252. svm_node[] x = new svm_node[m];
  253. for(int j=0;j<m;j++)
  254. {
  255. x[j] = new svm_node();
  256. x[j].index = atoi(st.nextToken());
  257. x[j].value = atof(st.nextToken());
  258. }
  259. if(m>0) max_index = Math.max(max_index, x[m-1].index);
  260. vx.addElement(x);
  261. }
  262. prob = new svm_problem();
  263. prob.l = vy.size();
  264. prob.x = new svm_node[prob.l][];
  265. for(int i=0;i<prob.l;i++)
  266. prob.x[i] = vx.elementAt(i);
  267. prob.y = new double[prob.l];
  268. for(int i=0;i<prob.l;i++)
  269. prob.y[i] = vy.elementAt(i);
  270. if(param.gamma == 0 && max_index > 0)
  271. param.gamma = 1.0/max_index;
  272. if(param.kernel_type == svm_parameter.PRECOMPUTED)
  273. for(int i=0;i<prob.l;i++)
  274. {
  275. if (prob.x[i][0].index != 0)
  276. {
  277. System.err.print("Wrong kernel matrix: first column must be 0:sample_serial_number\n");
  278. System.exit(1);
  279. }
  280. if ((int)prob.x[i][0].value <= 0 || (int)prob.x[i][0].value > max_index)
  281. {
  282. System.err.print("Wrong input format: sample_serial_number out of range\n");
  283. System.exit(1);
  284. }
  285. }
  286. fp.close();
  287. }
  288. }

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