Python ML K-Nearest Neighbours
K-nearest neighbours sorts a new row by its closest neighbours. The k nearest training rows vote, and the majority wins.
Distance between two flowers
Distance is the square root of the sum of the squared gaps across the features.
import numpy as np
first = np.array([5.1, 3.5])
second = np.array([4.9, 3.0])
print(round(float(np.sqrt(np.sum((first - second) ** 2))), 4))Why scale matters
Multiply one feature by 10 and the same two flowers look far apart. The big feature now rules the vote.
import numpy as np
first = np.array([5.1, 3.5])
second = np.array([4.9, 3.0])
print(round(float(np.sqrt(np.sum((first - second) ** 2))), 4))
first_big = np.array([5.1, 35.0])
second_big = np.array([4.9, 30.0])
print(round(float(np.sqrt(np.sum((first_big - second_big) ** 2))), 4))k changes the answer
A k of 1 scores 0.6842 on the test set. A k of 25 scores 0.8684. The vote size matters.
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)
for k in [1, 25]:
model = KNeighborsClassifier(n_neighbors=k)
model.fit(X_train, y_train)
print(k, round(model.score(X_test, y_test), 4))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)
for k in [1, 3, 5, 25]:
model = KNeighborsClassifier(n_neighbors=k)
model.fit(X_train, y_train)
print("k =", k, "test accuracy:", round(model.score(X_test, y_test), 4))
model = KNeighborsClassifier(n_neighbors=3)
model.fit(X_train, y_train)
print("First predictions:", model.predict(X_test[:5]))
print("First actual labels:", y_test[:5])
flower = np.array([[5.1, 3.5]])
print("New flower prediction:", model.predict(flower))Key points
- K-nearest neighbours: a model that copies the labels of the nearest rows
- k: how many neighbours get a vote
- Distance: how far apart two rows are, measured across the features
- Use KNeighborsClassifier from sklearn.neighbors to build the model
- Use a small k to follow local detail, and a large k to smooth the vote
- A k of 1 copies the single nearest row, noise and all
- Accuracy: the share of test rows the model labels correctly
In this example, the Iris data is cut down to the two sepal measurements, so the vote uses only sepal length and sepal width. A k of 1 scores 0.6842 on the test set, a k of 3 scores 0.7895, a k of 5 scores 0.8158, and a k of 25 scores 0.8684. The first five test predictions match the real labels exactly. A new flower with sepal length 5.1 and sepal width 3.5 is called group 0. Bigger k smooths the vote here, and the test score proves it.
Note
Scaling comes in a later lesson. This lesson uses only the two sepal measurements, which sit on a similar scale.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What does k control in K-nearest neighbours?