## python机器学习手写算法系列——KNN分类

（图一）

import math
from collections import Counter
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
# Create color maps
cmap_light = ListedColormap(['orange', 'cyan', 'cornflowerblue'])
cmap_bold = ListedColormap(['darkorange', 'c', 'darkblue'])
from sklearn import neighbors, datasets
n_neighbors = 15
# import some data to play with
# we only take the first two features. We could avoid this ugly
# slicing by using a two-dim dataset
X = iris.data[:, :2]
y = iris.target

class KNNClassifier():
X=None
y=None
n_neighbors=0
def __init__(self, n_neighbors=15):
self.n_neighbors=n_neighbors
def fit(self, X, y):
self.X=np.array(X)
self.y=np.array(y)
def predict_one(self, p):
distance_array=np.array(list(map(lambda o: math.dist(p, o), self.X)))
argsorted=np.argsort(distance_array)
neighbours = argsorted[:self.n_neighbors]
neighbour_labels = y[neighbours]
occurence_count = Counter(neighbour_labels)
most_frequent = occurence_count.most_common(1)[0][0]
return most_frequent
def predict(self, X):
y_hat = np.array(list(map(self.predict_one, X)))
return y_hat

knn = KNNClassifier()
knn.fit(X, y)
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
h = .02 # step size in the mesh
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
np.arange(y_min, y_max, h))
Z = knn.predict(np.c_[xx.ravel(), yy.ravel()])
# Put the result into a color plot
Z = Z.reshape(xx.shape)
plt.figure()
plt.pcolormesh(xx, yy, Z, cmap=cmap_light)
# Plot also the training points
plt.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold,
edgecolor='k', s=20)
plt.xlim(xx.min(), xx.max())
plt.ylim(yy.min(), yy.max())
plt.title("My KNN (k = %i)"
% (n_neighbors))
plt.show()

（图二）

# we create an instance of Neighbours Classifier and fit the data.
clf = neighbors.KNeighborsClassifier(n_neighbors)
clf.fit(X, y)
# Plot the decision boundary. For that, we will assign a color to each
# point in the mesh [x_min, x_max]x[y_min, y_max].
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
h = .02 # step size in the mesh
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
np.arange(y_min, y_max, h))
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
# Put the result into a color plot
Z = Z.reshape(xx.shape)
plt.pcolormesh(xx, yy, Z, cmap=cmap_light)
# Plot also the training points
plt.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold,
edgecolor='k', s=20)
plt.xlim(xx.min(), xx.max())
plt.ylim(yy.min(), yy.max())
plt.title("Scikit-learn KNN (k = %i)"
% (n_neighbors))
plt.show()

（图三）

K的选择

# 源代码

https://github.com/EricWebsmith/machine_learning_from_scrach

# 参考文献

https://scikit-learn.org/stable/auto_examples/neighbors/plot_classification.html

https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KNeighborsClassifier.html

https://en.wikipedia.org/wiki/K-nearest_neighbors_algorithm

https://blog.csdn.net/juwikuang/article/details/108565458