Reading history

K-Nearest Neighbours (KNN) in Python with scikit-learn

4 min read 2 views

Learn the k-nearest neighbours algorithm: how KNN predicts, why feature scaling matters, choosing k with cross-validation, and its pros and cons.

K-nearest neighbours (KNN) may be the most intuitive machine learning algorithm: to classify something new, look at the k most similar examples you already know and go with the majority. There is no equation to fit, since the model simply remembers the training data. KNN is a great way to understand distance, scaling and the effect of a single setting on model behaviour.

In this lesson you will learn

  • How KNN makes a prediction
  • Why feature scaling is essential for distance-based models
  • Choosing k with cross-validation
  • The strengths and weaknesses of KNN

How KNN Works

  1. Store all the training examples.
  2. For a new point, measure its distance to every stored example, usually the straight-line (Euclidean) distance.
  3. Take the k closest examples, its neighbours.
  4. Classification: predict the most common class among them. Regression (KNeighborsRegressor): predict the average of their values.

Because all the work happens at prediction time, KNN is called a lazy learner. Training is instant, but predicting can be slow on large datasets.

Scaling Makes or Breaks KNN

The wine dataset has 13 chemical measurements for 178 wines from three growers. Some features are small numbers, such as hue at around 1, while proline runs into the hundreds and above 1,000.

from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

X, y = load_wine(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, random_state=1, stratify=y
)

raw = KNeighborsClassifier(n_neighbors=5).fit(X_train, y_train)
scaled = make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=5)).fit(X_train, y_train)

print(f"KNN without scaling: {raw.score(X_test, y_test):.3f}")
print(f"KNN with scaling:    {scaled.score(X_test, y_test):.3f}")

Output

KNN without scaling: 0.644
KNN with scaling:    0.933
  • Without scaling, distance is dominated by the feature with the largest numbers, proline, so the other twelve features barely count. Accuracy is only 64%.
  • StandardScaler gives every feature a mean of 0 and a standard deviation of 1, so each one has a fair say. Accuracy jumps to 93%.
  • Putting the scaler and model in a pipeline ensures the scaler learns its settings from the training data only.

Choosing k

from sklearn.datasets import load_wine
from sklearn.model_selection import cross_val_score
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

X, y = load_wine(return_X_y=True)
for k in [1, 3, 5, 9, 15, 31]:
    model = make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=k))
    scores = cross_val_score(model, X, y, cv=5)
    print(f"k = {k:2d}: mean accuracy {scores.mean():.3f}")

Output

k =  1: mean accuracy 0.950
k =  3: mean accuracy 0.944
k =  5: mean accuracy 0.949
k =  9: mean accuracy 0.966
k = 15: mean accuracy 0.955
k = 31: mean accuracy 0.966
  • Small k (such as 1) follows every quirk of the training data, including noise. That is a high-variance model that can overfit.
  • Large k smooths decisions over many neighbours and eventually ignores real local patterns; at the extreme it always predicts the most common class.
  • cross_val_score trains and tests on 5 different splits and averages the results, a fairer way to compare settings than one split. Here k = 9 and k = 31 tie, and the simpler choice is usually the smaller, cheaper one that performs as well.
  • For two classes, an odd k avoids tied votes.

Strengths and Weaknesses

StrengthsWeaknesses
Simple to understand and explainSlow predictions on large datasets
No training timeNeeds feature scaling
Handles any number of classes naturallyStruggles with many features (the “curse of dimensionality”)
Captures irregular boundariesSensitive to irrelevant features

Common Mistakes

  1. Forgetting to scale the features.
  2. Choosing k from the test set instead of cross-validation on the training data.
  3. Using KNN with dozens of irrelevant features, which makes every point seem equally far away.
  4. Using it on millions of rows without an indexing method, so predictions crawl.

Practice Exercises

Exercise 1. Compute the Euclidean distance between (1, 2) and (4, 6).

Show answer

√((4 − 1)² + (6 − 2)²) = √(9 + 16) = √25 = 5. In NumPy: np.linalg.norm(np.array([4, 6]) - np.array([1, 2])).

Exercise 2. Try weights="distance" in KNeighborsClassifier. What does it change?

Show answer

Closer neighbours get a bigger vote than distant ones, instead of every neighbour counting equally. It often helps when k is fairly large.

Frequently Asked Questions

Is KNN the same as k-means?

No. KNN is supervised: it uses labelled examples to classify new points. K-means is unsupervised: it groups unlabelled data into k clusters. Both happen to use a “k” and distances.

What is a good default value of k?

scikit-learn uses 5. A common rule of thumb is around the square root of the number of training samples, but cross-validation should make the final choice.

Summary

  • KNN predicts from the majority of the k closest training examples.
  • Always scale features, ideally inside a pipeline.
  • Small k can overfit; large k can underfit; choose with cross-validation.
  • It is simple and flexible but slow and weak with many features.

Next: Decision Trees and Random Forests.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *