Lably
Skip to content

K-nearest neighbors algorithm

Non-parametric classification method

  • 13 min read
  • 16 chapters
  • 4 labs on Lably

Learn it on Lably

The k-NN algorithm can also be generalized for regression. In k-NN regression, also known as nearest neighbor smoothing, the output is the property value for the object. This value is the average of the values of k nearest neighbors. If k = 1, then the output is simply assigned to the value of that single nearest neighbor, also known as nearest neighbor interpolation.

For both classification and regression, a useful technique can be to assign weights to the contributions of the neighbors, so that nearer neighbors contribute more to the average than distant ones. For example, a common weighting scheme consists of giving each neighbor a weight of 1/d, where d is the distance to the neighbor.

The input consists of the k closest training examples in a data set. The neighbors are taken from a set of objects for which the class (for k-NN classification) or the object property value (for k-NN regression) is known. This can be thought of as the training set for the algorithm, though no explicit training step is required.

A peculiarity (sometimes even a disadvantage) of the k-NN algorithm is its sensitivity to the local structure of the data. In k-NN classification the function is only approximated locally and all computation is deferred until function evaluation. Since this algorithm relies on distance, if the features represent different physical units or come in vastly different scales, then feature-wise normalizing of the training data can greatly improve its accuracy.

Statistical setting

Suppose we have pairs (X1,Y1),(X2,Y2),…,(Xn,Yn) taking values in Rd×{1,2}, where Y is the class label of X, so that X|Y=r∼Pr for r=1,2 (and probability distributions Pr). Given some norm ‖⋅‖ on Rd and a point x∈Rd, let (X(1),Y(1)),…,(X(n),Y(n)) be a reordering of the training data such that ‖X(1)−x‖≤⋯≤‖X(n)−x‖.

Sign in to keep reading

15 more chapters are free with a Lably account.

More in Robotics