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 03 of 08

03Scale first

Chapter 2 left a question: with all thirteen measurements, does every one count fairly? The answer is no. Imagine comparing people by height in meters and income in dollars: a difference of a few thousand dollars would swamp any difference in height, and “nearest” would just mean “similar income”. The wines have the same problem.

3.1The biggest numbers decide

Proline runs from about 300 to 1{,}700, while hue stays between 0.48 and 1.71 (Figure 2a). In (1), a typical proline difference is hundreds, so its square is tens of thousands; a hue difference squared is below one. How much each measurement contributes on average follows from one line of algebra.

Proposition 1 (A measurement’s share is its variance). Let x and x' be two inputs drawn independently from the same population, and let measurement j have variance \sigma_j^2. Then

\mathbb E\bigl[(x_j-x'_j)^2\bigr]=2\sigma_j^2,\qquad\text{so}\qquad \frac{\mathbb E\bigl[(x_j-x'_j)^2\bigr]}{\mathbb E\bigl[\operatorname{dist}(x,x')^2\bigr]}=\frac{\sigma_j^2}{\sum_{l=1}^d\sigma_l^2}. \tag{5}

Write \mu_j for the mean of measurement j. Expand the square and use linearity of expectation:

\mathbb E\bigl[(x_j-x'_j)^2\bigr]=\mathbb E[x_j^2]-2\,\mathbb E[x_jx'_j]+\mathbb E[{x'_j}^2]. \tag{6}

Both inputs come from the same population, so \mathbb E[x_j^2]=\mathbb E[{x'_j}^2]=\sigma_j^2+\mu_j^2 (the variance plus the squared mean). They are independent, so \mathbb E[x_jx'_j]=\mathbb E[x_j]\,\mathbb E[x'_j]=\mu_j^2. Hence \mathbb E[(x_j-x'_j)^2]=2(\sigma_j^2+\mu_j^2)-2\mu_j^2=2\sigma_j^2. The squared distance is the sum of these terms over j, so its expectation is 2\sum_l\sigma_l^2, and dividing gives the share.

So each measurement’s say in the distance is proportional to its variance, which depends on its units. Proline varies in the hundreds and hue in tenths, so on our training wines (5) gives proline 99.8\% of the expected squared distance. Counted pair by pair, proline takes 95\% of the squared distance on average (Figure 2b); the other twelve measurements share what is left.

(a) The range of each of the 13 measurements over the 178 wines, on a log scale; proline (orange) runs into the thousands, hue (purple) stays near 1. (b) Each measurement’s share of the squared distance between two training wines, averaged over all pairs: raw (orange), proline takes 95\%; standardized (teal), every measurement takes about 1/13. Data of Forina et al. (1988); computed for this tutorial, with the same data as the companion video.
Figure 2. (a) The range of each of the 13 measurements over the 178 wines, on a log scale; proline (orange) runs into the thousands, hue (purple) stays near 1. (b) Each measurement’s share of the squared distance between two training wines, averaged over all pairs: raw (orange), proline takes 95\%; standardized (teal), every measurement takes about 1/13. Data of Forina et al. (1988); computed for this tutorial, with the same data as the companion video.

Worked example 2 (A nearest neighbor chosen by proline). Take the training wine of Table 1, from cultivar two. With raw measurements, its nearest neighbor matches its proline almost exactly, 470 against 472, but it is from cultivar three, with a very different color intensity and flavanoids. Every other wine differs from it in proline by tens or hundreds, and those differences, squared, outweigh everything else. After standardizing (below), its nearest neighbor is a cultivar-two wine that resembles it in color and flavanoids, even though their proline differs much more.

cultivarprolinecolor intensityflavanoids
the winetwo4723.741.84
nearest, raw distancethree4709.900.51
nearest, standardized distancetwo3252.002.27
Table 1. One training wine and its nearest neighbor by raw and by standardized distance (Worked example 2). Data of Forina et al. (1988).
Try itRaw or standardized: who decides the distance?

Switch between raw and standardized measurements, and pick any of the 124 training wines. Left: every measurement's share of the squared distance, averaged over all pairs of training wines, as in Figure 2b. Right: the chosen wine (navy) and its nearest neighbor (in its cultivar's color), with every measurement shown in standard deviations so they fit one axis.

3.2The fix: standardize

Definition 2 (Standardization). Replace each measurement by its z-score,

z_j=\frac{x_j-\mu_j}{\sigma_j}, \tag{7}

where \mu_j and \sigma_j are the mean and standard deviation of measurement j over the training points; then use the Euclidean distance on the z-scores.

Subtracting \mu_j does not change any difference; dividing by \sigma_j gives every standardized measurement variance one. By Proposition 1, each now has expected squared difference 2 and the same share of the distance, 1/d; on the wines, proline’s share drops from 95\% to about 1/13 (Figure 2b). Every measurement now speaks in the same units: standard deviations. Hastie et al. (2009, §13.3) recommend exactly this before k-nearest neighbors, because the features are usually measured in different units.

Rescaling each measurement to the range zero to one, (x_j-\min_j)/(\max_j-\min_j), works too; it is simpler but depends on the two most extreme values, so a single outlier can squeeze all the others together. Either way, the scaling is a property of the training data: compute \mu_j and \sigma_j (or the minimum and maximum) on the training points only, inside each cross-validation fold, and apply the same numbers to the test points. Computing them on all the data first leaks test information into the model (Episode 11).

Standardizing has a classic interpretation. The Mahalanobis distance \sqrt{(x-x')^\top M(x-x')}, with M positive definite, generalizes the Euclidean one (Murphy, 2022, eq. 16.2). With M=\operatorname{diag}(1/\sigma_1^2,\dots,1/\sigma_d^2) it is exactly the Euclidean distance of the z-scores; with M the inverse covariance matrix it also removes the correlations between measurements.

How much does it matter? With five neighbors, the cross-validated accuracy on the training wines rises from 72\% with raw measurements to 95\% with standardized ones. So always scale before measuring distance. Note what standardizing does not do: it gives every measurement an equal say, including useless ones, and each irrelevant measurement adds noise to the distance. Choosing the measurements, or learning the matrix M (Murphy, 2022, §16.2), is the next step when equal weights are not good enough.

Pause and think. Suppose alcohol were recorded in parts per million instead of percent, so every value is 10{,}000 times larger. What happens to k-nearest neighbors on raw measurements, and on standardized ones?

Show the answer

On raw measurements alcohol’s variance grows by 10^8, so by (5) it now dominates the distance and the neighbors change completely. On standardized measurements nothing changes: \mu_j and \sigma_j grow by the same factor, so the z-scores (7) are identical. Standardized k-nearest neighbors does not depend on the units.

Scaling fixes the distance. But we picked five neighbors out of thin air. How should we choose k?