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.

svmutil.py 8.7 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. #!/usr/bin/env python
  2. import os
  3. import sys
  4. from svm import *
  5. from svm import __all__ as svm_all
  6. __all__ = ['evaluations', 'svm_load_model', 'svm_predict', 'svm_read_problem',
  7. 'svm_save_model', 'svm_train'] + svm_all
  8. sys.path = [os.path.dirname(os.path.abspath(__file__))] + sys.path
  9. def svm_read_problem(data_file_name):
  10. """
  11. svm_read_problem(data_file_name) -> [y, x]
  12. Read LIBSVM-format data from data_file_name and return labels y
  13. and data instances x.
  14. """
  15. prob_y = []
  16. prob_x = []
  17. for line in open(data_file_name):
  18. line = line.split(None, 1)
  19. # In case an instance with all zero features
  20. if len(line) == 1: line += ['']
  21. label, features = line
  22. xi = {}
  23. for e in features.split():
  24. ind, val = e.split(":")
  25. xi[int(ind)] = float(val)
  26. prob_y += [float(label)]
  27. prob_x += [xi]
  28. return (prob_y, prob_x)
  29. def svm_load_model(model_file_name):
  30. """
  31. svm_load_model(model_file_name) -> model
  32. Load a LIBSVM model from model_file_name and return.
  33. """
  34. model = libsvm.svm_load_model(model_file_name.encode())
  35. if not model:
  36. print("can't open model file %s" % model_file_name)
  37. return None
  38. model = toPyModel(model)
  39. return model
  40. def svm_save_model(model_file_name, model):
  41. """
  42. svm_save_model(model_file_name, model) -> None
  43. Save a LIBSVM model to the file model_file_name.
  44. """
  45. libsvm.svm_save_model(model_file_name.encode(), model)
  46. def evaluations(ty, pv):
  47. """
  48. evaluations(ty, pv) -> (ACC, MSE, SCC)
  49. Calculate accuracy, mean squared error and squared correlation coefficient
  50. using the true values (ty) and predicted values (pv).
  51. """
  52. if len(ty) != len(pv):
  53. raise ValueError("len(ty) must equal to len(pv)")
  54. total_correct = total_error = 0
  55. sumv = sumy = sumvv = sumyy = sumvy = 0
  56. for v, y in zip(pv, ty):
  57. if y == v:
  58. total_correct += 1
  59. total_error += (v-y)*(v-y)
  60. sumv += v
  61. sumy += y
  62. sumvv += v*v
  63. sumyy += y*y
  64. sumvy += v*y
  65. l = len(ty)
  66. ACC = 100.0*total_correct/l
  67. MSE = total_error/l
  68. try:
  69. SCC = ((l*sumvy-sumv*sumy)*(l*sumvy-sumv*sumy))/((l*sumvv-sumv*sumv)*(l*sumyy-sumy*sumy))
  70. except:
  71. SCC = float('nan')
  72. return (ACC, MSE, SCC)
  73. def svm_train(arg1, arg2=None, arg3=None):
  74. """
  75. svm_train(y, x [, options]) -> model | ACC | MSE
  76. svm_train(prob [, options]) -> model | ACC | MSE
  77. svm_train(prob, param) -> model | ACC| MSE
  78. Train an SVM model from data (y, x) or an svm_problem prob using
  79. 'options' or an svm_parameter param.
  80. If '-v' is specified in 'options' (i.e., cross validation)
  81. either accuracy (ACC) or mean-squared error (MSE) is returned.
  82. options:
  83. -s svm_type : set type of SVM (default 0)
  84. 0 -- C-SVC (multi-class classification)
  85. 1 -- nu-SVC (multi-class classification)
  86. 2 -- one-class SVM
  87. 3 -- epsilon-SVR (regression)
  88. 4 -- nu-SVR (regression)
  89. -t kernel_type : set type of kernel function (default 2)
  90. 0 -- linear: u'*v
  91. 1 -- polynomial: (gamma*u'*v + coef0)^degree
  92. 2 -- radial basis function: exp(-gamma*|u-v|^2)
  93. 3 -- sigmoid: tanh(gamma*u'*v + coef0)
  94. 4 -- precomputed kernel (kernel values in training_set_file)
  95. -d degree : set degree in kernel function (default 3)
  96. -g gamma : set gamma in kernel function (default 1/num_features)
  97. -r coef0 : set coef0 in kernel function (default 0)
  98. -c cost : set the parameter C of C-SVC, epsilon-SVR, and nu-SVR (default 1)
  99. -n nu : set the parameter nu of nu-SVC, one-class SVM, and nu-SVR (default 0.5)
  100. -p epsilon : set the epsilon in loss function of epsilon-SVR (default 0.1)
  101. -m cachesize : set cache memory size in MB (default 100)
  102. -e epsilon : set tolerance of termination criterion (default 0.001)
  103. -h shrinking : whether to use the shrinking heuristics, 0 or 1 (default 1)
  104. -b probability_estimates : whether to train a SVC or SVR model for probability estimates, 0 or 1 (default 0)
  105. -wi weight : set the parameter C of class i to weight*C, for C-SVC (default 1)
  106. -v n: n-fold cross validation mode
  107. -q : quiet mode (no outputs)
  108. """
  109. prob, param = None, None
  110. if isinstance(arg1, (list, tuple)):
  111. assert isinstance(arg2, (list, tuple))
  112. y, x, options = arg1, arg2, arg3
  113. param = svm_parameter(options)
  114. prob = svm_problem(y, x, isKernel=(param.kernel_type == PRECOMPUTED))
  115. elif isinstance(arg1, svm_problem):
  116. prob = arg1
  117. if isinstance(arg2, svm_parameter):
  118. param = arg2
  119. else:
  120. param = svm_parameter(arg2)
  121. if prob == None or param == None:
  122. raise TypeError("Wrong types for the arguments")
  123. if param.kernel_type == PRECOMPUTED:
  124. for xi in prob.x_space:
  125. idx, val = xi[0].index, xi[0].value
  126. if xi[0].index != 0:
  127. raise ValueError('Wrong input format: first column must be 0:sample_serial_number')
  128. if val <= 0 or val > prob.n:
  129. raise ValueError('Wrong input format: sample_serial_number out of range')
  130. if param.gamma == 0 and prob.n > 0:
  131. param.gamma = 1.0 / prob.n
  132. libsvm.svm_set_print_string_function(param.print_func)
  133. err_msg = libsvm.svm_check_parameter(prob, param)
  134. if err_msg:
  135. raise ValueError('Error: %s' % err_msg)
  136. if param.cross_validation:
  137. l, nr_fold = prob.l, param.nr_fold
  138. target = (c_double * l)()
  139. libsvm.svm_cross_validation(prob, param, nr_fold, target)
  140. ACC, MSE, SCC = evaluations(prob.y[:l], target[:l])
  141. if param.svm_type in [EPSILON_SVR, NU_SVR]:
  142. print("Cross Validation Mean squared error = %g" % MSE)
  143. print("Cross Validation Squared correlation coefficient = %g" % SCC)
  144. return MSE
  145. else:
  146. print("Cross Validation Accuracy = %g%%" % ACC)
  147. return ACC
  148. else:
  149. m = libsvm.svm_train(prob, param)
  150. m = toPyModel(m)
  151. # If prob is destroyed, data including SVs pointed by m can remain.
  152. m.x_space = prob.x_space
  153. return m
  154. def svm_predict(y, x, m, options=""):
  155. """
  156. svm_predict(y, x, m [, options]) -> (p_labels, p_acc, p_vals)
  157. Predict data (y, x) with the SVM model m.
  158. options:
  159. -b probability_estimates: whether to predict probability estimates,
  160. 0 or 1 (default 0); for one-class SVM only 0 is supported.
  161. -q : quiet mode (no outputs).
  162. The return tuple contains
  163. p_labels: a list of predicted labels
  164. p_acc: a tuple including accuracy (for classification), mean-squared
  165. error, and squared correlation coefficient (for regression).
  166. p_vals: a list of decision values or probability estimates (if '-b 1'
  167. is specified). If k is the number of classes, for decision values,
  168. each element includes results of predicting k(k-1)/2 binary-class
  169. SVMs. For probabilities, each element contains k values indicating
  170. the probability that the testing instance is in each class.
  171. Note that the order of classes here is the same as 'model.label'
  172. field in the model structure.
  173. """
  174. def info(s):
  175. print(s)
  176. predict_probability = 0
  177. argv = options.split()
  178. i = 0
  179. while i < len(argv):
  180. if argv[i] == '-b':
  181. i += 1
  182. predict_probability = int(argv[i])
  183. elif argv[i] == '-q':
  184. info = print_null
  185. else:
  186. raise ValueError("Wrong options")
  187. i+=1
  188. svm_type = m.get_svm_type()
  189. is_prob_model = m.is_probability_model()
  190. nr_class = m.get_nr_class()
  191. pred_labels = []
  192. pred_values = []
  193. if predict_probability:
  194. if not is_prob_model:
  195. raise ValueError("Model does not support probabiliy estimates")
  196. if svm_type in [NU_SVR, EPSILON_SVR]:
  197. info("Prob. model for test data: target value = predicted value + z,\n"
  198. "z: Laplace distribution e^(-|z|/sigma)/(2sigma),sigma=%g" % m.get_svr_probability());
  199. nr_class = 0
  200. prob_estimates = (c_double * nr_class)()
  201. for xi in x:
  202. xi, idx = gen_svm_nodearray(xi, isKernel=(m.param.kernel_type == PRECOMPUTED))
  203. label = libsvm.svm_predict_probability(m, xi, prob_estimates)
  204. values = prob_estimates[:nr_class]
  205. pred_labels += [label]
  206. pred_values += [values]
  207. else:
  208. if is_prob_model:
  209. info("Model supports probability estimates, but disabled in predicton.")
  210. if svm_type in (ONE_CLASS, EPSILON_SVR, NU_SVC):
  211. nr_classifier = 1
  212. else:
  213. nr_classifier = nr_class*(nr_class-1)//2
  214. dec_values = (c_double * nr_classifier)()
  215. for xi in x:
  216. xi, idx = gen_svm_nodearray(xi, isKernel=(m.param.kernel_type == PRECOMPUTED))
  217. label = libsvm.svm_predict_values(m, xi, dec_values)
  218. if(nr_class == 1):
  219. values = [1]
  220. else:
  221. values = dec_values[:nr_classifier]
  222. pred_labels += [label]
  223. pred_values += [values]
  224. ACC, MSE, SCC = evaluations(y, pred_labels)
  225. l = len(y)
  226. if svm_type in [EPSILON_SVR, NU_SVR]:
  227. info("Mean squared error = %g (regression)" % MSE)
  228. info("Squared correlation coefficient = %g (regression)" % SCC)
  229. else:
  230. info("Accuracy = %g%% (%d/%d) (classification)" % (ACC, int(l*ACC/100), l))
  231. return pred_labels, (ACC, MSE, SCC), pred_values

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