Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 3: Classical Machine LearningClassic Algorithms

k-Nearest Neighbors

P3.B140 min●●○ IntermediateReviewed Dec 2, 2026

Why this matters for machine learning

k-nearest neighbors is the simplest model that learns from examples: it stores them and answers a new question from the most similar ones. It makes the ideas of distance, flexibility and the cost of a prediction concrete, and the same nearest-neighbor search runs inside modern retrieval systems.

  • Retrieval for language models looks up the stored text vectors nearest to a query vector, which is nearest-neighbor search at a much larger scale. (P10.E5: Retrieval-Augmented Generation, coming soon)
  • The number k is the first flexibility knob you can see: a small k overfits, a large k underfits, and validation picks the value. The trade-off is analysed as bias and variance. (P3.A5: The bias–variance trade-off)
  • A feature measured in big units dominates every distance, so distance-based methods need scaled features. Scaling gets its own lesson. (P3.A11: Features, scaling and data leakage)
  • k-means clustering uses the same distance to the nearest point, with cluster centres in place of stored examples. (P3.C1: k-means clustering)

Before this: The supervised learning setup, Polynomial regression, underfitting and overfitting, Train, validation and test sets, Norms and distances

After this lesson you can

  • Predict a class by majority vote, or a number by averaging, among the k nearest stored points, and handle ties and distance weights
  • Explain why k = 1 has zero training error, why k equal to the number of points predicts the majority class, and choose k on held-out data
  • Show with numbers how an unscaled feature takes over a distance, and choose between Euclidean, Manhattan and cosine distance
  • State the cost of brute-force search (about n times d operations per query), name the faster options, and explain why distances lose meaning in high dimensions

You want to know whether a new house will sell for a high price. One reasonable move is to look up the five most similar houses that sold recently and see what they went for. You did not fit a formula. You used the examples directly.

That is the whole idea of k-nearest neighbors (k-NN). It was a classic method long before neural networks became popular, and it is still a good first baseline. It is also the cleanest way to see three ideas that every model in this course shares: the choice of a flexibility knob, the need for honest held-out data, and the fact that similar has to be defined by a measurement.

This lesson uses the supervised-learning setup of P3.A1: examples with features x\mathbf{x} and a label yy, the label being a class (classification) or a number (regression). All data here is made up, and the lesson says so wherever it matters.

The algorithm in one paragraph

  1. Store every training example (xi,yi)(\mathbf{x}_i, y_i). That is the whole “training”.
  2. For a new point x\mathbf{x} (the query), compute its distance to every stored point.
  3. Take the kk stored points with the smallest distances: the neighbors.
  4. Classification: the predicted class is the one with the most votes among the neighbors. Regression: the prediction is the average of the neighbors’ yy values.

The number kk is chosen by you before predicting. It is a hyperparameter, a setting that is not learned from the data by the fitting step (P3.A4).

A hand-worked example

Eight stored points with two features, in two classes, A and B. The query is x=(3,3)\mathbf{x}=(3,3).

PointClassSquared distance to (3,3)(3,3)
(3,4)(3,4)B0+1=10+1=1
(2,2)(2,2)A1+1=21+1=2
(1,3)(1,3)A4+0=44+0=4
(5,2)(5,2)B4+1=54+1=5
(1,1)(1,1)A4+4=84+4=8
(3,0)(3,0)A0+9=90+9=9
(6,4)(6,4)B9+1=109+1=10
(7,1)(7,1)B16+4=2016+4=20

The table is sorted nearest first. (Ranking by the squared distance gives the same order as ranking by the distance, so we skip the square root.) Now read off the vote for different kk:

  • k=1k=1: the nearest point is B, so the prediction is B.
  • k=3k=3: neighbors B, A, A. Two votes for A, one for B, so A.
  • k=5k=5: B, A, A, B, A gives A three votes to two, so A.
  • k=7k=7: A has four votes, B three, so A.
  • k=8k=8 (all points): four votes each, a tie. The nearest point is a B, so this lesson’s rule (explained below) gives B; a library with a different rule could say A.

