example-4.rb 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. # This example illustrates loading a datafile from a CSV file,
  2. # and display of information available for a model and when
  3. # predicting a value for a given instance of data.
  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. Dataset = Problem.from_file("weather.csv", Problem::Csv)
  12. # Iterate over each kernel type
  13. Parameter.kernels.each do |kernel|
  14. # -- train model for this kernel type
  15. params = Parameter.new(
  16. :svm_type => Parameter::C_SVC,
  17. :kernel_type => kernel,
  18. :cost => 10,
  19. :degree => 1,
  20. :gamma => 100
  21. )
  22. model = Svm.svm_train(Dataset, params)
  23. # -- report information on model
  24. puts "Model has kernel: #{Parameter.kernel_name(model.kernel_type)}, cost #{model.cost}, gamma #{model.gamma}"
  25. puts "Model has #{model.nSV.to_a.join(",")} support vectors for the #{model.number_classes} classes"
  26. puts "The instances used as support vectors for training are: #{model.support_vector_indices.join(",")}"
  27. # -- test kernel performance on the training set
  28. accuracy = model.evaluate_dataset(Dataset, :print_results => true)
  29. puts "Kernel #{Parameter.kernel_name(kernel)} has #{accuracy} on the training set"
  30. Dataset.size.times do |i|
  31. puts "Instance #{i} is predicted as #{model.predict(Dataset, i)} with value #{model.predict_values(Dataset, i)}"
  32. end
  33. end