Skip to content
GATEiit

GATE DA · Machine Learning

k-nearest neighbour and naive Bayes classifier

Two simple classifiers: k-nearest neighbour, which votes among the closest training points, and naive Bayes, which applies Bayes' theorem with conditionally independent features; GATE asks for distance votes, posterior probabilities and smoothing.

Before you start

  • Bayes' theorem →

    Naive Bayes picks the class with the largest posterior P(c∣x)∝P(x∣c)P(c).

  • Independence of events →

    The naive assumption is that features are independent given the class.

  • Classification set-up →

    Both methods are classifiers; you need decision boundaries and train/test error.

  • Distances between vectors

    kNN depends entirely on the distance used, e.g. Euclidean ∥x−z∥2 or Manhattan ∥x−z∥1.

This topic comes before: Clustering algorithms: k-means and k-medoid, Cross-validation: leave-one-out (LOO) and k-fold

Concept notes

1. k-nearest neighbour (kNN)

kNN stores the training set. To classify a query q:

  1. Compute the distance from q to every training point.
  2. Take the k nearest.
  3. Predict the majority class among them (for kNN regression, predict their average y).

Common distances: Euclidean ∑j(xj−zj)2, Manhattan ∑j∣xj−zj∣, and Minkowski (∑j∣xj−zj∣p)1/p (which gives Manhattan for p=1 and Euclidean for p=2). To find the nearest points you can compare squared Euclidean distances and skip the square root.

Properties:

  • Lazy / instance-based: no training phase; prediction costs O(nd) per query with brute force.
  • Non-parametric: the boundary can take any shape; it is piecewise linear for 1-NN (a Voronoi partition).
  • Choose odd k for two classes to avoid ties; a distance-weighted vote (weight 1/d) is a common variant.
  • Feature scaling matters: a feature measured in large units dominates the distance, so standardise first.
  • In high dimensions all distances become similar (curse of dimensionality), and kNN degrades.
P1P4P2P6P3P5qclass +class −inner circle: k = 1, outer: k = 3
kNN around query q: k = 1 picks P1 (+); k = 3 picks P1, P4 (+) and P2 (−), still +

2. Choosing k

k controls the bias–variance trade-off:

Small k (e.g. 1) Large k
Boundary jagged, follows individual points smooth
Training error 0 for 1-NN (distinct points) higher
Variance high, sensitive to noise low
Bias low high

At the extreme k=n, every query gets the overall majority class.

  • 1-NN has zero training error because each training point is its own nearest neighbour, but that says nothing about test error.
  • Choose k by cross-validation, not by training error.
  • As n→∞, the 1-NN error rate is at most twice the Bayes (optimal) error rate, a classical result that explains why such a simple rule works.

The answer for a query can change with k. In the figure, q=(0,0) gives + for k=1 and k=3, but with k=5 the neighbours P1, P4 (+) and P2, P6, P3 (−) give −.

3. Naive Bayes classifier

For classes c and features x=(x1,…,xd), Bayes' theorem gives P(c∣x)=P(x∣c) P(c)P(x). Estimating P(x∣c) for all combinations of feature values is impossible with limited data, so naive Bayes assumes the features are conditionally independent given the class: P(x∣c)=∏j=1dP(xj∣c). The MAP decision rule is c^=arg⁡max⁡c  P(c)∏jP(xj∣c). P(x) is the same for every class, so you can compare the numerators and normalise only if the posterior itself is asked.

Training is just counting: P(c) = fraction of training points in class c, and P(xj=v∣c) = fraction of class-c points with xj=v.

  • It is a generative model: it models P(x∣c) and P(c).
  • It is fast, needs little data and handles many features (text classification).
  • The independence assumption is rarely true, yet the ranking of classes is often right, so accuracy can be good even when the probabilities are poorly calibrated.
  • To avoid underflow when multiplying many small numbers, add logs: ln⁡P(c)+∑jln⁡P(xj∣c).

