View Single Post
Old 09-01-2012, 05:26 AM
invis invis is offline
Senior Member
Join Date: Jul 2012
Posts: 50
Default Re: libsvm and Python

Hi !
All you need for this HW is svm_train and a bit svm_predict.
So how to use them ?

I found that svm_train cant take data from numpy.array, so this is what I do:
with open('features.train') as f:

numbers =[[float(e.strip().split()[0]), float(e.strip().split()[1]), float(e.strip().split()[2])] for e in lines]
# or same, but with loop
# for e in lines:
# 	temp = e.strip().split()
#	numbers.append([float(temp[0]), float(temp[1]), float(temp[2])])

for i in range(len(numbers)):
	X_train.append({1 : numbers[i][1], 2:numbers[i][2]})
After you can train your model:
import svmutil as svm
options = 'your options, for example -c 2 -q 3 ...' 
model = svm.svm_train(Y_train, X_train, options)
To use you model on another data sets (or on the same) use:
p_label, p_acc, p_val = svm.svm_predict(Y_train, X_train, model)
try help(svm.svm_predict) or help(svm.svm_train) for more information.

Hope this helps.

edit: one important note. If you train your model with '-v' parameter (for cross validation) function will not return the Model, but only a float number - 'Cross Validation Accuracy'
Reply With Quote