MoonSay /Tutorials/Machine Learning Interview #17
Contents
  1. 01Introduction
  2. 02The rule
  3. 03Scale first
  4. 04Choosing k
  5. 05Interview follow-ups
  6. 06Common misconceptions
  7. 07Interview questions and model answers
  8. 08Summary
  9. References
k-Nearest Neighbors/Chapter 04 of 08

04Choosing k

Chapter 3 fixed the distance; this chapter answers how to choose k. To see what k does, go back to two measurements, now standardized, and color every spot of the plane by the cultivar that k-nearest neighbors would predict there (Figure 3).

The prediction of k-nearest neighbors at every spot of the plane (standardized alcohol and flavanoids), with the training wines on top; red, blue and gold are cultivars one, two and three. (a) k=1: every training wine is classified correctly, but the boundary is jagged, with islands around single wines. (b) k=15: smooth. (c) k=61: half the training wines vote every time, and the smallest cultivar, three, loses ground near its edges. Computed for this tutorial, with the same data as the companion video.
Figure 3. The prediction of k-nearest neighbors at every spot of the plane (standardized alcohol and flavanoids), with the training wines on top; red, blue and gold are cultivars one, two and three. (a) k=1: every training wine is classified correctly, but the boundary is jagged, with islands around single wines. (b) k=15: smooth. (c) k=61: half the training wines vote every time, and the smallest cultivar, three, loses ground near its edges. Computed for this tutorial, with the same data as the companion video.
Try itChoose k: from jagged to too smooth

Move k through every odd value from 1 to 61. Left: the prediction at every spot of the plane, on the two standardized measurements of Figure 3, with the training accuracy of that map. Right: the training and cross-validated accuracy with all 13 standardized measurements, as in Figure 4, with the current k marked.

4.1One neighbor memorizes, many neighbors blur

Pause and think. With k=1, what is the training accuracy?

Show the answer

A perfect 100\%: every training wine is its own nearest neighbor, at distance zero, so it votes for its own label. The plane is cut into one cell per training point, the points closer to it than to any other (a Voronoi tessellation), and each cell takes that point’s label (Murphy, 2022, §16.1.1). Zero training error says nothing about new wines.

With k=1 the boundary follows every single wine, including the unusual ones: a lone wine inside another cultivar’s region gets an island of its own (Figure 3a). That is overfitting, as in Episode 2: the model learns the noise in the training set. With k=15 the boundary is smooth. With k=61, half of the 124 training wines vote on every prediction, so near the edge of the smallest cultivar its own wines are outnumbered, and the boundary moves into its territory: underfitting. In the extreme k=n, every point gets the same vote, the majority class of the whole training set.

Small k means high variance: the prediction depends on one or two particular training points, and a different training set would give a different boundary. Large k means high bias: the prediction averages over neighbors that are far away and no longer like x. For regression this tradeoff can be written down exactly.

Proposition 2 (Bias and variance of k-nearest neighbors, Hastie et al., 2009, eq. 7.10). Let y=f(x)+\varepsilon, where the noise \varepsilon has mean 0 and variance \sigma^2 and is independent across points, and treat the training inputs as fixed. Let x_{(1)},\dots,x_{(k)} be the k training inputs nearest to x_0 and \hat f(x_0)=\frac1k\sum_{l=1}^ky_{(l)} the prediction (3). For a new response y_0=f(x_0)+\varepsilon_0,

\mathbb E\bigl[(y_0-\hat f(x_0))^2\bigr]=\underbrace{\sigma^2}_{\text{noise}}+\underbrace{\Bigl[f(x_0)-\frac1k\sum_{l=1}^kf(x_{(l)})\Bigr]^2}_{\text{bias}^2}+\underbrace{\frac{\sigma^2}{k}}_{\text{variance}} . \tag{8}
Try itStep through the derivation: the error of k-nearest neighbors

Press Next step to derive Proposition 2 one line at a time. Blue marks what changes in each step.

First the mean of the prediction. Each neighbor’s response is y_{(l)}=f(x_{(l)})+\varepsilon_{(l)} and the noise has mean zero, so

