k-Nearest Neighbours and Naive Bayes

Two simple, instructive models: similarity-based prediction and fast probabilistic classification with independence assumptions.

Beginner · about 4 hours · difficulty 2/5

Learn first: Logistic Regression and Linear Classifiers

These models are rarely your final choice on tabular data, but they are fast baselines, teach key concepts and remain useful in specific niches.

k-nearest neighbours

  • Predicts from the labels of the k closest training points; no real training step.
  • Needs scaled features and a sensible distance metric.
  • Small k overfits (noisy), large k underfits (too smooth).
  • Suffers from the curse of dimensionality: in many dimensions all points look equally far apart.
  • The same idea powers vector search over embeddings (approximate nearest neighbours).

Naive Bayes

  • Applies Bayes' rule assuming features are independent given the class.
  • Multinomial NB on word counts is a classic, very strong baseline for text classification.
  • Gaussian NB for continuous features, Bernoulli NB for binary ones.
  • Trains in one pass and handles huge vocabularies easily; probabilities tend to be poorly calibrated.

Good enough to move on when you can explain why kNN degrades in high dimensions and build a text classifier with TF-IDF or counts plus naive Bayes.

Key concepts

  • Distance metrics
  • Choosing k
  • Curse of dimensionality
  • Multinomial naive Bayes for text
  • Gaussian and Bernoulli NB
  • Approximate nearest neighbour search

Mini project

Build an SMS spam filter on the UCI SMS Spam Collection with CountVectorizer and multinomial naive Bayes, and compare it with kNN on TF-IDF features.

Check yourself

What does the 'naive' in naive Bayes assume, and why does the model often work well anyway?

Free resources