Machine Learning with scikit-learn

KNN in Python with scikit-learn (k-Nearest Neighbors)

Classify a point by asking its k nearest neighbours to vote, and see why scaling and the choice of k matter.

  • Intermediate
  • 3 min read
  • 1 runnable example
What you'll learn
  • KNeighborsClassifier and n_neighbors
  • Why distances need scaled features
  • Finding the neighbours with kneighbors
Wine test accuracy
No scaling
  • k=5: 0.722
With scaling
  • k=1: 1.000
  • k=5: 0.963
  • k=15: 0.981

Ask the neighbours

The problem

You want to classify new items by comparing them with examples you already know, without building a complicated model. Similar items should get the same label.

Think of it like this

KNN is like guessing which team a new player supports by looking at the five people sitting closest to them in the stadium and taking a vote. With one neighbour the guess is jumpy; with more neighbours it is steadier.

From stadium seats to code
fit(X_train, y_train)🏟️ Remember where everyone sits
StandardScaler()📏 Measure every direction in the same units
n_neighbors=5👥 Look at the 5 closest people
predict(X_test)🗳️ Take the majority vote
The closest k examples vote.
In one sentence

k-nearest neighbors predicts the class of a point from the most common class among the k training points closest to it.

Key points

  1. Without scaling, accuracy is only 0.722 because proline decides the distances.
  2. With StandardScaler in the pipeline, accuracy rises to between 0.963 and 1.000.
  3. n_neighbors=1 copies the nearest point; larger k gives smoother decisions.
  4. kneighbors returns the distances and indexes of the closest training rows.

When should you use it?

  • Small datasets where a simple, explainable model is enough.
  • Recommendation and "find similar items" features.
  • A baseline to compare other classifiers with.

When not to use it

  • Very large datasets: every prediction compares against all training rows.
  • Many features: distances become less meaningful in high dimensions.

Example code

Open in editor →
main.py
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.3, random_state=0, stratify=y)

# Without scaling, the large "proline" column dominates the distances
raw = KNeighborsClassifier(n_neighbors=5).fit(X_train, y_train)
print(f"k=5 without scaling: {raw.score(X_test, y_test):.3f}")

for k in [1, 3, 5, 9, 15]:
    model = make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=k))
    model.fit(X_train, y_train)
    print(f"k={k:<2} with scaling:    {model.score(X_test, y_test):.3f}")

knn = model[-1]
distances, indexes = knn.kneighbors(model[0].transform(X_test[:1]), n_neighbors=3)
print("3 nearest training rows:", indexes[0].tolist(), "classes", y_train[indexes[0]].tolist())
Get a Run button for this example

Result of running the code

k=5 without scaling: 0.722
k=1  with scaling:    1.000
k=3  with scaling:    0.963
k=5  with scaling:    0.963
k=9  with scaling:    0.963
k=15 with scaling:    0.981
3 nearest training rows: [70, 60, 73] classes [0, 0, 0]

Code explanation

Without scaling, the proline column (values in the hundreds) decides almost every distance and the model reaches only 0.722 accuracy. Inside the pipeline StandardScaler puts all 13 columns on the same scale, and accuracy jumps to 0.963-1.000. The loop tries k from 1 to 15: k=1 copies the single nearest neighbour, larger k votes over more points and gives smoother decisions. kneighbors shows the three training rows closest to the first test wine, all of class 0.

Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.

Practice exercises

Modify the runnable example with the exercises below to build understanding beyond copying the result.

  1. Change random_state and see how much the score moves.
  2. Swap in another built-in dataset (wine, breast_cancer, digits) and rerun.
  3. Try a different model or hyperparameter and compare the scores.
Run in the Python compiler →

Common mistakes

Using KNN on unscaled features

The column with the largest numbers dominates every distance.

Problem
KNeighborsClassifier(n_neighbors=5).fit(X_train, y_train)
Fix
make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=5)).fit(X_train, y_train)

Finished this lesson?

Mark it as learned to track your progress.

Practice with a challenge

Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.

All challenges

Tools for this lesson