example-1.rb 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. # Example to illustrate construction of a dataset by hand,
  2. # with training and evaluating SVM models.
  3. #
  4. require "svm-toolkit"
  5. include SvmToolkit
  6. puts "Classification with LIBSVM"
  7. puts "--------------------------"
  8. # Sample dataset: the 'Play Tennis' dataset
  9. # from T. Mitchell, Machine Learning (1997)
  10. # --------------------------------------------
  11. # Labels for each instance in the training set
  12. # 1 = Play, 0 = Not
  13. Labels = [0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0]
  14. # Recoding the attribute values into range [0, 1]
  15. Instances = [
  16. [0.0,1.0,1.0,0.0],
  17. [0.0,1.0,1.0,1.0],
  18. [0.5,1.0,1.0,0.0],
  19. [1.0,0.5,1.0,0.0],
  20. [1.0,0.0,0.0,0.0],
  21. [1.0,0.0,0.0,1.0],
  22. [0.5,0.0,0.0,1.0],
  23. [0.0,0.5,1.0,0.0],
  24. [0.0,0.0,0.0,0.0],
  25. [1.0,0.5,0.0,0.0],
  26. [0.0,0.5,0.0,1.0],
  27. [0.5,0.5,1.0,1.0],
  28. [0.5,1.0,0.0,0.0],
  29. [1.0,0.5,1.0,1.0]
  30. ]
  31. # create some arbitrary train/test split
  32. TrainingSet = Problem.from_array(Instances.slice(0, 10), Labels.slice(0, 10))
  33. TestSet = Problem.from_array(Instances.slice(10, 4), Labels.slice(10, 4))
  34. # Iterate over each kernel type
  35. Parameter.kernels.each do |kernel|
  36. # -- train model for this kernel type
  37. params = Parameter.new(
  38. :svm_type => Parameter::C_SVC,
  39. :kernel_type => kernel,
  40. :cost => 10,
  41. :degree => 1,
  42. :gamma => 100
  43. )
  44. model = Svm.svm_train(TrainingSet, params)
  45. # -- test kernel performance on the training set
  46. errors = model.evaluate_dataset(TrainingSet, :print_results => true)
  47. puts "Kernel #{Parameter.kernel_name(kernel)} has #{errors} on the training set"
  48. # -- test kernel performance on the test set
  49. errors = model.evaluate_dataset(TestSet, :print_results => true)
  50. puts "Kernel #{Parameter.kernel_name(kernel)} has #{errors} on the test set"
  51. end