Python opencv machine learning 1.knn k nearest neighbor learning test summary

      Outbreaks continue, simply learn image learn the more fans, the more we feel the image is inseparable from these machine learning neural network, although the feeling has to do something too complex, but still should learn in this regard. Therefore, the official start of science, matter can not do deep, have to look at the door.

Start, first test

As shown, there are already some of the random data, the new data into another (green), according to the attributes of its neighbors to its classification, k is the number of neighbors is selected, selecting three neighbors in the present experiment, the general to choose an odd number of neighbors, and neighbors from using Euclidean distance formula

Appreciated knn: determining their properties according to the attribute of k neighbors, typically selected from an odd number of neighbors, the modified KNN flies, the weight change with different weights according to the distance of the neighbors

Paste the code copied from "OpenCV-Python-Tutorial- Chinese version 20160814"

import cv2
import numpy as np
import matplotlib.pyplot as plt

traindata = np.random.randint(0, 100, (25, 2)).astype(np.float32)

resonses = np.random.randint(0, 2, (25, 1)).astype(np.float32)

red = traindata[resonses.ravel() == 0]
plt.scatter(red[:, 0], red[:, 1], 80, 'r', '^')

blue = traindata[resonses.ravel() == 1]
plt.scatter(blue[:, 0], blue[:, 1], 80, 'b', 's')

newcomer = np.random.randint(0, 100, (1, 2)).astype(np.float32)
plt.scatter(newcomer[:, 0], newcomer[:, 1], 80, 'g', 'o')

# 新来一个数组
# newcomer = np.random.randint(0, 100, (10, 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, resonses)
ret, result, neighbours, dist = knn.findNearest(newcomer, 3)

print("result", result, "\n")
print("neighbours", neighbours, "\n")
print("distance", dist)

plt.show()

 

Published 54 original articles · won praise 41 · views 7868

Guess you like

Origin blog.csdn.net/qq_36071362/article/details/104325341