Module 4 — k-Nearest-Neighbour Decision Rules

Source: Lec 9 — k-Nearest Neighbor Decision Rule. · Prev: Module 3 · Next: Module 5 — Regression · Index: 00_INDEX_and_Coverage

Setup

Training pairs , , , , . Test point . Distance (default Euclidean).


C23. The kNN Decision Rule

Intuition

“Tell me who your neighbours are and I will tell you who you are.” Find the training points closest to the new point and let them vote. Like asking the 3 nearest shops whether a new product sells — you trust people who live closest.

 x2
  6 |  B       ← B cluster
  5 |  B  B
    |
  2 |   ●?     ← query (k=3): neighbours A(1.0) A(1.4) B(4.2)  →  A
  1 | A  A
    +------------→ x1

Algorithm (lecture)

  1. Compute for all .
  2. Sort the distances in non-decreasing order.
  3. Take the first (the nearest neighbours).
  4. Let be the number of those points in class . Assign to class if . Ties are broken arbitrarily.

Geometrically, the neighbourhood is the closed disk of radius .

Mathematical facts

  • Choice of : no universal rule; estimate by cross-validation (C13). Small ⇒ low bias, high variance (jagged boundary); large ⇒ smoother, may swamp small classes.
  • 1-NN asymptotics (Cover & Hart 1967): as , the 1-NN error is at most twice the Bayes error . More precisely, for two classes .
  • Cost: no training, per query.

Derivation of the 1-NN limit (two classes)

Let . As the nearest neighbour of converges to , so its label is an independent draw with . 1-NN errs when the test label and the neighbour’s label differ: Let ; then . Taking expectations (with ): , because Jensen gives . ∎

Key insights

  • Distance function and feature scaling dominate the behaviour.
  • Majority voting is unreliable when the top two classes are nearly tied (the lecture’s motivation for the variants C24–C25).

Worked examples

Example 1 — Very Easy · Healthy or diseased plant?

  • Problem: Two leaf-sensor readings per plant. Training: A, A, B, B, B (A = healthy, B = diseased). Classify with (Euclidean).
  • Asked: Class.
  • Concept: kNN.
  • Approach: Distances, sort, vote.
  • Solution: ; ; ; ; . Sorted: . Votes: A = 2, B = 1.
  • Final answer: A.

Key lesson

Only the closest matter; the two B points at distance 5 never vote.

Example 2 — Easy · The vote flips with

  • Problem: The sorted neighbour labels of (nearest first) are . Classify for .
  • Asked: Four decisions.
  • Concept: Dependence on .
  • Approach: Count in prefixes.
  • Solution:
decision
523
633tie
743
954
  • Final answer: , tie, , .

Key lesson

The prediction flips with when the vote is nearly even.

Example 3 — Moderate · How good can 1-NN be?

  • Problem: Two classes with Bayes error . Bound the asymptotic 1-NN error. Repeat for .
  • Asked: Two bounds.
  • Concept: Cover–Hart.
  • Approach: vs .
  • Solution: : (crude: ). : (crude: ).
  • Final answer: and .

Key lesson

The bound is tight when is small, loose when large (it cannot exceed ).

Example 4 — Hard · Why you must scale features

  • Problem: Features (age in years, income in ₹). Training: , . Test . Feature standard deviations: age , income . Classify by 1-NN raw and after standardising (divide differences by the std).
  • Asked: Two decisions.
  • Concept: Feature scaling.
  • Approach: Compute both distances twice.
  • Solution: Raw: ; ⇒ A. Scaled: , ; , ⇒ B.
  • Final answer: Raw → A; scaled → B.

Key lesson

Without normalisation the large-unit feature (income) is the only feature that matters.

Example 5 — Very Hard · Cover–Hart on a two-region world

  • Problem: Half of the input space has , the other half . Compute (a) the Bayes error, (b) the asymptotic 1-NN error, (c) , and confirm (b) (c) .
  • Asked: Three numbers and verification.
  • Concept: Cover–Hart derivation.
  • Approach: Local errors, then average.
  • Solution: (a) Local Bayes: and . . (b) Local 1-NN: and . . (c) ; . Chain: ✓.
  • Final answer: , , bound .
