k-Nearest Neighbours
Context: FIT2086_MOC · the model-free alternative to Logistic Regression / linear regression and to trees · handles both classification and regression · tuned by leave-one-out Cross-Validation Parent Framework: Classification and Conditional Class Probabilities
Quick Revision
- 🎯 Objective: find the training individuals closest to ➔ vote (classification) or average (regression) their targets ➔ that is the prediction.
- 📦 Core Components: distance | neighbourhood size | prediction function (vote / mean / kernel-weighted mean) ➔ all chosen by LOO CV.
- ⚠️ Key Constraint: distances are only meaningful on comparable scales ➔ standardise predictors first, or the largest-unit predictor decides who is “near”.
📝 How It Works
1. Idea
- No model fitted ➔ keep the pairs ; predict the target of a new individual from its most similar individuals.
- Very weak assumption ➔ individuals similar in predictor values are similar in targets — nothing about linearity or a distribution.
- Reused without a target (W11) ➔ ignore missing values in the distance and predict each missing entry from the other columns ➔ imputation / collaborative filtering in Missing Data Imputation and Recommender Systems.
2. Distance
- Euclidean (default) ➔ .
- Not always best ➔ categorical predictors need other measures; different distances give different neighbours and predictions.
- Scaling ➔ predictors are usually standardised before computing distances.
3. Algorithm
- Compute for every training individual .
- Sort from smallest to largest ; relabel targets ( = closest, = furthest).
- Predict from the nearest.
4. Prediction Function
- Classification ➔ voting: the class most frequent among the neighbours.
- Regression ➔ averaging: .
- Weighted averaging ➔ with decreasing in ⟹ further neighbours count less; is a kernel function (e.g. uniform, inverse distance, Gaussian).
kknnkernels (Studio 9) ➔"rectangular"= plain averaging (all equal);"triangular","epanechnikov","gaussian","rank","optimal"weight neighbours by distance ➔train.kknnCV pickedgaussian, on the diabetes data ➔ Trees, Forests and kNN in R (rpart, randomForest, kknn).
5. Tuning by Leave-One-Out CV
- Tunables ➔ neighbourhood size · distance function · kernel weighting function.
- LOO CV ➔ for each parameter combination: predict every by kNN with removed from the training set ➔ accumulate the error (0/1 for classification, squared error for regression) ➔ choose the combination with the smallest total.
- Why LOO fits kNN ➔ there is no model to refit, so leaving one out costs only one more distance sort.
6. Strengths and Weaknesses
- Strengths ➔ very weak assumptions · very little model-fitting or training · handles continuous and categorical predictors.
- Weaknesses ➔ lots to configure (, “nearest”, weighting, whether all predictors count equally) · can perform poorly in high-dimensional predictor spaces · predictor selection is not straightforward · no interpretability.
⚖️ Core Decision Matrix
| Prediction rule | Target | Formula | Neighbour influence |
|---|---|---|---|
| Voting | categorical | most frequent class among | all equal |
| Averaging | numerical | all equal | |
| Kernel-weighted averaging | numerical (or class probabilities) | closer ⟹ heavier |
When It Flips: the -th neighbour is much further than the first ➔ unweighted rules let it count as much as the closest point; switch to a decreasing kernel .
📊 Exam Execution Trace & Applied Exercises
Manual Execution Trace
Nearest labels in rank order: 1 Disease · 2 No · 3 Disease · 4 No · 5 No · 6 Disease.
| Neighbours used | Disease votes | No-disease votes | Prediction | |
|---|---|---|---|---|
| rank 1 | Disease | |||
| ranks 1–3 | Disease | |||
| ranks 1–5 | No disease | |||
| ranks 1–6 | tie — even can tie in a two-class vote |
- Reading ➔ the same individual flips class as changes ⟹ is a genuine model choice, set by LOO CV. Lecture pictures: neighbours all diseased ⟹ Disease; with 3 of 4 healthy ⟹ No disease.
Applied Exercise
Problem: the nearest neighbours have targets with kernel weights (closest first). Give the plain and the weighted kNN regression predictions.
Final Extracted Output: unweighted; weighted — pulled towards the closest neighbour’s .
⚠️ Common Mistakes
- 💡 Forgetting to divide by ➔ the weighted mean needs the weights normalised; it only looks unnecessary when they already sum to .
- 💡 Distances on raw units ➔ a predictor in thousands swamps one in single digits; standardise first.
- 💡 Choosing on training error ➔ with left in, always “predicts” perfectly (its nearest neighbour is itself); leave it out (LOO).
🧠 Active Recall
kNN "does not produce a model". What does it store, and where does the work happen?
Answer
- Short answer: It stores the training pairs; all work happens at prediction time — distances to every training point, a sort, then a vote or average.
- Why: No fitting step ➔ nothing like is estimated, which is why LOO CV is cheap and why there is nothing to interpret.
Why standardise predictors before kNN, and what goes wrong if you don't?
Answer
- Short answer: Euclidean distance adds squared differences across predictors, so the predictor with the largest numeric scale dominates who counts as “nearest”.
- Why: Scale, not relevance ➔ has no per-predictor weight; standardising gives each predictor a comparable spread.
How would you choose , the distance and the kernel?
Answer
- Short answer: Leave-one-out CV over a grid of combinations — predict each with it removed, sum the errors, keep the smallest.
- Why: Held-out error ➔ each is predicted from data that excludes it, estimating error on future individuals.
🔭 Beyond the lecture (not in the slides)
- as a complexity dial ➔ small ⟹ jagged, low-bias/high-variance boundary; large ⟹ smoother, higher bias; predicts the overall majority / mean for everyone.
- Use odd for two classes ➔ avoids vote ties.