標籤:back sample size ict 使用 blank div data lan
快樂蝦
http://blog.csdn.net/lights_joy/
歡迎轉載,但請保留作者資訊
在opencv中支援神經網路分類器。本文嘗試在python中調用它。
和前面的貝葉斯分類器一樣。神經網路也遵循先訓練再使用的方式,我們直接在貝葉斯分類器的測試代碼上做簡單改動,完畢兩類資料點的分類。
首先也是先建立訓練用的資料:
# 訓練的點數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=‘float32‘), np.ones((train_pts,1), dtype=‘float32‘)))# 顯示訓練資料plt.figure(1)plt.plot(rand1[:,0], rand1[:,1], ‘o‘)plt.plot(rand2[:,0], rand2[:,1], ‘o‘)
相似這種資料:
在得到訓練資料後,接著建立一個網路並配置訓練參數:
# 建立網路ann = cv2.ml.ANN_MLP_create()ann.setLayerSizes(np.array([2, 10, 10, 1])) # 必須首先運行此行ann.setActivationFunction(cv2.ml.ANN_MLP_SIGMOID_SYM)ann.setTrainMethod(cv2.ml.ANN_MLP_BACKPROP)ann.setBackpropWeightScale(0.1)ann.setBackpropMomentumScale(0.1)
因為我們的輸入是資料點的座標值,輸出是此資料點所屬的類別。因此這個網路的輸入層有2個節點,輸出則僅僅有一個節點。中間有兩個隱層。各有10個節點。
接著我們對此網路進行訓練:
# 訓練ret = ann.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) = ann.predict(pt)
predict通過res返回得到一個20x1的數組,每一行相應一個輸入焦點。因為我們選擇sigmoid做為啟用函數。因此計算得到的值是一個介於[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‘)
看看最後的結果:
??
Python影像處理(14):神經網路分類器