The idea
These two families are merged here on purpose: they are the two simplest classifiers that are still strong baselines, and each fits in one sentence. KNN says you are what your neighbors are. Naive Bayes says multiply the evidence and pretend the features never talk to each other. One defers all work to query time; the other compresses the data to counts and defers nothing. Interviewers love both because each has one big idea and one famous failure mode.
K-nearest neighbors: prediction by memory
KNN has no training step — it is lazy (instance-based) learning. The "model" is the stored training set. To classify a query , find the training points closest to it under some distance and take a majority vote:
where is the index set of the nearest neighbors. Training costs (store the data); every query costs — a full scan of points in dimensions. Eager models pay once up front; KNN pays at every prediction, which is exactly backwards from what production usually wants.
is the bias-variance dial. At the classifier memorizes the training set — zero training error, a Voronoi-cell boundary around every point, and maximal variance: one mislabeled neighbor flips predictions in its whole cell. At every query receives the global majority class — maximal bias, zero variance, and the model has collapsed into "predict the prior". Tune by cross-validation (a common starting heuristic is ), and use odd for binary problems to dodge ties.
Distance choice and scaling. Standard metrics:
- Euclidean — the default for dense, comparable features.
- Manhattan — less dominated by a single coordinate's large deviation.
- Cosine distance — direction only, magnitude ignored; the workhorse for sparse text and embeddings.
Because distances add raw per-feature differences, scaling is mandatory: an income gap of 1000 contributes to squared Euclidean distance while a 25-year age gap contributes — the neighbor search becomes a one-feature model. Standardize (or min-max) before any distance computation.
The famous failure mode: the curse of dimensionality. As grows with fixed, pairwise distances concentrate — the ratio of the farthest to the nearest neighbor's distance tends toward 1, so "nearest" carries almost no information and the vote approaches a poll of random points. Each irrelevant feature adds pure noise to every distance. Mitigations: feature selection, PCA or learned embeddings, cosine on sparse data.
Query-cost mitigations: KD-trees and ball trees give roughly logarithmic queries but only help in low dimension (rule of thumb: below about 20). Beyond that, approximate nearest neighbors — LSH, HNSW graphs (the engines inside libraries like FAISS) — trade exactness for orders-of-magnitude speedups.
Naive Bayes: multiply the evidence
Start from Bayes' rule and drop the denominator, which is constant across classes:
Estimating the joint over features is hopeless — the table is exponential in . The naive move assumes features are conditionally independent given the class:
That factorization turns one -dimensional estimation problem into one-dimensional ones — which is why NB trains in a single counting pass and shrugs at a 100,000-word vocabulary. Always work in log space: a product of hundreds of probabilities like underflows double precision after a few hundred factors; sums of logs never do.
Variants — match the likelihood to the feature type:
- Gaussian NB — continuous features; fits a per-class mean and variance for each feature.
- Multinomial NB — count features (word frequencies, tf); the text baseline.
- Bernoulli NB — binary presence/absence features; explicitly counts absent words as evidence, which can win on short documents.
Laplace smoothing. With counts, an unseen word-class pair gives , and one zero in a product vetoes the entire class no matter how strong the rest of the evidence is. Add-one smoothing fixes this:
where is the count of word in class , the total token count in class , and the vocabulary size. ( below 1 — Lidstone smoothing — often edges out add-one on real text.)
Calibration caveat. Correlated features get multiplied in as if independent, so NB's posteriors slam toward 0 and 1. The ranking and the argmax are usually fine; the probabilities are not. Calibrate (Platt scaling, isotonic regression) before anyone consumes them as probabilities.
Worked example
Multinomial NB spam filter. Four training documents, vocabulary words: free, win, meeting.
| Doc | Class | Text |
|---|---|---|
| d1 | spam | "free win" |
| d2 | spam | "free free win" |
| d3 | ham | "meeting" |
| d4 | ham | "free meeting" |
Priors: 2 spam, 2 ham out of 4 docs, so . Token counts per class (spam has tokens total, ham has ):
| Word | Count in spam | Count in ham |
|---|---|---|
| free | 3 | 1 |
| win | 2 | 0 |
| meeting | 0 | 2 |
| total | 5 | 3 |
Laplace-smoothed likelihoods, denominators (spam) and (ham):
| Word | Smoothed prob. given spam | Smoothed prob. given ham |
|---|---|---|
| free | ||
| win | ||
| meeting |
Sanity check: each column sums to 1 ( and ).
Classify "free win":
Normalize over a common denominator of 288: and , so
Why the smoothing mattered: without it, , the ham score collapses to exactly zero, and the posterior becomes a certainty of 1.0 for spam — one never-seen word-class pair silently vetoes a class. With a realistic vocabulary this happens on virtually every document.
Log-space view: the posterior odds are , and — the same after the sigmoid. On real documents you are summing hundreds of terms like ; multiplying the raw probabilities instead would underflow double precision after a few hundred words.
Cheat sheet
KNN
- Rule: majority vote of the nearest points; distance-weighted votes are the standard upgrade (helps ties and imbalance).
- Costs: train , query ; KD/ball trees help only for below about 20; use approximate NN (LSH, HNSW) beyond that.
- : Voronoi memorization, high variance. : always the majority class, high bias. Tune by CV; odd for binary.
- Named fact (Cover-Hart): as , the 1-NN error rate is at most twice the Bayes-optimal error.
- Scale features first, always; cosine for sparse/text; watch class imbalance — a large drifts toward the majority class.
Naive Bayes
- Rule: — always in log space.
- Smoothing: ; is add-one, (Lidstone) often better on text.
- Variant picker: continuous features — Gaussian; counts/tf — Multinomial; binary presence — Bernoulli (uses absences as evidence; strong on short docs).
- Boundary geometry: multinomial/Bernoulli NB have a log-posterior linear in the count/binary features (the weights are log-probabilities); Gaussian NB is quadratic (linear if variances are tied across classes).
- Probabilities are overconfident by construction; ranking is fine — calibrate if the number itself matters.
Head to head
| KNN | Naive Bayes | |
|---|---|---|
| Core assumption | Smoothness: nearby points share labels | Conditional independence of features given class |
| Training cost | — store the data ( memory) | — one counting pass |
| Query cost | exact; sublinear with trees/ANN | for classes |
| Feature scaling | Mandatory | Essentially irrelevant |
| Decision boundary | Arbitrarily wiggly (Voronoi at ) | Linear (multinomial, tied-variance Gaussian) or quadratic (general Gaussian) |
| High dimensions | Degrades — distances concentrate | Fine — separate 1-D estimates |
| Probability output | Vote fraction, coarse for small | Overconfident; ranking still good |
Symptom to fix
| Symptom | Diagnosis | Fix |
|---|---|---|
| KNN predictions track a single feature | Unscaled features | Standardize / min-max before distances |
| KNN collapses after adding features | Distance concentration (curse of dimensionality) | Feature selection, PCA, embeddings, cosine on sparse data |
| KNN inference too slow | scan per query | KD/ball tree (low ), HNSW/LSH (high ) |
| KNN always predicts majority class | too large or class imbalance | Smaller , distance-weighted votes |
| NB scores a class as exactly impossible | Zero count for a feature-class pair | Laplace / additive smoothing |
| NB probabilities pinned at 0 or 1 | Correlated features double-counted | Expected; calibrate (Platt / isotonic) if probabilities matter |
| NB scores underflow to zero | Product of many small probabilities | Sum log-probabilities instead |