4. Zero counts, smoothing and continuous features

The zero-frequency problem: if a feature value never appears with class c in training, P(xj=v∣c)=0 and the whole product becomes 0, whatever the other features say.

Laplace (add-one) smoothing fixes this. For a feature with V possible values and Nc training points in class c: P(xj=v∣c)=count(xj=v,c)+1Nc+V. The general form adds α to each count and αV to the denominator. For text (multinomial NB), V is the vocabulary size and Nc the total word count in class c.

Gaussian naive Bayes handles real-valued features by fitting a normal distribution per feature per class: P(xj∣c)=12πσjc2exp⁡ ⁣(−(xj−μjc)22σjc2). It needs a mean and a variance for every (feature, class) pair: 2dK numbers, plus K−1 free priors.

kNN Naive Bayes
Type instance-based, discriminative generative, probabilistic
Training cost none one counting pass
Prediction cost O(nd) per query O(dK) per query
Main assumption nearby points share labels features independent given class

Formulas to remember

Euclidean distance
d(x,z)=∑j(xj−zj)2
Manhattan distance
d(x,z)=∑j∣xj−zj∣
Naive Bayes rule
c^=arg⁡max⁡c  P(c)∏j=1dP(xj∣c)
Posterior
P(c∣x)=P(c)∏jP(xj∣c)∑c′P(c′)∏jP(xj∣c′)
Laplace smoothingV = number of possible values of the feature
P(xj=v∣c)=nv,c+1Nc+V

Common mistakes

  • Forgetting to multiply by the class prior P(c) in naive Bayes.
  • In Laplace smoothing, adding 1 to the denominator instead of V (the number of possible values).
  • Running kNN on unscaled features, so one large-unit feature decides every neighbour.
  • Choosing k by training error; 1-NN always wins on training data.
  • Reporting the unnormalised naive Bayes score as the posterior; divide by the sum over classes.

Worked examples

Try each step yourself, then reveal the working.

Example 1: kNN with different k

numerical

Training points: P1 (1, 0) +, P4 (−1, −1) +, P2 (0, 2) −, P6 (−2, 1) −, P3 (2, 2) −, P5 (3, 0) +. Classify q=(0,0) with Euclidean distance for k=1,3,5.

  1. Step 1: Compute squared distances to $q$.

    Try it on paper first.

Example 2: Naive Bayes on two categorical features

numerical

Training data (10 days): class Yes on 6 days, No on 4. Among Yes days: Sunny 2, Rain 4; Wind weak 5, strong 1. Among No days: Sunny 3, Rain 1; weak 1, strong 3. Classify a day that is Sunny with strong wind and find P(No∣x).

  1. Step 1: Estimate the class-conditional probabilities.

    Try it on paper first.

Example 3: Laplace smoothing rescues a zero

numerical

A feature Colour takes 3 values (red, green, blue). Class A has 8 training points: red 0, green 5, blue 3. Find P(red∣A) without and with add-one smoothing.

  1. Step 1: Use raw counts.

    Try it on paper first.

Example 4: Why scale features for kNN?

conceptual

Features are annual income (in rupees, range about 2,00,000 to 20,00,000) and age (in years, 20 to 60). What goes wrong with Euclidean kNN, and what is the fix?

  1. Step 1: Compare the size of differences.

    Try it on paper first.

Previous year questions

5 official GATE DA questions on this topic, newest first.

Practise these 5 PYQs →

Topic test

10 questions: up to 4 official PYQs and original practice questions, with GATE marking (MCQ wrong answers lose marks). Score 60% or more to pass. A new set is drawn each time.

Mark as mastered

Loading your progress…

My revision notes

Notes written by the GATEiit team against the official GATE DA syllabus; being checked by a reviewer. Updated 2026-11-21. Spotted a mistake? Use Report an issue on any question, or contact us.