Created
December 6, 2011 17:35
-
-
Save neovintage/1439087 to your computer and use it in GitHub Desktop.
classifier_libsvm_minimal_modular with some extra comments
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'modshogun' | |
require 'narray' | |
# For the purposes of the example this is a helper file that's bundled in | |
# the examples directory. It does some things like loading data and | |
# checking some of the math. It's not necessary to include in your own | |
# projects | |
require 'load' | |
# Here we're setting our parameters for the SVM | |
@num = 1000 | |
@dist = 1 | |
@width = 2.1 | |
C = 1 | |
# We're just generating random data. gen_rand_ary is in the load.rb file. | |
# you'll find that all it does is creating an 2 by @num | |
puts "generating training data" | |
traindata_real = gen_rand_ary @num | |
testdata_real = gen_rand_ary @num | |
# just like the above methods this is just creating random labels for | |
# the training set and the test set. | |
puts "generating labels" | |
trainlab = gen_ones_vec @num | |
testlab = gen_ones_vec @num | |
# Assign the data to the feature matrix and then apply a particular | |
# kernel method to it. | |
# | |
puts "doing feature stuff" | |
feats_train = Modshogun::RealFeatures.new | |
feats_train.set_feature_matrix traindata_real | |
feats_test = Modshogun::RealFeatures.new | |
feats_test.set_feature_matrix testdata_real | |
kernel = Modshogun::GaussianKernel.new feats_train, feats_train, @width | |
# set the labels, the particular type of SVM we want to use and start training! | |
# | |
puts "labeling stuff" | |
labels = Modshogun::Labels.new | |
labels.set_labels trainlab | |
svm = Modshogun::LibSVM.new C, kernel, labels | |
svm.train | |
# With other ruby svm libs will typically use the method 'predict' to actually | |
# make the prediction. In shogun theres two ways to make a prediction. The first | |
# is a little weird in that we can use the kernel object and add both the training | |
# set and the test set to it. From there you can call 'svm.apply' and get the Label | |
# object. The second is a bit more manual, but you can init the training set on the | |
# kernel and then pass in a features object when calling 'svm.apply'. this is more | |
# analogous to the 'predict' method call in other SVM ruby libs. | |
# | |
puts "the grand finale" | |
kernel.init feats_train, feats_test | |
out = svm.apply.get_labels | |
testerr = mean out.sign.eql_items? testlab | |
puts testerr |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment