Happy Shrimp
http://blog.csdn.net/lights_joy/
Welcome reprint, but please keep the author information
in the OpenCV Support in SVM classifier, this article attempts to python call it in.
like the previous Bayesian classifier, SVM also follow the way of training and reuse, we directly in the Bayesian classifier test code to make simple changes to complete the classification of two types of data points.
The first is to create training data first, it is important to note that the Train_label must be of type integer, not float :
# training Points train_pts = 30# Create test data points, Class 2 # with (-1.5,-1.5) as Center Rand1 = np.ones ((train_pts,2)) * ( -2) + Np.random.rand (train_pts, 2) PR Int (' RAND1: ') print (RAND1) # with (1.5, 1.5) as Center Rand2 = np.ones ((train_pts,2)) + Np.random.rand (train_pts, 2) print (' Rand2: ') Print (rand2) # Merge random points, get training data Train_data = Np.vstack ((rand1, rand2)) Train_data = Np.array (train_data, dtype= ' float32 ') Train_label = Np.vstack ((Np.zeros ((train_pts,1), Dtype= ' int32 '), Np.ones ((train_pts,1), Dtype= ' Int32 ')) # Show Training Data plt.figure (1) plt.plot (rand1[:,0], rand1[:,1], ' O ') plt.plot (rand2[:,0], rand2[:,1], ' O ') plt.plot (rand2[:,0], rand2[:,1], ' O ')
Data similar to this:
after you get the training data, you then create a SVM Classifier and configure the training parameters:
# Create Classifier SVM = Cv2.ml.SVM_create () svm.settype (Cv2.ml.SVM_C_SVC) # SVM type Svm.setkernel (Cv2.ml.SVM_LINEAR) # Using linear core SVM.SETC (1.0)
We then train this classifier:
# TRAINING ret = Svm.train (Train_data, Cv2.ml.ROW_SAMPLE, Train_label)
After the training is complete, you can use the test data to make predictions:
# test data, 20 points [ -2,2]pt = Np.array (Np.random.rand (20,2) * 4-2, dtype= ' float32 ') (ret, res) = Svm.predict (PT) Print ("res =") pr Int (res)
predictthroughResreturn to get a20x1array, each line corresponds to an input point, and the computed value is the ordinal of the classification, which is0and the1, we take0.5classify the thresholds and display the results:
# Categorized by label Plt.figure (2) res = Np.hstack (res, RES) # First Class Type_data = Pt[res < 0.5]type_data = Np.reshape (Type_data, ( Type_data.shape[0]/2, 2) Plt.plot (type_data[:,0], type_data[:,1], ' O ') # Second Class Type_data = pt[res >= 0.5]type_data = NP.R Eshape (Type_data, (Type_data.shape[0]/2, 2)) Plt.plot (type_data[:,0], type_data[:,1], ' O ') plt.show ()
Look at the final result:
Finally, by SVM. Getsupportvectors gets the support vector.
# support Vector VEC = svm.getsupportvectors () print (VEC)
??
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Python image Processing (a): SVM classifier