Algorithms Made Simple

Nearest Neighbors and k-Means: Learning From Similarity

Classify by looking at the closest examples, group data with k-means, and know where each breaks.

Algorithms Made Simple · 5 min read

Two simple ideas, “look at the closest examples” and “group things that look alike,” power a surprising amount of machine learning.

k-nearest neighbors

To classify a new item, find the k most similar labeled examples and take a majority vote. There is no training step; the data are the model. Small k follows the data closely and is noisy. Large k smooths more and may blur real boundaries. Choose k using a validation set.

Distance needs care

Similarity is usually measured as distance. If one feature is measured in thousands and another in fractions, the large one dominates. Scale features to comparable ranges first, and think about which features should count.

k-means clustering

k-means groups unlabeled data into k clusters. Start with k guessed centers. Assign every point to its nearest center. Move each center to the average of its points. Repeat until the assignments stop changing.

Limits of k-means

  • You must choose k in advance, and there may be no single right answer.
  • Different starting centers can lead to different results, so run it several times.
  • It prefers round, similar-sized clusters.
  • Clusters are suggestions to inspect, not proof of real categories.

A practical habit

Look at examples from each group. If you cannot describe what the items share, the grouping may not be useful, however neat the picture looks.

More guides from this book