The prediction changed from B to A as kk grew. The single nearest point is a B that happens to sit very close; a wider look says the area belongs to A. Which answer is right depends on whether that nearest B is a real signal or a lucky accident (noise). That question, “how far should I look?”, is the whole subject of the middle of this lesson.

Try it: the eight points, by code

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

See it: decision regions for every spot of the plane

Doing this for one query is easy. A decision region shows the answer for every possible query at once: the plane is shaded by what k-NN would predict at each spot. The widget below uses made-up points of up to three classes. Filled marks are training points; hollow marks are held-out test points that never vote.

Add class:
Distance:
k used: 1 of 40 points
training accuracy: 100%
held-out test accuracy: 74% (37 of 50)

k = 1: each spot copies its single nearest point, so every training point is right about itself (training accuracy 100%, unless two points sit on the same spot with different classes). The boundary is jagged.

Cursor (5.0, 5.0): the nearest point votes ● 1, so the prediction is ● (blue circles).

Shaded areas: what k-NN predicts there. Filled marks: training points (k-NN stores these). Hollow marks: held-out test points, never used for voting. Lines join the cursor to its neighbours. Marks are shaped as well as coloured. Tap the plane, or focus it and use the arrow keys (Shift for bigger steps).

Rules used: each point's distance to the spot is measured; the k nearest vote; if classes tie, the class of the nearest of the tied points wins; equal distances are ordered by the point's position in the list. With fewer than k points, all of them vote. Training accuracy counts each training point as its own nearest neighbour.

