How can I save a LibSVM python object instance?

China☆狼群 提交于 2019-12-10 09:49:50

问题


I wanted to use this classifier in other computer without had to train it again. I used to save some classifiers from scikit with cPickle. Doing the same with LIBSVM it gives me a " ValueError: ctypes objects containing pointers cannot be pickled ".

I'm using LibSVM 3.1 and Python 2.7.3.

Thanks

from libsvm.svm import *
from libsvm.svmutil import *
import cPickle

x = [[1, 0, 1], [-1, 0, -1]]
y = [1, -1]
prob = svm_problem(y, x)
param = svm_parameter()
param.kernel_type = LINEAR
param.C = 10
m = svm_train(prob, param)
labels_pred, acc, probs = svm_predict([-1, 1], [[1, 1, 1], [0, 0, 1]], m)
print labels_pred, acc, probs

import ipdb; ipdb.set_trace()

filename='libsvm-classif.pkl'

fid = open(filename, 'wb')
cPickle.dump(m, fid)
fid.close()

fid = open(filename, 'rb')
m = cPickle.load(fid)
labels_pred, acc, probs = svm_predict([-1, 1], [[1, 1, 1], [0, 0, 1]], m)

print labels_pred, acc, probs

回答1:


Just use libsvm's load and save functions

svm_save_model('libsvm.model', m)
m = svm_load_model('libsvm.model')

This is from the README file included in the python directory of the libsvm package. It seems to have a much better description of features than the website.



来源:https://stackoverflow.com/questions/11440970/how-can-i-save-a-libsvm-python-object-instance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!