Skip to content

AI Glossary · Concepts

What is k-Nearest neighbors?

k-Nearest neighbors

k-nearest neighbors (k-NN) predicts the label or value for a new example by finding the k most similar examples it has already seen and taking a vote or an average of their answers.

Also known as: k-NN, kNN, k-nearest neighbor

· Updated · Chain of Thought

Model Training

  • 2 explainers
  • 3 sources

An appraiser pricing a house looks at comparable sales: the five most similar recently sold homes nearby, by size, bedrooms and location. Averaging their prices gives an estimate. That is k-nearest neighbors with k = 5. For a yes-or-no question, such as whether a transaction is fraud, the five nearest past cases vote instead.

There is almost no training step. The method stores the labeled examples and does its work when a question arrives, so adding new examples changes its answers immediately. The results depend on what “similar” means. If one column is price in dollars and another is number of bedrooms, the dollar column swamps the distance unless both are scaled. With many columns, everything starts to look roughly equally far away, which makes the neighbors less meaningful.

The find-the-closest step is the same one behind semantic search and vector databases, which look up the nearest embeddings to a query, usually approximately for speed. k-NN adds the vote or average over those neighbors’ known answers. Some recommendation systems apply the same idea to people, suggesting what the most similar users liked. Despite the similar name, k-means clustering is an unlabeled grouping method, not a predictor.

Common questions

How do you choose k in k-nearest neighbors?

Treat k as a setting to test. scikit-learn’s documentation says the best value is highly data-dependent: a larger k suppresses the effects of noise but makes the class boundaries less distinct. Try several values on examples the method has not seen, and use an odd k for a two-class vote so it cannot tie. Weighting closer neighbors more, through the library’s weights setting, is another option.

Brute-force k-NN compares the query with every stored example, so its search time grows with the size of the data. Exact tree indexes in scikit-learn, such as KD trees and ball trees, can skip candidates and still return the true neighbors. Approximate indexes such as HNSW find close matches faster and can miss some true neighbors. A vector database returns those neighbors, ranked by a score such as cosine similarity, to feed retrieval-augmented generation. k-NN as a predictor then votes or averages over the neighbors’ known answers.

Sources

Go deeper