What learning is · lesson 4 of 13
Parts in this lesson
Anp.sqrt(((X - new) ** 2).sum(axis=1))distance to every known example (from 1.2)
Bnp.argsort(dist)[:k]the k nearest
CKNeighborsClassifier(n_neighbors=5).fit(X, y)the scikit-learn model
D(X - X.mean(axis=0)) / X.std(axis=0)standardising each feature (from 0.5)

Your first model: nearest neighbours

Last updated

Your first model needs no maths beyond lesson 1.2’s distance. To label a new penguin, find the penguins in the data that are most like it, and go with what most of them are. That’s k-nearest neighbours. You’ll run it by hand in NumPy, then with scikit-learn, and meet the mistake that ruins it more often than any other: forgetting that features are measured on different scales.

By the end of this lesson you can

  • Classify a new example with k-nearest neighbours, by hand and with KNeighborsClassifier
  • Explain what k does, and read the vote as a probability
  • Standardise features so that one measured in big units doesn’t swamp the rest

Look at the closest examples

A biologist hands you a penguin with a 45 mm bill, 17 mm deep, and asks its species. A sensible answer: look up the penguins you already know with bills most like that, and see what they are. If most of the closest ones are Chinstraps, say Chinstrap.

That's the whole of k-nearest neighbours (k-NN):

  1. Work out the distance from the new example to every labelled one.
  2. Take the k nearest.
  3. Let them vote; the most common label wins.

Click anywhere on the plot to try a new penguin. Change k, and turn on the regions to see how k-NN would label every spot:

Neighbour circlesk = 5
35404550551416182022bill length (mm)bill depth (mm)AdelieChinstrapGentoo

The 5 nearest penguins, all within 0.7 mm: 3 Chinstrap, 2 Gentoo. The vote says Chinstrap. Click anywhere on the plot to move the new penguin.

Notice that k-NN never builds a formula. "Training" is just remembering the data; all the work happens when you ask for a prediction. That makes it easy to understand, and slow on big datasets, since every prediction measures the distance to every remembered example.

Distance and voting, by hand

The distance is lesson 1.2's: subtract, square, add up, square root.

d(x,x′)=∑j=1d(xj−xj′)2

In words: for each feature j, the gap between the two examples, squared; add them up; take the square root. In NumPy, for one new example against all of X at once: np.sqrt(((X - new) ** 2).sum(axis=1)), broadcasting from lesson 0.6.

knn.ipynb

np.argsort gives the positions that would sort the distances, so its first 5 entries are the 5 nearest penguins: three Chinstraps and two Gentoos, all within 0.7 mm. np.unique(..., return_counts=True) counts the votes. Chinstrap wins, 3 to 2.

k-NN with scikit-learn

scikit-learn's KNeighborsClassifier does the same, with the pattern every scikit-learn model follows: make it, fit it to the training data, then predict.

knn.ipynb

The first penguin comes out Chinstrap, as by hand. predict_proba shows the vote as fractions: 0 Adelie, 0.6 Chinstrap, 0.4 Gentoo, which is 3 of 5 and 2 of 5. It's a rough probability: with k=5 it can only be a multiple of 0.2, but it already says this penguin is a close call, which a bare label hides.

What k does. With k=1, the single nearest penguin decides, so one odd penguin creates a little island of its own label (try it with the regions on). With a large k, the borders smooth out, but a big k starts outvoting small groups. k is a hyperparameter: a setting you choose, not something the model learns from data. Lessons 2.6 and 2.9 show how to choose it honestly. For two classes, pick an odd k so there's no tie.

Wrong way: forgetting to scale

Distance adds up gaps in each feature's own units. Look at two penguins measured by flipper length and bill depth:

scale.ipynb

The flippers differ by 5 mm and the bills by 1.3 mm. Squared, that's 25 against 1.69: the flipper gap counts nearly 15 times as much, only because flippers are long numbers. Add body mass in grams and it's worse: a 100 g difference squares to 10,000 and swamps everything. k-NN would then be a "nearest in body mass" model, ignoring the bill entirely.

The fix is to standardise each feature (lesson 0.5): subtract its mean and divide by its standard deviation, so every feature is in "standard deviations from typical", with no units.

xj′=xj−μjσj

In words: for each feature j, how many standard deviations this value is from that feature's mean. In NumPy: (X - X.mean(axis=0)) / X.std(axis=0).

scale.ipynb

The same model on the same three features: 78.4% right unscaled, 95.9% scaled. (cross_val_score measures the share right on penguins each model hasn't seen; lessons 2.5 and 2.9 explain it.) Any model built on distances needs this: k-NN, k-means clustering (lesson 4.8), support vector machines (lesson 4.7). Lesson 2.10 shows the right place in your code to do it, because it's easy to do in a way that cheats.

Check what you learned

With k=3, a new penguin’s nearest three are Adelie, Gentoo, Adelie. What does k-NN say?
Predict, then check with the figure: you set k=1 and turn on the regions. What happens to the borders between species?
Features are bill length in mm and body mass in g, unscaled. Which feature will decide k-NN’s neighbours?

Sources

Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.

All sources for Simple Machine Learning