regionBayes 1-NN
half 10.90.100.18
half 20.50.500.50
average0.300.34

Key lesson

1-NN pays extra only where the posterior is neither pure nor 50/50.

Common mistakes

  • Not scaling features.
  • Using even in 2-class problems (ties).
  • Believing 1-NN error is always twice Bayes (it is an upper bound).

Exam traps

  • Ties are broken arbitrarily.
  • “Optimal ” is found by cross-validation; there is no formula.
  • The bound requires .

Connections: Bayes error (C15), cross-validation (C13), weighted / Tweaked kNN (C24, C25), k-means assignment (C36).

Mastery checklist

  • Run kNN by hand.
  • Explain the effect of and of scaling.
  • Derive for 1-NN.

C24. Distance-Weighted kNN

Intuition

A neighbour 1 cm away should speak louder than one 10 km away. Give each of the neighbours a weight that decreases with distance.

Formal definition (Dudani 1976, as in the lecture)

Let be the nearest neighbours sorted by distance , so . Assign to the class whose neighbours’ weights sum to the greatest value.

 weight
 1.0 |●
     |   ●
     |        ●        weights fall linearly from 1 (nearest)
 0.0 +-----------●→ d   to 0 (k-th neighbour)
       d1  d2   dk

Properties

  • (nearest) and (farthest), linear in between.
  • It reduces sensitivity to the arbitrary cut-off, but must still be chosen.

Worked examples

Example 1 — Very Easy · Compute the weights

  • Problem: Distances for . Weights?
  • Asked: .
  • Concept: Linear weighting.
  • Approach: .
  • Solution: ; ; .
  • Final answer: .

Key lesson

The farthest neighbour always gets weight 0.

Example 2 — Easy · Plain vs weighted vote

  • Problem: Neighbour labels (nearest first) with the distances above. Plain vote vs weighted vote.
  • Asked: Two classes.
  • Concept: Weighted voting.
  • Approach: Sum the weights per class.
  • Solution: Plain: A = 1, B = 2 ⇒ B. Weighted: A ; B ⇒ A.
  • Final answer: Plain → B; weighted → A.

Key lesson

One very close point can outweigh two distant ones.

Example 3 — Moderate · All distances equal

  • Problem: with labels . Weights and decision.
  • Asked: Weights, class.
  • Concept: Degenerate case .
  • Approach: Use the "" branch.
  • Solution: All ⇒ A , B ⇒ B (ordinary kNN).
  • Final answer: B.

Key lesson

The formula degrades gracefully to majority vote.

Example 4 — Hard · Five neighbours

  • Problem: with distances and labels . Compute weights and compare plain majority vs weighted.
  • Asked: Weights, both decisions.
  • Concept: Weighted kNN.
  • Approach: , , denominator .
  • Solution: . Class A: . Class B: . Plain majority: A , B ⇒ A. Weighted ⇒ B.
  • Final answer: Plain → A; weighted → B.

Key lesson

Close neighbours (B, B) outweigh far ones (A, A).

Example 5 — Very Hard · Weighted kNN can collapse to 1-NN

  • Problem: Show (i) the weighted rule with neighbours ignores the th, so it uses only the nearer neighbours; (ii) construct distances where weighted kNN is identical to 1-NN regardless of the other labels.
  • Asked: Proof and construction.
  • Concept: Weight structure.
  • Approach: Algebra.
  • Solution: (i) always, so never contributes. The remaining weights are , ; they depend on — so still controls the scale of the weighting. (ii) Let with labels . Weights: ; ; . Class A ; B ⇒ A, the 1-NN label, even though a majority of 3 says B.
  • Final answer: Weighted kNN can behave like 1-NN when the nearest neighbour is much closer than the rest.

Key lesson

The weighting depends on relative distances; an outlier in distance can make the rule effectively 1-NN.

Common mistakes

  • Forgetting .
  • Using weights and calling them the lecture formula.

Exam traps

  • Weights use in the numerator, in the denominator.
  • You still need a valid .

