k-nearest neighbors (kNN): ask the k closest neighbors

When a new point with no answer comes in, find the k closest points among those whose answers you know, and ask them. Press one step at a time: measure, line up, keep k, vote.

Short answer. k-nearest neighbors (kNN) does not train. It keeps the training data as it is, and when a new point comes in, it finds the k closest points and takes a majority vote (classification) or an average (regression) of their answers. You choose k. A small k gives a jagged border, a large k a smooth one.

Green A and blue B are training points whose answers we know. The orange ring with "?" is the new point with no answer (you can drag it). Thin gray lines are distances, small numbers are the order from nearest, thick lines are the neighbors kept, the dashed orange circle reaches neighbor number k, and arrows are the votes the neighbors cast. The table shows the first k + 2 in the line. The 36 points (18 A, 18 B) are made up with a fixed-seed random generator, so they are the same every time you open the page.

Try this. (1) As it starts (new point at (0.4, 0.4), k = 5), press "Next" four times. The nearest point is an A at distance 0.32, the farthest is 4.53 away, neighbor number 5 is 0.81 away, and the vote is A 2, B 3 → B. (2) Press the weights button to switch to "1 ÷ distance". Now A 5.16, B 4.76 → A. The answer flips, because two of the three nearest (0.32 and 0.5) are A. (3) Switch back to uniform and set k to 1, 3, 5, 7. The answers are A, A, B, B. Same data, same new point, different answers for different k.

Definitions

The text below uses points with two features. These are the textbook definitions. The training data are pairs of a point with n features and its label. For training point i, yᵢ is its label and dᵢ is its distance to the query point q.

k-nearest neighbors (kNN)
Let Nₖ(q) be the set of indices of the k training points closest to the query point q. kNN decides the answer for q using only the labels of the points in Nₖ(q). Training only stores the data; the work happens when a query point arrives. Classification uses a majority vote, and regression uses the mean of the neighbors' answers.

y^=1k∑i∈Nk(𝐪)yi

Euclidean distance
The straight-line distance between two points x = (x₁, …, xₙ) and q = (q₁, …, qₙ): the square root of the sum of the squared differences in each coordinate.

d(𝐱,𝐪)=∑j=1n(xj−qj)2

majority vote
Each of the k neighbors casts one vote, and the class with the most votes is the answer (uniform weights). 1(·) is the indicator function: 1 if the condition inside is true, 0 if not.

y^=argmaxc∑i∈Nk(𝐪)1(yi=c)

distance weights
Neighbor i casts 1/dᵢ votes instead of one. Add up the score of each class and take the class with the highest score.

y^=argmaxc∑i∈Nk(𝐪),yi=c1di

decision boundary
The border in feature space where the class the classifier outputs changes, that is, the border between regions assigned to different classes. In kNN, the training data and k set the decision boundary.

1. What k-nearest neighbors is: remember instead of train

When every example comes with an answer (group A or B?) and the job is to guess the answer for new examples, that is supervised learning. Most models pull a rule (weights) out of the training data and then throw the data away. k-nearest neighbors does not. In the words of the scikit-learn docs, it "does not attempt to construct a general internal model, but simply stores instances of the training data". That is why it is called instance-based learning.

The work happens when a new point arrives. Measure the distance from the new point to the training points, keep the k closest, and use their answers to decide. If the answer is a group, that is classification (majority vote). If it is a number, that is regression (average).

k-means has a similar name but is a different thing. k-means groups points into k clusters with no answers, while here k is the number of neighbors. And how to find the close points quickly among very many is covered on the vector search page. This page is about deciding the answer from the neighbors you found.

2. The procedure and the formulas

keep        store every training point and its answer (no training math)
when a new point q comes in
  1 distance:  measure the distance from each training point to q
  2 line up:   sort them from nearest to farthest
  3 keep:      keep only the first k
  4 answer:    classification: vote with the k groups; regression: average the k answers

As formulas:

distance         d(x, q) = √((x₁ − q₁)² + (x₂ − q₂)² + …)
majority vote    ŷ = the group that appears most among the k neighbors
distance weights score of group c = (sum of 1 ÷ dᵢ over the neighbors in group c),  ŷ = the group with the highest score
regression       ŷ = (y₁ + y₂ + … + y_k) ÷ k

Uniform and distance weights. A majority vote gives every neighbor one vote (weights="uniform" in scikit-learn). Distance weights give each neighbor 1 ÷ distance votes, so closer neighbors count more (weights="distance"). As in Try this (2), the two can give different answers. With distance 0 you cannot compute 1 ÷ 0, so in this page's experiment only the points at distance 0 vote in that case.

In scikit-learn it is a few lines. fit just stores the data, and the work happens in predict.

from sklearn.neighbors import KNeighborsClassifier

model = KNeighborsClassifier(n_neighbors=5)        # add weights="distance" for distance weights
model.fit(X_train, y_train)                        # stores the training data
print(model.predict([[0.4, 0.4]]))                 # majority vote of the 5 nearest
print(model.score(X_test, y_test))                 # accuracy on the test data

3. Work it by hand: six points on a line

The training points sit on a number line: 1 (A), 2 (A), 4 (B), 5 (A), 7 (B), 8 (B). The new point is 4.4.

