k-Nearest Neighbors › Example
Machine Learning from ScratchAll chapters k-Nearest Neighbors › ExampleSection view · Sections in this chapter6 / 10 ↓
Reading tools Definitions, links & notes
Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.
Article links
Make inline references clickable
Before trusting code, it is worth carrying out one prediction entirely by hand. A single worked example with confirms that every operation (distance, ranking, tie-breaking, voting, averaging) is exactly what we think it is, and it exposes the one place where the rules leave us a choice.
Suppose a two-dimensional binary classification training set contains five points:
The query is . Class-0 points sit near the origin, and class-1 points form a diagonal ridge going out toward , so the query lies between the two groups and the class votes are close. That is deliberate: an ambiguous query is exactly where the mechanics become visible.
Step 1: compute Euclidean distances to every training point.
For :
For :
For :
For :
For :
The distances already show the ranking: and are closest and exactly tied, and form the next tier, and is farthest. How we resolve the ties will decide which points enter the neighborhood, so it is worth handling them explicitly.
Step 2: sort the distances in increasing order:
Notice that and are exactly tied at , and and are tied at . Duplicate inputs or rounded and discrete features can produce exact ties in any dimension. This hand-designed coordinate set makes their effect visible. When they occur, we need a deterministic rule. We break equal-distance ties by training-row order, using np.argsort(..., kind="stable") in the implementation. If a class vote is tied, our classifiers choose the smallest class label. A different distance-tie rule can change the selected neighbor at the cutoff and therefore change the prediction.
Step 3: select the nearest neighbors. The first three sorted indices are . Their labels are , , and .
Step 4: count votes. Class 0 receives two votes and class 1 receives one vote. The majority class is therefore class 0, and our kNN prediction is .
We can now check what happens with weighted voting. Suppose we use . The weights for the three neighbors are:
where:
- : weight assigned to neighbor , equal to the reciprocal of its squared distance
- : Euclidean distance from the query to neighbor
Class 0 weight is ; class 1 weight is . Weighted voting still predicts class 0, but the margin is now narrow. Uniform voting predicted class 0 by a 2-to-1 vote; weighted voting predicts it by 2.22 versus 2.00. This illustrates how sensitive predictions near the decision boundary can be: the same neighbor set can carry very different levels of confidence depending on how much each neighbor is allowed to count.
Step 5 (regression analogue). If the same five training points had numeric labels as targets for a regression task, uniform kNN with would produce the local average
This is the same set of neighbors, but now the answer is a continuous value rather than a class, and each observed label is contributing equally to the prediction. The result sits between the class-0 and class-1 values, which is what a local average should do. The uniform average is, in effect, the least-squares minimizer over the local neighborhood, the same justification used in the OLS chapter, restricted here to three nearby examples.
Comments
Add to the conversation
A question, a correction, or an example from your own work.
No comments yet. Be the first to share your thoughts!