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.
| Point | Distance | Group | Vote |
|---|
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.
- 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.
- 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.
- 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.
- 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
q: the new point with no answer.q₁, q₂are its first and second feature values.x: one training point.x₁, x₂are its feature values.d,dᵢ: straight-line (Euclidean) distance.dᵢis the distance from neighbor i to q.k: how many neighbors to keep. You choose it.c: one group (one possible classification answer).ŷ: the answer given for the new point.yᵢ: for regression, the answer (a number) of neighbor i.
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 point | Group | Distance to 4.4 | Rank |
|---|---|---|---|
| 1 | A | 3.4 | 5 |
| 2 | A | 2.4 | 3 |
| 4 | B | 0.4 | 1 |
| 5 | A | 0.6 | 2 |
| 7 | B | 2.6 | 4 |
| 8 | B | 3.6 | 6 |
- k = 1. The nearest is 4 (B, distance 0.4), so the answer is B. One neighbor decides alone.
- 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.
- 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.
- 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, 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
| Option | Good | Bad | Use it when |
|---|---|---|---|
| k-nearest neighbors itself | No training math. It only stores the training data | It 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 k | Follows nearby points one by one, so the border is detailed | One noisy point can swing the answer. Training accuracy at k = 1 is always 100%, so you cannot trust it | The right k depends heavily on the data. Measure on data not used for training (section 4) |
| Large k | Suppresses the effects of noise | The classification border becomes less distinct | Same as above |
Uniform (uniform) | One vote per neighbor, so it is simple | A far neighbor such as number k weighs the same as the nearest one | Try both and compare |
Distance weights (distance) | Listens more to closer neighbors | One 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
- Classification. A majority vote of the k neighbors decides the group (experiment 1).
- Regression. Average the k neighbors' answers (numbers), like the 14 in section 3.
- On embeddings. The points do not have to be 2D. As long as you can measure distance, it works the same. You can find the k closest embedding vectors of documents or images and follow their answers, and finding those close vectors quickly is vector search.
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 here | What books call it |
|---|---|
| deciding with the k closest neighbors | k-nearest neighbors (kNN) |
| remembering the data instead of training | instance-based learning, non-generalizing learning |
| points with known answers · the new point | training data · query point |
| group | class, label |
| one vote per neighbor · 1 ÷ distance votes | majority vote, uniform weights · distance weights |
| the line where the two colors meet | decision boundary |
| straight-line distance | Euclidean distance |
| giving a number · giving a group | regression · classification |
| data not used for training | validation set, test set |
| matching the scales | feature scaling, normalization, standardization |
| measure all · KD tree · ball tree | brute force · k-d tree · ball tree |
Sources
- scikit-learn user guide: Nearest Neighbors (the principle of nearest neighbor methods, instance-based learning, majority vote, choosing k with noise and borders,
uniformanddistanceweights, the search methodsbrute,kd_tree,ball_tree, and regression by the mean of the neighbors' answers).
← Decision trees, random forests and boostingk-means clustering →