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 -nearest neighbours (-NN):
- Work out the distance from the new example to every labelled one.
- Take the nearest.
- Let them vote; the most common label wins.
Click anywhere on the plot to try a new penguin. Change , and turn on the regions to see how -NN would label every spot:
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 -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.
In words: for each feature , the gap between the two examples, squared; add them up; take the square root. In NumPy, for one new example against all of at once: np.sqrt(((X - new) ** 2).sum(axis=1)), broadcasting from lesson 0.6.
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.
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 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 does. With , 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 , the borders smooth out, but a big starts outvoting small groups. 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 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:
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. -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.
In words: for each feature , how many standard deviations this value is from that feature's mean. In NumPy: (X - X.mean(axis=0)) / X.std(axis=0).
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: -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
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.
- Cover and Hart, Nearest neighbor pattern classification, IEEE Transactions on Information Theory 13(1), 1967: the paper that studied the nearest-neighbour rule
- scikit-learn: Nearest Neighbors Classification: how KNeighborsClassifier votes, and choosing k
- scikit-learn: KNeighborsClassifier: fit, predict and predict_proba
- Horst, Hill and Gorman, palmerpenguins: Palmer Archipelago (Antarctica) penguin data, 2020: the penguins dataset, released under CC0