ML K-nearest Neighbors
K-nearest neighbors (KNN) may be the simplest machine-learning algorithm there is. It doesn't build formulas or trees at all. To classify a new point it:
- measures the distance from the new point to every training point,
- picks the k closest ones (the neighbours),
- lets them vote: the most common class among them wins.
"Training" just means storing the data, which is why KNN is called a lazy learner. All the work happens at prediction time.
A tiny example
Invented data: 12 fruits measured by weight (grams) and a sweetness score from 1 to 10. Classes: 0 = lemon, 1 = orange.
import numpy as np
import matplotlib.pyplot as plt
weight = np.array([95, 110, 102, 120, 88, 105, 150, 170, 160, 140, 182, 155])
sweet = np.array([2.0, 3.0, 2.5, 3.5, 1.8, 2.2, 6.0, 7.5, 6.8, 5.5, 7.0, 4.0])
fruit = np.array([0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1])
new = (130, 4.5)
plt.scatter(weight, sweet, c=fruit, cmap="coolwarm", s=50)
plt.scatter(*new, c="black", marker="*", s=250)
plt.xlabel("Weight (g)")
plt.ylabel("Sweetness")
plt.show()
print("Black star = the unknown fruit at", new)Black star = the unknown fruit at (130, 4.5)
Doing it by hand
Let's compute the distances ourselves and look at the 3 nearest neighbours. Because grams and sweetness points have very different ranges, we first scale both features to z-scores (see the Scale lesson) — otherwise weight alone would decide everything:
import numpy as np
weight = np.array([95, 110, 102, 120, 88, 105, 150, 170, 160, 140, 182, 155])
sweet = np.array([2.0, 3.0, 2.5, 3.5, 1.8, 2.2, 6.0, 7.5, 6.8, 5.5, 7.0, 4.0])
fruit = np.array([0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1])
names = np.array(["lemon", "orange"])
X = np.column_stack([weight, sweet])
mean, std = X.mean(axis=0), X.std(axis=0)
Xs = (X - mean) / std
new = (np.array([130, 4.5]) - mean) / std
dist = np.sqrt(((Xs - new) ** 2).sum(axis=1))
nearest = np.argsort(dist)[:3]
for i in nearest:
print(f"row {i:2}: weight={weight[i]}, sweet={sweet[i]}, {names[fruit[i]]:6} distance={dist[i]:.3f}")
votes = np.bincount(fruit[nearest])
print("votes:", votes, "->", names[votes.argmax()])row 3: weight=120, sweet=3.5, lemon distance=0.590
row 9: weight=140, sweet=5.5, orange distance=0.590
row 11: weight=155, sweet=4.0, orange distance=0.854
votes: [1 2] -> orange
KNeighborsClassifier
scikit-learn's version does the same, plus clever data structures that avoid comparing with every point in big data sets:
import numpy as np
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
weight = [95, 110, 102, 120, 88, 105, 150, 170, 160, 140, 182, 155]
sweet = [2.0, 3.0, 2.5, 3.5, 1.8, 2.2, 6.0, 7.5, 6.8, 5.5, 7.0, 4.0]
fruit = [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1]
X = np.column_stack([weight, sweet])
scaler = StandardScaler().fit(X)
new = scaler.transform([[130, 4.5], [100, 6.0]])
for k in [1, 3, 5]:
knn = KNeighborsClassifier(n_neighbors=k).fit(scaler.transform(X), fruit)
print(f"k={k}: predictions={knn.predict(new)} P(orange)={knn.predict_proba(new)[:, 1].round(2)}")k=1: predictions=[0 1] P(orange)=[0. 1.]
k=3: predictions=[1 0] P(orange)=[0.67 0.33]
k=5: predictions=[1 0] P(orange)=[0.6 0.4]
predict_proba for KNN is just the share of neighbours voting for each class — with k = 3 the only possible values are 0, ⅓, ⅔ and 1.
Choosing k
- Small k (like 1) follows every quirk of the training data: low bias, high variance, easy to overfit.
- Large k smooths the decision boundary but can blur real differences: high bias, underfitting.
Use cross validation to pick it. Here on the bigger, built-in iris flower data set (150 flowers, 4 measurements, 3 species):
from sklearn.datasets import load_iris
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
X, y = load_iris(return_X_y=True)
for k in [1, 3, 5, 9, 15, 31, 61]:
model = make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=k))
scores = cross_val_score(model, X, y, cv=5)
print(f"k={k:2}: mean accuracy {scores.mean():.3f}")k= 1: mean accuracy 0.947
k= 3: mean accuracy 0.953
k= 5: mean accuracy 0.960
k= 9: mean accuracy 0.960
k=15: mean accuracy 0.940
k=31: mean accuracy 0.927
k=61: mean accuracy 0.847
Accuracy stays high over a wide range of k and drops when k becomes so large that neighbours from other species outvote the right ones.
Tip: For two-class problems, use an odd k to avoid tied votes.
weights="distance"lets closer neighbours count more than distant ones.
KNN for regression
KNeighborsRegressor predicts the average target of the k neighbours instead of voting:
from sklearn.neighbors import KNeighborsRegressor
size_m2 = [[30], [42], [55], [61], [75], [88], [102], [120]]
rent = [520, 610, 700, 760, 880, 950, 1100, 1250]
model = KNeighborsRegressor(n_neighbors=2).fit(size_m2, rent)
print("70 m2 ->", model.predict([[70]]))
distances, indices = model.kneighbors([[70]])
print("neighbours:", [size_m2[i][0] for i in indices[0]], "with distances", distances[0])70 m2 -> [820.]
neighbours: [75, 61] with distances [5. 9.]
The prediction for 70 m² is simply the average rent of the 61 m² and 75 m² flats.
Test yourself
Why is KNN called a 'lazy' learner?
- It is slow to code
- Training only stores the data; the work happens at prediction time
- It ignores half the data
- It never makes mistakes
Why should features be scaled before using KNN?
- KNN only accepts values between 0 and 1
- Distances would be dominated by features with large ranges
- Scaling makes k smaller
- It is not necessary
What happens when k is very small, such as k = 1?
- The model underfits
- The model is very sensitive to noise and may overfit
- Predictions become averages
- Training becomes slower