Python ML KNN from Scratch
KNN from scratch is three steps in plain NumPy. Measure the distances, pick the nearest k rows, and let their labels vote.
Distance by hand
The distance from a new flower to a training flower uses the same square root formula.
import numpy as np
new = np.array([5.1, 3.5])
old = np.array([4.9, 3.0])
print(round(float(np.sqrt(np.sum((new - old) ** 2))), 4))Nearest three
argsort ranks the distances. The first three entries are the nearest rows.
import numpy as np
train = np.array([[5.1, 3.5], [4.9, 3.0], [6.0, 2.2], [5.0, 3.6]])
new = np.array([5.0, 3.4])
distances = np.sqrt(np.sum((train - new) ** 2, axis=1))
print(np.argsort(distances)[:3])The vote wins
Three nearest labels hold two of one group and one of another. The group with two votes wins.
import numpy as np
labels = np.array([1, 1, 0])
values, counts = np.unique(labels, return_counts=True)
print(values)
print(counts)
print(values[np.argmax(counts)])Example
import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
X, y = load_iris(return_X_y=True)
X = X[:, [0, 1]]
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
def predict_one(point, k=3):
distances = np.sqrt(np.sum((X_train - point) ** 2, axis=1))
nearest = np.argsort(distances)[:k]
labels, counts = np.unique(y_train[nearest], return_counts=True)
return labels[np.argmax(counts)]
scratch_pred = np.array([predict_one(point) for point in X_test])
scratch_acc = np.mean(scratch_pred == y_test)
model = KNeighborsClassifier(n_neighbors=3)
model.fit(X_train, y_train)
print("From scratch accuracy:", round(float(scratch_acc), 4))
print("sklearn accuracy:", round(model.score(X_test, y_test), 4))
print("Same predictions:", bool(np.array_equal(scratch_pred, model.predict(X_test))))
print("First predictions:", scratch_pred[:5])
print("First actual labels:", y_test[:5])Key points
- Use np.sqrt and np.sum to measure the distance to every training row
- Use np.argsort to rank the rows from nearest to farthest
- Use np.unique with return_counts to count the votes
- Use np.argmax to pick the label with the most votes
- The from-scratch version must match sklearn on the same data and split
- Use the same two sepal measurements as the last lesson
- Ties are broken by the first label in sorted order
In this example, the same Iris split and the same two sepal measurements from the last lesson are used again. Each test flower is measured against every training flower, the three nearest vote, and the majority label wins. The from-scratch accuracy is 0.7895 and the sklearn accuracy is 0.7895. Every single prediction matches, so the check passes. The first five predictions match the real labels exactly.
Note
No library model is used for the predictions here. sklearn runs only as the check.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What is the first step of KNN from scratch?