Ask Your Question
1

Save SVM in Python

asked 2013-01-04 16:39:38 -0600

StevenBell gravatar image

I'm using Python to train an SVM, and I'd like to save the resulting model for use later. However, I get an error:

TypeError: can't pickle SVM objects

Is there another persistence method I should use? Is there something that I could add to the Python SVM module to make it pickle-able?

Minimal working code is below:

import numpy as np
import cv2
import pickle

points = np.array([[1.0, 2.1], [1, -1], [2, 3], [2, 1]], dtype=np.float32)
labels = np.array([0, 1, 0, 1], dtype=np.float32)

model = cv2.SVM(points, labels)
pickle.dump(model, open("save.pkl", 'w'))
edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
3

answered 2013-01-04 18:21:22 -0600

updated 2013-01-04 18:22:23 -0600

What about this:

import numpy as np
import cv2

points = np.array([[1.0, 2.1], [1, -1], [2, 3], [2, 1]], dtype=np.float32)
labels = np.array([0, 1, 0, 1], dtype=np.float32)

# Train the SVM:
model = cv2.SVM(points, labels)

# Store it by using OpenCV functions:
model.save("/path/to/model.xml")

# Now create a new SVM & load the model:
model2 = cv2.SVM()
model2.load("/path/to/model.xml")

# Predict with model2:
model2.predict(np.array([[1.0, 2.1]], dtype=np.float32))
edit flag offensive delete link more

Comments

Thanks, I was clearly thinking too hard to notice the save() and load() methods right in front of me!

StevenBell gravatar imageStevenBell ( 2013-01-04 18:22:36 -0600 )edit

No problem. :-)

Philipp Wagner gravatar imagePhilipp Wagner ( 2013-01-04 18:35:22 -0600 )edit

O.K., so does anyone know how to do this in OpenCV 3.0.0? I've got to the point where I can .save() my SVM model to a .dat file, but it appears that there is no .load() method in the new version. My model is trapped in a .dat and can't get out!

Ujustwaite gravatar imageUjustwaite ( 2015-09-28 14:06:00 -0600 )edit

Question Tools

Stats

Asked: 2013-01-04 16:39:38 -0600

Seen: 7,187 times

Last updated: Jan 04 '13