Skip to chapter content
navan✳THE BUILD LABMACHINE LEARNING / GUIDE
0/28 read
CHAPTER 10 / 28 · SUPERVISED MODELS

Learning from nearby examples.

Understand distance, neighbor count, scaling, and the local nature of k-nearest neighbors.

BY NAVAN SAMILONG READTHEORY FIRST
01 / FROM THE BEGINNING

Start with the meaning.

The nearest-neighbor idea is close to a human analogy: a new case may resemble past cases, so their answers can guide its prediction. In k-nearest neighbors, k is the number of nearby training examples considered. For classification, the nearby labels vote; for regression, their numeric targets can be averaged. The model stores training examples rather than learning a short equation. A prediction therefore depends on how “near” is defined and which examples are available.

For two numeric features, distance might be the straight-line distance between points on a chart. This is Euclidean distance. If a row has area and number of rooms, the difference in area may be measured in tens while the room difference is only one or two. Without scaling, area can dominate the distance calculation regardless of importance. A preprocessing step can put features on comparable scales, but that step must learn its scaling values from training data only.

02 / THE MODEL

How the idea works.

With k = 1, a new point copies the label of its single closest training point. This can be sensitive to a mislabeled or unusual example. Increasing k smooths the decision by consulting more neighbors. Too large a k can ignore meaningful local structure and favor the majority class everywhere. The best value depends on the data and is chosen using validation, not by looking at the final test answers.

Distance is not equally meaningful for every representation. One-hot categories, text vectors, and high-dimensional numerical data can make an ordinary geometric distance behave differently from human similarity. In many dimensions, most points can become relatively far from one another, weakening the intuition of a tiny local neighborhood. The choice of features and distance metric is part of the model, even though it may look like a setup detail.

Prediction cost can grow with the number of stored examples because the algorithm may need to compare a new case with many training rows. Some data structures accelerate particular searches, but very large or high-dimensional datasets can still be costly. KNN is useful as an interpretable baseline when a meaningful distance exists and local similarity is a plausible explanation for the target.

new caselabelled neighbors
A new point is classified using nearby labelled training points under a chosen distance.
03 / PYTHON, EXPLAINED

Follow the code.

nearest-neighbors.py
from sklearn.neighbors import KNeighborsClassifier

X = [[1.0], [1.2], [4.0], [4.2]]
y = ["low", "low", "high", "high"]
model = KNeighborsClassifier(n_neighbors=3)
model.fit(X, y)
print(model.predict([[1.1]]))

Each inner list is a one-feature training row. The first two values belong to low and the next two to high. The model is configured to consult three neighbors. fit stores the training rows and labels. For 1.1, the closest rows are 1.0, 1.2, and 4.0; two vote low and one votes high, so the printed prediction is ['low']. The square brackets in the result indicate an array of predictions, one for each input row supplied to predict.

This small example is intentionally one-dimensional so distance is easy to picture. The 4.0 row is far away yet still enters the vote because k requests three neighbors from only four training rows. With more dense data, the third neighbor may be much closer. The model has no understanding of what “low” means beyond the labels supplied.

04 / THE BOUNDARY

What the result does not say.

KNN does not automatically know which feature deserves more weight. Rescaling a column can change every neighbor relationship and every prediction. A proper evaluation therefore treats the scaler and neighbor model as one pipeline.

A neighbor-based explanation can show the similar past cases behind one prediction, but similar-looking cases are not always causally related. If a dataset omits a crucial factor, proximity in recorded features may be false reassurance.

05 / KEEP THIS

One clear idea.

KNN predicts from nearby training cases; distance, scale, and k determine what nearby means.

THE CODE IN CONTEXT

The ML cookbook

Complete, explained Python workflows sit alongside this reading course.

Browse the cookbook
Finished reading?
Built with curiosity. By Navan Sami. ↗Machine learning with Python · From examples to trustworthy models.