快樂蝦
http://blog.csdn.net/lights_joy/
歡迎轉載,但請保留作者信息
在opencv中支持SVM分類器。本文嘗試在python中調用它。
和前面的貝葉斯分類器一樣,SVM也遵循先訓練再使用的方式。我們直接在貝葉斯分類器的測試代碼上做簡單改動。完畢兩類數據點的分類。
首先也是先創建訓練用的數據。須要注意的是這里的train_label必須是整數類型,而不是float:
# 訓練的點數 train_pts = 30 # 創建測試的數據點,2類 # 以(-1.5, -1.5)為中心 rand1 = np.ones((train_pts,2)) * (-2) + np.random.rand(train_pts, 2) print('rand1:') print(rand1) # 以(1.5, 1.5)為中心 rand2 = np.ones((train_pts,2)) + np.random.rand(train_pts, 2) print('rand2:') print(rand2) # 合並隨機點,得到訓練數據 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'))) # 顯示訓練數據 plt.figure(1) plt.plot(rand1[:,0], rand1[:,1], 'o') plt.plot(rand2[:,0], rand2[:,1], 'o') plt.plot(rand2[:,0], rand2[:,1], 'o')
相似這種數據:
在得到訓練數據后,接着創建一個SVM分類器並配置訓練參數:
# 創建分類器 svm = cv2.ml.SVM_create() svm.setType(cv2.ml.SVM_C_SVC) # SVM類型 svm.setKernel(cv2.ml.SVM_LINEAR) # 使用線性核 svm.setC(1.0)
接着我們對此分類器進行訓練:
# 訓練 ret = svm.train(train_data, cv2.ml.ROW_SAMPLE, train_label)
在訓練完畢后就能夠使用測試數據進行預測了:
# 測試數據。20個點[-2,2] pt = np.array(np.random.rand(20,2) * 4 - 2, dtype='float32') (ret, res) = svm.predict(pt) print("res = ") print(res)
predict通過res返回得到一個20x1的數組。每一行相應一個輸入點。計算得到的值就是分類的序號,在這里是0和1,我們取0.5為閾值進行分類並顯示結果:
# 按label進行分類顯示 plt.figure(2) res = np.hstack((res, res)) # 第一類 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') # 第二類 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') plt.show()
看看最后的結果:
最后。通過svm. getSupportVectors獲取支持向量。
# 支持向量 vec = svm.getSupportVectors() print(vec)