\mathbb E\hat f(x_0)=\frac1k\sum_{l=1}^kf(x_{(l)}),\qquad \hat f(x_0)-\mathbb E\hat f(x_0)=\frac1k\sum_{l=1}^k\varepsilon_{(l)} . \tag{9}

Now split the error into three pieces:

y_0-\hat f(x_0)=\underbrace{\varepsilon_0}_{A}+\underbrace{f(x_0)-\mathbb E\hat f(x_0)}_{B}+\underbrace{\mathbb E\hat f(x_0)-\hat f(x_0)}_{-\frac1k\sum_l\varepsilon_{(l)}}. \tag{10}

Square and take the expectation. B is a fixed number. A and the third piece have mean zero and are independent of each other (the new point’s noise is independent of the training noise), so all cross terms vanish, and

\mathbb E\bigl[(y_0-\hat f(x_0))^2\bigr]=\mathbb E[\varepsilon_0^2]+B^2+\frac1{k^2}\sum_{l=1}^k\mathbb E[\varepsilon_{(l)}^2]=\sigma^2+B^2+\frac{k\sigma^2}{k^2}, \tag{11}

where the variance of the average used that the k noise terms are independent, so the variance of their sum is the sum of their variances. This is (8).

The formula shows both sides of k. The variance \sigma^2/k falls as k grows: averaging k noisy responses cancels noise. The bias is the gap between f(x_0) and the average of f over the neighbors; it is small when the neighbors are close to x_0, and grows with k because the k-th neighbor is farther away. The noise \sigma^2 is the same for every k and cannot be removed. A related measure of complexity is the effective number of parameters, n/k (Hastie et al., 2009, §2.3.2): if the neighborhoods did not overlap there would be n/k of them, each with one fitted average. With our 124 training wines, k=1 is as flexible as a model with 124 parameters, and k=61 as one with 2.

4.2Choose k by cross-validation

We cannot choose k by training accuracy, which always favors k=1, and we must not look at the test set. So we use cross-validation (Episode 11), on the training wines only:

  1. keep the 54 test wines aside, untouched;
  2. for each candidate, every odd k from 1 to 61: split the 124 training wines into five folds; for each fold, standardize with the means and standard deviations of the other four, predict the held-out fold, and score it; repeat with ten different splits and average the 50 scores;
  3. pick the k with the highest average;
  4. standardize with all 124 training wines and keep them as the model with that k;
  5. predict the test wines once, and report that accuracy.

That is 31 candidates times 50 fits, plus the final one: 1{,}551 fits. For k-nearest neighbors each “fit” is just storing the training fold, so the cost is all in the predictions.

Training accuracy and cross-validated accuracy (five folds, repeated ten times) against k, with all 13 standardized measurements. Training accuracy is 100\% at k=1; cross-validated accuracy peaks at k=23 and falls for large k. Computed for this tutorial, with the same data as the companion video.
Figure 4. Training accuracy and cross-validated accuracy (five folds, repeated ten times) against k, with all 13 standardized measurements. Training accuracy is 100\% at k=1; cross-validated accuracy peaks at k=23 and falls for large k. Computed for this tutorial, with the same data as the companion video.

Worked example 3 (Choosing k for the wines). Figure 4 shows the result. The cross-validated accuracy is 92\% at k=1, although its training accuracy is 100\%; it peaks at 96\% at k=23, and falls to 83\% at k=61. We keep k=23, and test once: 53 of the 54 test wines are classified correctly.

The curve is flat near its top: every k from about 5 to 50 is within a few points of the best. That is typical, and it is why the exact value matters less than avoiding the two ends. The best k also grows with the data. If k grows with n but more slowly, so that k\to\infty and k/n\to0, the error of k-nearest neighbors approaches the lowest possible error for any distribution (Fix and Hodges, 1989; Stone, 1977): more data allow more neighbors, which cancel noise, while the neighbors still stay close.

So the method is simple and its choices are clear. What do interviewers ask next? Three follow-ups come up again and again.