Connections: C23, C25.

Mastery checklist

  • Compute linear distance weights.
  • Explain when weighted and plain kNN disagree.

C25. Tweaked kNN (TkNN): Bounded Majority Voting

Intuition

Instead of fixing , keep widening the neighbourhood until the winner leads the runner-up by a margin . If no margin is ever reached, refuse to classify. A single, more interpretable parameter replaces .

flowchart TD
    S[Sort neighbours] --> I["L ← β"]
    I --> C{"margin = L_max1 − L_max2 = β ?"}
    C -->|yes| O[Output majority class]
    C -->|no| G["L ← L+1"]
    G --> E{"L > n ?"}
    E -->|no| C
    E -->|yes| U[Unclassified]

Algorithm (lecture)

  1. Compute and sort distances .
  2. (a positive integer).
  3. Take the first neighbours; let be the class counts. ; = second largest.
  4. If ⇒ output the majority class. Else and repeat. If ⇒ is unclassified.

Properties

  • ⇒ the rule equals 1-NN (at the margin is already ).
  • Larger ⇒ more cautious, more abstentions.
  • Choose by cross-validation. It does not consider the quality of the voting neighbours (open problem noted in the lecture).

Worked examples

Example 1 — Very Easy · β = 1 is 1-NN

  • Problem: Show TkNN with equals 1-NN.
  • Asked: Proof.
  • Concept: Margin definition.
  • Approach: Start at .
  • Solution: At : the top class has count 1, every other has 0 ⇒ margin ⇒ stop, output the class of the nearest neighbour.
  • Final answer: Yes.

Key lesson

is the most permissive setting.

Example 2 — Easy · The alternating sequence

  • Problem: The sequence (nearest first) (the lecture’s 9.1). Run TkNN with and .
  • Asked: Output.
  • Concept: Algorithm.
  • Approach: Track the margin.
  • Solution: : : counts margin ⇒ . :
23456789
counts (1,1)(2,1)(2,2)(2,3)(3,3)(4,3)(4,4)(5,4)
margin01010101

Never reaches ; ⇒ unclassified.

  • Final answer: ; unclassified.

Key lesson

The lecture’s remark “for cannot classify” is verified; an alternating sequence never builds a margin.

Example 3 — Moderate · Adaptive k

  • Problem: Sequence with . Output and the effective .
  • Asked: Class and .
  • Concept: Adaptive .
  • Approach: Margin tracking.
  • Solution: : margin 0. : margin 1. : margin ⇒ stop.
  • Final answer: with .

Key lesson

The effective depends on the query.

Example 4 — Hard · Three classes

  • Problem: Three classes ; sequence ; . Find the output and .
  • Asked: Class and .
  • Concept: with three classes.
  • Approach: Counts at each .
  • Solution: : margin 0. : margin 0. : margin 1. : margin 0. : margin 1. : margin ⇒ stop.
  • Final answer: at .

Key lesson

The margin is against the second best class, not the average of the others.

Example 5 — Very Hard · Why the margin is exactly β

  • Problem: Show that TkNN can only ever stop when and that the margin at stopping is exactly (not larger). Then argue why overshooting is impossible.
  • Asked: Two proofs.
  • Concept: Margin dynamics.
  • Approach: One-step margin changes.
  • Solution: The margin is at most (all neighbours in one class), so stopping requires — matching the initial . When increases by 1, exactly one class count increases by 1: if it is the leader, rises by 1; if it is the runner-up, falls by 1; otherwise is unchanged. So and cannot jump over : the first time it equals . (At the start we have .)
  • Final answer: The stopping margin is exactly .

Key lesson

The test "" is equivalent to "", because moves in unit steps.

Common mistakes

  • Starting with instead of (harmless, but not the lecture’s algorithm).
  • Forgetting to return “unclassified”.

Exam traps

  • ⇒ 1-NN.
  • No is needed, but is.

Connections: C23, C24, cross-validation (C13).

Mastery checklist

  • Run TkNN on a label sequence.
  • Explain why is 1-NN.
  • State when it abstains.