K-Nearest Neighbors
Classifying or predicting by looking at the k closest training points β the simplest non-parametric method, intuitive yet powerful.
Current vote
Class 1
1 votes for C0
2 votes for C1
The amber circle grows until it reaches the kth nearest point. Only points inside that radius vote.
k-Nearest Neighbors (k-NN) is a simple non-parametric algorithm: to classify a new point, find the training points closest to it and take the majority class.
Algorithm:
- Choose (number of neighbors)
- For a new point , compute the distance to every training point
- Find the training points with smallest distance
- Predict the majority class among those neighbors
Distance: usually Euclidean distance , but any distance function works.
: assign the class of the single nearest neighbor. Large : smoother boundary, more robust to noise.
- Non-parametric: makes no assumption about the underlying data distribution
- "Lazy" learning: no training phase β all the work happens at prediction time
- Naturally handles multi-class problems via simple majority vote
- Decision boundary complexity adapts to the data, with no fixed functional form
- Forgetting to scale features: distance-based methods let large-scale features dominate unless every feature is standardized first
- Using an even for binary classification: ties become possible and need a tie-breaking rule, which an odd avoids
- Ignoring the curse of dimensionality: in high dimensions, "nearest" stops being meaningful as distances between all points converge
Given measurements (petal length, petal width) of a new flower: find the 3 nearest flowers in the training set. If 2 are Setosa and 1 is Versicolor, predict Setosa. Simple, no training required β just store all training examples.
What is the computational cost of classifying a single test point using k-NN with training points and features? How does this compare to training a logistic regression model?
Solution
For k-NN: computing distances to all training points costs . Finding the smallest costs (or for exact sort). Total per prediction: . Training cost: (just store the data).
For logistic regression: training costs (gradient descent, iterations). Prediction costs (dot product + sigmoid). k-NN is free to "train" but expensive to predict; logistic regression is the opposite.
Approximate nearest neighbor methods (KD-tree, ball tree, FAISS) can reduce query time to or approximately.
Related concepts
Needs first