There is no training
k-NN stores the training set and does all of its work at prediction time.
- : the point being predicted.
- : one stored training point.
- : the number of features.
Every stored point is measured against the query, the smallest distances win, and those neighbours decide the answer.
The vote, and the average
- : the indices of the nearest stored points.
- : 1 when the condition holds and 0 when it does not.
For classification the most common label among the neighbours wins.
For regression it is their mean instead, and the only thing that changed is what you do with the neighbours once you have them.
One prediction, in order
- Compute the distance from the query to every stored training point.
- Sort those distances and keep the smallest .
- Read the labels of those points.
- Take the majority label, or the mean value.
- Discard everything and start again for the next query.
What actually controls
draws a boundary that passes between every pair of differently labelled points, so the training error is zero and the variance is enormous.
Raising averages more neighbours together, which smooths the boundary, lowers the variance and raises the bias.
The usual starting point is the square root of the training size, taken as an odd number so a two-class vote cannot tie.
The honest answer is cross-validation, because the right depends on how much the classes overlap and nothing else predicts that.
The three costs nobody mentions first
Each prediction touches all stored points across all features, so the model gets slower as the data grows rather than faster.
The whole training set is the model, so memory scales with the data too.
Distance is measured in the units of the features, so an unscaled column measured in thousands drowns out every column measured in fractions.