Unit 5 of 8 · about 3 hours · implement, measure

k-nearest neighbors, search cost and the curse of dimensionality

kNN is the purest similarity classifier: no training, all geometry. It punishes unscaled features and high dimensions faster than any other family, which makes it the ideal instrument for learning scale discipline.

You'll be able to

  • Implement brute-force kNN with uniform and distance weights and match sklearn predictions including a distance tie.
  • Explain how neighborhood size, weighting and feature scale move bias, variance and cost, and when trees lose to brute force.
  • Measure distance concentration and search time as dimension grows and state the scaling policy you would ship.

Covers

k-nearest neighbors, distance, weighting and feature scaleNeighbor search cost and the curse of dimensionality
1

Read

In this order, only the parts listed

0 of 3 done

  1. Murphy Chapter 16: KNN and the curse of dimensionalityProbabilistic Machine Learning, Chapter 16: exemplar-based methods

    Sections 16.1 to 16.1.3 (pp. 547 to 550): the KNN decision rule, the curse of dimensionality with the growing-hypercube example, and k-d trees, hashing and approximate search for speed

  2. sklearn neighbors: classification, regression and weightsscikit-learn - neighbors, SVMs, trees and ensembles

    1.6.2 Classification and 1.6.3 Regression: n_neighbors default 5, uniform versus distance weights, and the regressor averaging rule

  3. sklearn neighbor search algorithms and costscikit-learn - neighbors, SVMs, trees and ensembles

    1.6.4 Nearest Neighbor Algorithms: brute force against K-D and ball trees, the auto-selection rule with leaf_size 30, and when high dimension or sparse input falls back to brute force

2

Focus on

  • The vote is a majority under uniform weights and an inverse-distance vote under distance weights. On the toy, query 2.5 has and tied for third place. sklearn warns that such ties depend on training order: in the given order joins, so uniform predicts 0 and distance weights give 1 at probability 0.652; reorder the rows and joins, so uniform predicts 1.
  • Scale is the model. With an informative feature on (label ) and a nuisance feature on , 5-NN scores 0.47 unscaled and 0.995 standardized (400 train and 200 test points, seed 0). Standardize inside a Pipeline so test data meets the same transform.
  • Distances concentrate fast: for 50 uniform points in the unit cube, the ratio of pairwise distances falls from 101.9 at to 0.13 at , so fixed neighborhoods stop being local.
  • Trees win at low dimension and lose at high dimension. Timing fit plus 200 queries at on uniform points: at ball tree takes 0.007 seconds against brute 0.02, while at brute takes 0.007 against KD 0.196 (one run on an i9-12900K, sklearn 1.9.1).
Common mistakes · 3
  • Tuning on train error always picks . Memorization looks perfect and generalizes worst, so tune by cross-validation.
  • Scaling before the split leaks test ranges into the train transform. Fit the scaler on train only and apply it to test.
  • algorithm auto is not a promise of trees. Sparse input, high dimension or above half of silently selects brute force, so confirm with timing rather than the parameter name.
3

Try it yourself

Closed-book, before checking anything

From a blank file, implement brute-force kNN with uniform and distance weights and match sklearn on X = [0, 1, 2, 5, 6] with y = [0, 0, 1, 1, 1] at query 2.5 and . Make your tie rule explicit (lower training index wins), then reorder the training rows and show sklearn's uniform answer flip from 0 to 1. Rerun the scaling pair and report 0.47 unscaled against 0.995 standardized.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.At query 2.5 with , which third neighbor joins and , and what does uniform voting predict?Answer

    and tie at distance 2.5. In the given order sklearn takes , so votes are 1, 0, 0 and uniform predicts 0; with the rows reordered it takes and predicts 1. A tie at the -th place makes the answer depend on data order, so state your rule.

  2. 2.Why does the unscaled toy score 0.47 while the standardized one scores 0.995?Answer

    The nuisance feature spans 1000x the informative one, so Euclidean neighborhoods are chosen by noise. Standardizing restores the informative axis.

  3. 3.The concentration ratio reads 101.9 at and 0.13 at . What breaks for kNN?Answer

    Relative distance contrasts vanish, so the nearest and farthest points sit almost equally far. Fixed- neighborhoods cover non-local regions and the vote carries little signal.

  4. 4.At and , which search algorithm wins and why?Answer

    Brute force at 0.007 seconds against 0.196 for KD-tree. Partitioning overhead and dimensionality defeat the trees while blocked matrix distance stays cheap.

5

Practice

  • HoML Chapter 3, Exercise 1: MNIST classifier above 97 percent

    Exercise solutions, Exercise 1: grid search KNeighborsClassifier over weights and n_neighbors on MNIST past 97 percent test accuracy

    Fit on the standard train split and score the held-out test set. Narrow the grid before running it at full size.

You're done when

Your kNN matches sklearn on the toy including the tie, your scaling rerun shows the collapse and the recovery, and the MNIST grid clears 97 percent.

Only when you can do this without notes.

Leads to

Notes

Resources · 2 for this unit, 6 more in the section

Also in this section

  • Hands-On Machine Learning with Scikit-Learn and PyTorch - nonlinear classical modelsAurelien Geron (O'Reilly, 2025) · primary

    Read Chapters 3, 5 and 6 and the online Appendix C notebook as the first pass through performance measures, trees, ensembles and SVMs, running notebooks 03, 05 and 06 alongside. Vary depth, estimators, learning rate, k, C and RBF width under fixed splits.

  • ISLP - tree-based methods and support vector machinesJames, Witten, Hastie, Tibshirani and Taylor · required

    Use Chapters 8 and 9 with their Python labs for the statistical account of trees, bagging, random forests, boosting and SVMs that the notebooks leave implicit, and for model-choice and feature-importance arguments.

  • Deep-ML - tree, ensemble and kernel problemsDeep-ML · support

    Use 138 Best Gini-Based Split, 20 Decision Tree Learning, 307 Bagging Classifier, 21 Pegasos Kernel SVM and 280 RBF Kernel as unit checks after the local implementation passes. Their tests were read in review; each card states what they pin, including tie and update-order conventions.

  • XGBoost parameters and sklearn estimator interfaceXGBoost developers · reference

    Read the tree-booster parameter list for eta, depth, sampling and regularization names and defaults, and the sklearn page for early stopping with eval_set.

  • LightGBM parametersLightGBM developers · reference

    Read learning_rate, num_leaves, max_depth, min_data_in_leaf, feature_fraction, bagging_fraction with bagging_freq, lambda_l2 and early stopping defaults.

  • CatBoost common parameters and categorical featuresCatBoost developers · reference

    Read iterations, learning_rate, l2_leaf_reg, depth, grow_policy, subsample, rsm, boosting_type, use_best_model and one_hot_max_size defaults, plus native categorical handling.