Training pointGroupDistance to 4.4Rank
1A3.45
2A2.43
4B0.41
5A0.62
7B2.64
8B3.66
  1. k = 1. The nearest is 4 (B, distance 0.4), so the answer is B. One neighbor decides alone.
  2. k = 3, uniform. The neighbors are 4 (B), 5 (A) and 2 (A). A has 2 votes and B has 1, so the answer is A. Raising k changed the answer.
  3. k = 3, distance weights. A gets 1 ÷ 0.6 + 1 ÷ 2.4 ≈ 1.67 + 0.42 = 2.08, B gets 1 ÷ 0.4 = 2.5. The answer is B, because 2 is far away (2.4) and its vote is light.
  4. For regression. If the three neighbors' answers are the numbers 10, 12 and 20, the answer is (10 + 12 + 20) ÷ 3 = 14.

4. k changes the border

Put a new point at every spot on the plane, paint the spots that get A green and those that get B blue, and a line appears where the two colors meet. That is the decision boundary. Move k with the slider below. The graph under it shows, for each k, the share of the 36 training points answered correctly (training accuracy) and the share of 100 test points, made up separately with the same rule, answered correctly (test accuracy). The test points are not drawn.

Training accuracy
Test accuracy

Try this. (1) With k = 1 the training accuracy is 100%, because each training point's nearest neighbor is itself (distance 0). But the test accuracy is 78%, and the border is jagged, wrapping around every stray point. (2) Raise k to 3, 5, 7 and the test accuracy climbs to 82%, 85%, 87% while the border smooths out. On this data k = 7 is the best (its training accuracy is 83%). (3) Raise k to 9 and 11 and the test accuracy drops to 84% and 82%. k = 15 gives 85%.

The scikit-learn docs say "the optimal choice of the value k is highly data-dependent: in general a larger k suppresses the effects of noise, but makes the classification boundaries less distinct." In the experiment, 100% training and 78% test at k = 1 is what memorizing the noise in the training data looks like. That is overfitting. Choosing k by training accuracy would always pick k = 1, so measure on data that was not used for training. Here we used the test data, but when you really choose k, hold out separate validation data and use the test data only once at the end (data splitting).

5. Before you measure distance: match the scales

Look at the distance formula d = √((difference across)² + (difference up)²). If one feature's numbers get 100 times bigger, the square of its difference gets 10,000 times bigger. So the feature with the bigger scale decides the distance almost alone. This follows straight from the distance formula, with nothing else needed. Here it is with three points.

Before: across in m 0123 123 P (A) R (B) q q→P 1.50 · q→R 1.02: R is nearer across × 100 After: across × 100 (cm) 100150200 P (A) R (B) q q→P 10.11 · q→R 100: P is nearer
The same three points q, P, R. On the right, only the across feature is written in cm instead of m, so its numbers are 100 times bigger, drawn at the same scale. The up differences (1.5 or less) almost vanish, and the nearest point changes from R (B) to P (A). With k = 1 the answer changes from B to A too. The thick orange line goes to the nearest point.

Before, q to R was the square root of 1.0² + 0.2² = 1.04. After, it is the square root of 100² + 0.2² = 10000.04. The up difference of 0.2 hardly counts at all. The unit is just a choice someone made, yet it changes the answer, so match the scale of each feature before measuring distance (normalization and standardization).

6. When to use what

OptionGoodBadUse it when
k-nearest neighbors itselfNo training math. It only stores the training dataIt builds no internal model, so it must find neighbors for every answer. It uses distance, so it is sensitive to feature scales (section 5)The data fits "close things have similar answers". After matching the scales
Small kFollows nearby points one by one, so the border is detailedOne noisy point can swing the answer. Training accuracy at k = 1 is always 100%, so you cannot trust itThe right k depends heavily on the data. Measure on data not used for training (section 4)
Large kSuppresses the effects of noiseThe classification border becomes less distinctSame as above
Uniform (uniform)One vote per neighbor, so it is simpleA far neighbor such as number k weighs the same as the nearest oneTry both and compare
Distance weights (distance)Listens more to closer neighborsOne very close neighbor can decide almost alone (because of 1 ÷ distance)Try both and compare

Ways to find the k nearest. scikit-learn offers brute force (brute), a KD tree (kd_tree) and a ball tree (ball_tree) as search methods. This page only names them. How to find close points quickly among very many is on the vector search page.

Where it is used

Common questions

Are k-nearest neighbors and k-means the same thing?

No. Only the names are alike. k-nearest neighbors takes points that already have answers, finds the k closest to a new point, and uses their answers to decide the new point's answer. There k is the number of neighbors. k-means groups points into k clusters with no answers at all, and k is the number of clusters.

How do I choose k?

There is no fixed value. The right k depends heavily on the data. Try several k and keep the one with the highest accuracy on data that was not used for training. In experiment 2 on this page it was k = 7. With two groups, use an odd k so the majority vote can never tie.

How is it different from vector search?

Vector search is about finding the close vectors quickly among very many. k-nearest neighbors is about deciding a new point's answer from the neighbors you found. Ways to speed up the first step of k-nearest neighbors, finding the k closest, are on the vector search page.

Words

Plain words used hereWhat books call it
deciding with the k closest neighborsk-nearest neighbors (kNN)
remembering the data instead of traininginstance-based learning, non-generalizing learning
points with known answers · the new pointtraining data · query point
groupclass, label
one vote per neighbor · 1 ÷ distance votesmajority vote, uniform weights · distance weights
the line where the two colors meetdecision boundary
straight-line distanceEuclidean distance
giving a number · giving a groupregression · classification
data not used for trainingvalidation set, test set
matching the scalesfeature scaling, normalization, standardization
measure all · KD tree · ball treebrute force · k-d tree · ball tree

Sources

← Decision trees, random forests and boostingk-means clustering →