Understanding k-Nearest Neighbour html
咱們將Red系列標記爲Class-0(由0表示),將Blue 系列標記爲Class-1(由1表示)。 咱們建立了25個系列或25個訓練數據,並將它們標記爲0級或1級.在Matplotlib的幫助下繪製它,紅色系列顯示爲紅色三角形,藍色系列顯示爲藍色方塊.算法
import numpy as np import cv2 import matplotlib.pyplot as plt # Feature set containing (x,y) values of 25 known/training data trainData = np.random.randint(0,100,(25,2)).astype(np.float32) # Labels each one either Red or Blue with numbers 0 and 1 responses = np.random.randint(0,2,(25,1)).astype(np.float32) # Take Red families and plot them red = trainData[responses.ravel()==0] plt.scatter(red[:,0],red[:,1],80,'r','^') # Take Blue families and plot them blue = trainData[responses.ravel()==1] plt.scatter(blue[:,0],blue[:,1],80,'b','s') plt.show()
接下來初始化kNN算法並傳遞trainData和響應以訓練kNN(它構造搜索樹).而後咱們將對一個new-comer,並在OpenCV的kNN幫助下將它歸類爲一個系列.KNN以前,咱們須要瞭解一下咱們的測試數據(new-comer),數據應該是一個浮點數組,其大小爲numberoftestdata×numberoffeatures.而後找到new-comer的最近的鄰居並分類.數組
newcomer = np.random.randint(0,100,(1,2)).astype(np.float32) plt.scatter(newcomer[:,0],newcomer[:,1],80,'g','o') knn = cv2.ml.KNearest_create() knn.train(trainData, cv2.ml.ROW_SAMPLE, responses) ret, results, neighbours ,dist = knn.findNearest(newcomer, 3) print( "result: {}\n".format(results) ) print( "neighbours: {}\n".format(neighbours) ) print( "distance: {}\n".format(dist) ) plt.show()
輸出:dom
result: [[1.]] neighbours: [[1. 1. 0.]] distance: [[ 29. 149. 160.]]
上面返回的是:測試
若是newcomer有大量數據,則能夠將其做爲數組傳遞,相應的結果也做爲矩陣得到.spa
newcomers = np.random.randint(0,100,(10,2)).astype(np.float32) plt.scatter(newcomers[:,0],newcomers[:,1],80,'g','o') knn = cv2.ml.KNearest_create() knn.train(trainData, cv2.ml.ROW_SAMPLE, responses) ret, results, neighbours ,dist = knn.findNearest(newcomers, 3) print( "result: {}\n".format(results) ) print( "neighbours: {}\n".format(neighbours) ) print( "distance: {}\n".format(dist) ) plt.show()
輸出:rest
result: [[1.] [0.] [1.] [0.] [0.] [0.] [0.] [0.] [0.] [0.]] neighbours: [[0. 1. 1.] [0. 0. 0.] [1. 1. 1.] [0. 1. 0.] [1. 0. 0.] [0. 1. 0.] [0. 0. 0.] [0. 1. 0.] [0. 0. 0.] [0. 0. 1.]] distance: [[ 229. 392. 397.] [ 4. 10. 233.] [ 73. 146. 185.] [ 130. 145. 1681.] [ 61. 100. 125.] [ 8. 29. 169.] [ 41. 41. 306.] [ 85. 505. 733.] [ 242. 244. 409.] [ 61. 260. 493.]]