The model save and load __python of SVM in Python opencv3.x

Source: Internet
Author: User
Tags svm

Nonsense not much to say directly on the code:

Import NumPy as NP
from Sklearn import datasets

x,y = Datasets.make_classification (n_samples=100,n_features=2, n_redundant=0,n_classes=2,random_state=7816)

print (x.shape,y.shape)
X = X.astype (np.float32)
y = y * 2-1 '
detach data ' from
Sklearn import model_selection as Ms
X_train, X_test, y_train, y_test = Ms.train_test_split (
    X, y, test_size=0.2, random_state=42
)
import cv2
SVM = cv2.ml.SVM_create ()
Svm.setkernel ( Cv2.ml.SVM_LINEAR)
' start training '

Y_train = Y_train.reshape ( -1, 1)
# Print (y_train)
Svm.train (x_ Train, Cv2.ml.ROW_SAMPLE, Y_train)
svm.save ("Svmtest.mat")
print ("done\n")

svm2 = Cv2.ml.SVM_load (" Svmtest.mat ")

# svm2.load (" Svmtest.mat ")
# Print (svm2)
' Start forecast '
_, y_pred = Svm2.predict (x_ Test)

' metrics the Scikit-learn module to calculate the accuracy ' from
sklearn import metrics
print Metrics.accuracy_score ( Y_test, y_pred))

The key code is as follows:

Create:

Import cv2
SVM = cv2.ml.SVM_create ()
Svm.setkernel (Cv2.ml.SVM_LINEAR)

The other is the older version, basically not.

Load:

SVM2 = Cv2.ml.SVM_load ("Svmtest.mat")

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.