k-NN decision regions. Shaded areas show the predicted class at every spot. Pick a data set, move the k slider (odd values), switch the distance, and tap the plane to add points of the chosen class (or switch to cursor mode and tap to see one query's neighbors joined by dashed lines). By keyboard: focus the plane, move the cursor with the arrow keys, press Enter to add a point. The readouts show accuracy on the training points and on the hollow test points.

Things to try (the data sets are fixed, so these numbers repeat):

  1. Two blobs, k=1k=1. Training accuracy is 100% and test accuracy is 74% (37 of 50). The regions have small islands around single points. Raise kk to 15: training accuracy falls to 90% and test accuracy rises to 84%. The boundary is smooth and the model generalizes better. Test accuracy on 50 points moves a lot by chance (its standard error is about 0.06, P1.D13), so read this as a trend, not as a precise gain.
  2. Blobs with 10% wrong labels, k=1k=1. Every wrong label carves a small island of the wrong class around itself, and test accuracy is 78%. At k=5k=5 the islands vanish and test accuracy is 88%. Noisy labels are what a small kk memorizes.
  3. Press k = all points. The whole plane takes the class with the most training points: on Two blobs that is 58% training accuracy and 50% test accuracy.
  4. Two moons: k=3k=3 gives 94% training and 98% test accuracy, while k=1k=1 gives 100% and 94%.
  5. Empty. Add a few points of two classes by hand and place a lone point of one class deep inside the other. Then raise kk and watch the lone point’s island disappear.
  6. Switch between L2 and L1. The shapes of the boundaries change (L1 gives more boxy, axis-aligned corners), though on these data sets the accuracy differences are within chance.

The status line under the plane explains what the current kk does, and the rules the widget uses (ties, equal distances, training accuracy) are stated under it.

Votes, ties and weights

Odd kk for two classes. With two classes and an odd kk, the votes cannot tie. That is why the slider moves in odd steps. With three or more classes a tie is still possible even for odd kk (a 1-1-1 vote at k=3k=3), and with an even kk it happens in two classes too (the k=8k=8 line above).

Tie rules. There is no single standard. This lesson’s widget and cells use “the class of the nearest of the tied points wins”, which is a sensible rule because it uses the extra information in the distances. Libraries choose their own. In the checks made for this lesson, scikit-learn 1.8 returned the class with the lowest label in each tie it was given, whichever neighbor was closest. Do not rely on a tie rule; avoid ties by choice of kk, or break them with weights.

Distance-weighted voting. Counting every neighbor equally means a neighbor at distance 5 counts as much as one at distance 0.1. A common alternative gives neighbor ii the weight wi=1/diw_i=1/d_i (closer counts more), and each class gets the sum of its neighbors’ weights. This also removes most ties. Weighted voting does not remove the need for a good kk, but it makes the result less sensitive to it, because far neighbors count little.

If a query lands exactly on a stored point, di=0d_i=0 and 1/di1/d_i cannot be computed; implementations handle that case separately (scikit-learn gives the exact-match point all the weight).

k-NN for regression

The recipe is the same with an average instead of a vote. Take stored points at x=1,2,3,4,5,6x=1,2,3,4,5,6 with targets yy equal to 1.01.0, 2.52.5, 2.02.0, 4.04.0, 3.53.5 and 6.06.0, and predict at x=3.4x=3.4. The three nearest points are x=3x=3 (distance 0.4, y=2.0y=2.0), x=4x=4 (0.6, y=4.0y=4.0) and x=2x=2 (1.4, y=2.5y=2.5).

  • k=1k=1: the prediction is 2.02.0.
  • k=3k=3, plain average of 2.02.0, 4.04.0 and 2.52.5: 2.8332.833.
  • k=3k=3, weighted by 1/d1/d: the weights are 2.52.5, 1.6671.667 and 0.7140.714. The weighted sum is 5.0+6.667+1.786=13.4525.0+6.667+1.786=13.452 and the weights add to 4.8814.881, so the prediction is 13.452/4.881=2.75613.452/4.881=2.756.

The prediction is a step-like curve: constant until the set of neighbors changes. Two properties are worth remembering. First, k-NN regression cannot extrapolate: outside the range of the stored xx values it just returns the average of the nearest few targets, so it never leaves the range of the training yy values. P3.A3’s degree-9 polynomial predicted about 5,700 at x=1.2x=1.2; k-NN would predict a plain number near the edge targets. Second, k=nk=n predicts the overall mean of yy everywhere, the regression counterpart of “predict the majority class”.

Which distance, and why scaling decides everything

k-NN is only as good as its idea of “near”. The usual choices (P1.B4):

  • Euclidean (L2): ∑j(xj−xj′)2\sqrt{\sum_j (x_j-x'_j)^2}. The default. One big difference in one feature counts a lot because it is squared.
  • Manhattan (L1): ∑j∣xj−xj′∣\sum_j |x_j-x'_j|. Differences add up without squaring, so one large difference is less dominant.
  • Cosine: compares the direction of two vectors, ignoring their length (P1.B3). It suits text or embedding vectors, where how long the vector is matters less than where it points. For vectors scaled to length 1, ranking by cosine similarity and ranking by Euclidean distance agree (P1.B3), so you can use whichever is faster.

The algorithm runs the same with any of them, but the answer can change, as P1.B4 showed with one query and five points whose nearest member differs under L1, L2 and L∞.

The scaling trap. Distances add up differences in every feature, so a feature measured in big numbers takes over. P1.B4’s three people: Alice is (25, 50 000)(25,\,50\,000) (age, income), Bob (60, 50 500)(60,\,50\,500), Carol (26, 60 000)(26,\,60\,000). Alice’s distance to Bob is 501.2 and to Carol is 10 000.0, so Bob is “nearer”, though he is 35 years older. After rescaling both features to similar ranges (using the ranges assumed in P1.B4) the distances become 0.700 and 0.102, and Carol is the neighbor. With k=1k=1 the prediction for Alice would flip from Bob’s label to Carol’s.

The same effect on a whole data set, in the next cell. The made-up data has a class that depends on age only; income is noise on a scale thousands of times larger. Before scaling, k-NN’s test accuracy is 49.8%, no better than always guessing the larger class (50.8%). After standardizing each feature, z=(x−mean)/stdz=(x-\text{mean})/\text{std}, with the mean and standard deviation taken from the training rows only, it reaches 86.6%. (The best possible here is about 90%, because 10% of the labels were flipped.)

Try it: scaling, and the pairwise-distance trick

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Two details. The cell computes all the distances at once with the expansion

∥a−b∥2=∥a∥2+∥b∥2−2 a⋅b\lVert\mathbf{a}-\mathbf{b}\rVert^2=\lVert\mathbf{a}\rVert^2+\lVert\mathbf{b}\rVert^2-2\,\mathbf{a}\cdot\mathbf{b}

(P2.3), including the np.maximum(…, 0) that guards against tiny negative values from rounding. And the scaling numbers come from the training rows only: computing them on all the data would let the test rows influence the model (the leak of P3.A4; P3.A11 gives the full list of such traps).

Other points about features:

  • Categorical features (colour, country) do not have a natural distance. Turning them into 0/1 columns works only with care, because a 0/1 column then has a very different scale from a standardized one. P3.A11 covers encodings.
  • Missing values must be filled before computing distances (P2.5).
  • Which features count matters as much as their scale: see the curse of dimensionality below.

k is the flexibility knob

P3.A3 called the flexibility of a model its capacity, and said that for k-NN a small kk means high capacity. Now you can see why.

  • k=1k=1 copies the nearest point. Each training point is its own nearest neighbor (distance 0), so the training error is zero, unless two stored points have the same features but different labels. The boundary follows every point, noise included, and is jagged. This is overfitting in the sense of P3.A3: zero training error, worse test error.
  • Large kk averages over many points. The boundary becomes smooth, the model reacts less to single points, and eventually it is too stiff to follow the real pattern (underfitting).
  • k=nk=n: every stored point votes for every query. The prediction is the majority class of the whole training set, everywhere (with the tie rule used here deciding exactly balanced cases). That is the most rigid model there is.

So kk runs from “memorize” to “ignore the features”. The U-shaped test curve of P3.A3 appears again here, with kk in place of the degree but reversed (small kk on the high-capacity side). P3.A5 explains the U-shape as bias and variance.

Go deeper Two classical facts about nearest neighbors

A small kk is more flexible than its size suggests. For k-NN regression the degrees of freedom (a measure of effective flexibility) work out as about n/kn/k, because each training point carries weight 1/k1/k in its own prediction. At k=1k=1 that is nn, as many as there are points, like the interpolating polynomial of P3.A3. Larger kk gives fewer effective parameters.

What happens with unlimited data. Cover and Hart (1967) showed that for two classes, under mild conditions on the data, the error of the 1-nearest-neighbor rule approaches a limit of at most 2R∗(1−R∗)2R^*(1-R^*) as the number of stored points grows without bound, where R∗R^* is the smallest error any rule can reach (the Bayes error). They summarized this as saying that half of the classification information in an infinite sample is contained in the nearest neighbor. Later work showed that if kk also grows, but more slowly than nn, k-NN approaches the best possible error. These are statements about unlimited data; with finite data and many features, what matters is the next sections.

Choosing k

Never choose kk by training accuracy: k=1k=1 always wins that contest at 100%. Choose it on held-out data (P3.A4): validation accuracy, or cross-validation when data is scarce.

The cell below uses made-up data (two interleaved half-circles plus noise, 401 points, seeded), split 201 for training, 100 for validation and 100 for test. It prints the accuracy for several kk, chooses kk on validation, evaluates once on the test set, and repeats the choice with 5-fold cross-validation on the 301 non-test rows.

Try it: choosing k with validation and cross-validation

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

What the numbers show (this is the output of the cell):

  • k=1k=1: training accuracy 1.000, validation 0.740. The memorizing model is clearly worse on new data.
  • k=3k=3 to k=101k=101: for every value printed, validation accuracy is between 0.83 and 0.87, a long plateau. Training accuracy falls slowly from 0.87 to 0.80 across it.
  • k=201k=201 (all training points): both fall to about chance, 0.512 on training and 0.450 on validation, because the model now predicts the larger class everywhere.
  • Validation picks k=9k=9 (0.870), and the test accuracy at k=9k=9 is 0.85. Cross-validation picks k=25k=25 (0.837) with its own noisy estimate. Those are two different answers from two noisy measurements of a flat curve.

The honest lesson is that on a plateau many kk values are equally good, and the exact winner depends on the split. Pick a value in the middle of the plateau rather than a lucky spike, and prefer the simpler (larger-kk, smoother) choice when scores tie within their noise (the standard error of a 100-point validation accuracy is about 0.035). Then refit on all the non-test data and report the test accuracy once. A common rule of thumb is to try odd values from 1 up to about n\sqrt{n}; treat it as a starting range, not a theorem.

Lazy learning, and what a prediction costs

Most models do their work in training and then predict cheaply: a fitted line is just two numbers. k-NN is the opposite. Its “training” is storing the data, so it is called a lazy learner, and the work happens at prediction time.

For nn stored points with dd features, one query by brute force costs about n⋅dn\cdot d subtract-and-square steps, plus finding the kk smallest (P1.G4). Memory holds the whole training set. A million points with 100 features is about 10810^8 steps for one prediction. The next cell times one query for three sizes of nn (the times depend on your machine and change from run to run, but they grow roughly in proportion to nn).

Try it: the cost of one brute-force query

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Ways to go faster:

  • Vectorize (P2.2, P2.3): compute all distances in one array expression, as in the cells above. This does not change the n⋅dn\cdot d work, only how fast each step runs.
  • KD-trees and ball trees organize the stored points so that whole groups can be skipped. They return the exact neighbors. They work well when the dimension is small and stop helping as it grows (see the next section; the block below shows it).
  • Approximate nearest-neighbor search (for example graph-based indexes such as HNSW) returns neighbors that are almost always the true ones, in much less time. This is what large vector databases use.

That last point is the bridge to modern AI. A retrieval system for a language model turns every text chunk into an embedding vector, stores millions of them, and answers a query by finding the stored vectors nearest to the query’s vector, usually by cosine similarity. That is k-NN with kk equal to a handful, with the query timing problem solved by approximate search (P10.E4 builds the search, P10.E5 the full retrieval system).

The curse of dimensionality

Distances lose their meaning. The numbers from P1.B4’s high-dimensional box, reproduced here: draw 1000 random points and a random query in the unit cube of dd dimensions, and compare the farthest and the nearest distance by (farthest−nearest)/nearest(\text{farthest}-\text{nearest})/\text{nearest}. The ratio is 113.1 for d=2d=2, 3.28 for d=10d=10, 0.49 for d=100d=100 and 0.12 for d=1000d=1000 (P1.B4 also ran d=10000d=10000: 0.04). When the ratio is near zero, the “nearest” neighbor is hardly nearer than the farthest one, so which points count as “the nearest kk” is easily changed by small noise, and the vote becomes unreliable. This is a statement about random data. Real data usually has structure (a few directions that matter), so k-NN can work in high dimensions, but the effect is a reason to be careful.

Neighborhoods are not local. If the data fills the unit cube evenly, to capture 10% of the data you need a sub-cube with edge 0.11/d0.1^{1/d}: 0.316 for d=2d=2, 0.794 for d=10d=10 and 0.977 for d=100d=100, which is 98% of the range. In 100 dimensions a “local” neighborhood that holds a tenth of the data spans that much along every axis. Local averaging only works if the neighbors are local.

Useless features swamp useful ones. The cell’s last part builds two informative features and adds mm columns of pure noise. With k=5k=5, 200 training points and 1000 test points (mean of 20 runs), test accuracy falls from 0.911 with no extra columns to 0.891 with 8, 0.844 with 32, 0.748 with 128 and 0.638 with 512. A few noise columns cost little (8 of them: 0.911 to 0.891), but many noise columns add so much random distance that the two useful columns cannot overcome it.

Try it: distances bunch together, and noise features hurt

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

What helps: fewer, better features (feature selection, P3.A11); reducing the dimension first (PCA, P3.C3); more data; and a distance learned from data, as in embeddings from neural networks, where the vectors are trained so that nearness means similarity (P10.E4). Scaling alone does not cure noise columns.

Go deeper Other distances: Hamming and Mahalanobis

For binary or categorical vectors, the Hamming distance counts the positions that differ. The Mahalanobis distance uses the covariance of the data (P1.D7) so that correlated or unequal-spread features are accounted for; with an identity covariance it is the Euclidean distance. Both are available as options in scikit-learn’s neighbors classes. Standardizing features is the simplest special case of choosing the metric by the data.

k-NN in scikit-learn

scikit-learn is not available in the browser, so this block is shown, not run. It was run locally (scikit-learn 1.8.0) on the same age and income data as the cell above. The scaler sits inside a Pipeline, so cross-validation fits it on each training part only (P3.A4).

import numpy as np
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import GridSearchCV

# X_train, y_train, X_test, y_test: the age/income data of the cell above
plain = KNeighborsClassifier(n_neighbors=5).fit(X_train, y_train)
print("no scaling :", plain.score(X_test, y_test))

pipe = make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=5))
pipe.fit(X_train, y_train)
print("scaled     :", pipe.score(X_test, y_test))

grid = {"kneighborsclassifier__n_neighbors": [1, 3, 5, 9, 15, 25]}
search = GridSearchCV(pipe, grid, cv=5).fit(X_train, y_train)
print("best k     :", search.best_params_["kneighborsclassifier__n_neighbors"],
      " CV accuracy", round(search.best_score_, 3))
print("test, once :", search.score(X_test, y_test))
print(np.round(search.cv_results_["mean_test_score"], 3))
no scaling : 0.498
scaled     : 0.866
best k     : 25  CV accuracy 0.935
test, once : 0.846
[0.87  0.905 0.925 0.92  0.925 0.935]

The first two lines match the NumPy cell (0.498 and 0.866). On these data the cross-validation curve rises from 0.87 at k=1k=1 to a plateau around 0.92 to 0.94. The cross-validation score of the winner (0.935) is above the best accuracy possible on these data (about 0.90, because 10% of the labels are flipped), a reminder that the best of six noisy scores is optimistic (P3.A4). The test accuracy, 0.846, is the honest number.

The tree versus brute-force comparison, from the same machine (50,000 stored points, 500 queries, uniformly random features; absolute times depend on the machine, and only the pattern matters):

for algorithm in ["brute", "kd_tree"]:
    model = KNeighborsClassifier(n_neighbors=5, algorithm=algorithm).fit(X, y)
    model.predict(queries)
d =  2: brute 0.200 s, kd_tree 0.002 s
d = 10: brute 0.019 s, kd_tree 0.112 s
d = 50: brute 0.029 s, kd_tree 3.539 s

In two dimensions the tree is roughly a hundred times faster. By ten dimensions it is slower than brute force, and by fifty it is far slower. By default, scikit-learn’s algorithm="auto" chooses between these for you.

Regression: one more cell

Try it: k-NN regression by hand and on noisy data

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

The first part reproduces the numbers above (2.000, 2.833 and 2.756). The second part draws 40 training points from a noisy sine (made up, noise sd 0.3), where the best possible mean squared error is 0.32=0.090.3^2=0.09. Training error is 00 at k=1k=1 and rises with kk. Test error is 0.178 at k=1k=1, lowest at k=5k=5 (0.111), then rises, and at k=40k=40 (all points) both errors are 0.598, close to the variance of yy (about 0.59 for this curve). The last two lines show that outside the data the prediction is flat, the mean of the five rightmost targets.

Strengths, weaknesses, and when to use it

Strengths: nothing to train, which makes it easy to try; it adapts to any boundary shape if there is enough data; new examples can be added by appending them. Weaknesses: slow, memory-hungry prediction; sensitive to the scale and choice of features; weak in high dimensions or with many irrelevant features; it needs a distance that fits the data; and with imbalanced classes the majority class tends to win the vote (P3.A10). It is a strong baseline for small, low-dimensional, well-scaled data, and the standard method behind similarity search at any scale.

Depth: three ways to see it

Intuition

Asking the neighbors: to guess how a new restaurant will be rated, you look at the restaurants in the same area with the same price and type. One close neighbor could be a fluke, so you check several. If you ask everyone in the whole city, the answer is just the city average. The analogy breaks when “area” is judged in many dimensions at once: with a hundred measurements per restaurant, everyone is far from everyone, and the closest restaurant in the list may be no more similar than a random one.

Math

Let Nk(x)N_k(\mathbf{x}) be the indices of the kk training points nearest to x\mathbf{x} under a distance dd. Classification: y^(x)=arg⁡max⁡c∑i∈Nk(x)1[yi=c]\hat{y}(\mathbf{x})=\arg\max_c \sum_{i\in N_k(\mathbf{x})}\mathbf{1}[y_i=c]. Regression: y^(x)=1k∑i∈Nk(x)yi\hat{y}(\mathbf{x})=\frac1k\sum_{i\in N_k(\mathbf{x})}y_i. With weights wi=1/d(x,xi)w_i=1/d(\mathbf{x},\mathbf{x}_i): y^=∑i∈Nkwiyi/∑i∈Nkwi\hat{y}=\sum_{i\in N_k} w_iy_i\big/\sum_{i\in N_k}w_i and, for classes, arg⁡max⁡c∑i∈Nkwi1[yi=c]\arg\max_c\sum_{i\in N_k}w_i\mathbf{1}[y_i=c].

Cost: nn distances of dd features each, O(nd)O(nd) per query, plus selecting kk smallest (O(n)O(n) with a partial selection). Standardizing: zj=(xj−μj)/sjz_j=(x_j-\mu_j)/s_j with μj,sj\mu_j,s_j from the training rows. Cross-validation estimate: the mean of the KK fold accuracies (P3.A4).

Code

import numpy as np

def knn_predict(X_train, y_train, X_new, k):
    # squared distances, shape (n_new, n_train); broadcasting as in P2.3
    d2 = ((X_new[:, None, :] - X_train[None, :, :]) ** 2).sum(axis=2)
    nearest = np.argsort(d2, axis=1, kind="stable")[:, :k]   # indices, nearest first
    votes = y_train[nearest].sum(axis=1)                       # classes 0/1: count of 1s
    return (2 * votes > k).astype(int)                         # strict majority (odd k)

The scikit-learn version is the KNeighborsClassifier class: its fit stores the data and its predict finds the neighbors. Put a StandardScaler before it in a pipeline.

Common mistakes

Quiz

Check your understanding

  1. A 1-nearest-neighbor classifier is scored on its own training data. Apart from two stored points with identical features but different labels, what accuracy does it get, and why?

  2. Each person has an age in years and an income in dollars. You run k-NN on the raw numbers. What happens, and what fixes it?

  3. You must choose k for a classifier. Which procedure is sound?

  4. A brute-force k-NN classifier stores 1,000,000 examples with 100 features each. About how much work does one prediction take?

  5. Two useful features are joined by 500 columns of random noise, and k-NN accuracy falls from 0.91 to about 0.64. What is the best explanation?

Exercises

  1. Use the eight points of the worked example and the query (2,4)(2,4). Find the votes at k=1,3,5,7k=1,3,5,7 (use squared distances).
    Show answerSorted by squared distance: (3,4)(3,4) B 1, (1,3)(1,3) A 2, (2,2)(2,2) A 4, (1,1)(1,1) A 10, (5,2)(5,2) B 13, (6,4)(6,4) B 16, (3,0)(3,0) A 17, (7,1)(7,1) B 34. So k=1k=1: B; k=3k=3: A 2, B 1, so A; k=5k=5: A 3, B 2, so A; k=7k=7: A 4, B 3, so A.
  2. With three classes and k=3k=3, the neighbors (nearest first) have classes 2, 0, 1. What does this lesson’s tie rule predict? Why might another library give a different answer?
    Show answerClass 2, the class of the nearest of the tied points. Another library may break ties differently: scikit-learn 1.8 returned the lowest label (0) in this case.
  3. A query person is (30, 40 000)(30,\ 40\,000) (age, income). B is (32, 60 000)(32,\ 60\,000) and C is (50, 45 000)(50,\ 45\,000). Which is nearer by raw Euclidean distance? Then divide the differences by the ranges 50 years and 100 000 dollars and decide again.
    Show answerRaw: B is at ≈20 000\approx 20\,000 and C at ≈5 000\approx 5\,000, so C is nearer. Scaled: B is 0.042+0.22=0.204\sqrt{0.04^2+0.2^2}=0.204 and C is 0.42+0.052=0.403\sqrt{0.4^2+0.05^2}=0.403, so B is nearer. The income gap decided the raw answer; after scaling the 20-year age gap counts for more.
  4. A search service stores 2,000,000 vectors with 128 features. How many subtract-and-square steps does a brute-force query take? Name one way to speed it up while keeping exact answers, and one that gives up exactness.
    Show answerAbout 2×106×128=2.56×1082\times10^6\times128=2.56\times10^8. Exact: vectorize or batch the brute force (a tree rarely helps at 128 dimensions; see the timings above). Not exact: approximate search such as HNSW, which accepts occasionally missing a true neighbor.
  5. What edge length must a sub-cube have to hold 1% of the volume of the unit cube in d=10d=10? Is that “local”?
    Show answer0.011/10=0.6310.01^{1/10}=0.631. It covers 63% of the range along every axis, which is not local.
  6. For the six points of the regression example, predict at x=5.2x=5.2 with k=2k=2, with a plain average and with weights 1/d1/d.
    Show answerThe two nearest are x=5x=5 (d=0.2d=0.2, y=3.5y=3.5) and x=6x=6 (d=0.8d=0.8, y=6.0y=6.0). Plain: (3.5+6.0)/2=4.75(3.5+6.0)/2=4.75. Weighted: weights 5 and 1.25, so (5⋅3.5+1.25⋅6.0)/6.25=4.0(5\cdot3.5+1.25\cdot6.0)/6.25=4.0.

Next: P3.B2 turns to a method that classifies by probabilities, naive Bayes. P3.B3 and P3.B4 build decision trees and forests, which handle irrelevant features better than k-NN does. P3.A5 explains the trade-off in kk as bias and variance, P3.A11 returns to scaling and encodings, and P3.C1 uses nearest-point distances without labels.

Key takeaways

  • k-NN stores the training set. To predict, it finds the k stored points nearest to the query, then takes a majority vote (classification) or an average (regression).
  • k is the flexibility knob. k = 1 copies the single nearest point, has zero training error and a jagged boundary. A very large k smooths everything, and k equal to the number of points predicts the majority class everywhere. Choose k on validation data, never on training accuracy.
  • The distance is part of the model. A feature with large numbers dominates the distance unless the features are put on comparable scales, with the scaling constants taken from the training rows only.
  • There is no training step, but every prediction compares the query with all n stored points: about n times d operations by brute force. Trees and approximate search speed this up, and trees lose their edge as the dimension grows.
  • In many dimensions the nearest and farthest points are almost equally far away, and useless features swamp the useful ones. k-NN works best with few, informative, scaled features.
Found a mistake? Tell us