Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

ML coding · Probabilistic models

Gaussian naive Bayes classifier

Medium · Target 20 minutes · Python and NumPy

Fit a Gaussian naive Bayes model on X_train (n × d) with integer labels y_train, and return the predicted label for each row of X_test.

  • Prior of class c: the fraction of training rows with label c.
  • For each class and feature: the mean and the biased variance (divide by the class count), plus ε = 10⁻⁹ × the largest variance of any feature over the whole training set.
  • Predict the class with the largest log prior plus Σj log N(xj; μcj, σ²cj).

Every feature varies within every class in the tests.

Examples

Input X_train = [[0, 0], [1, 1], [0, 1], [5, 5], [6, 6], [5, 6]], y_train = [0, 0, 0, 1, 1, 1], X_test = [[0.5, 0.5], [5.5, 5.5]]

Output [0, 1]

Two well-separated clusters: each test point goes to the nearer one.

Input X_train = [[0], [2], [10], [12]], y_train = [0, 0, 1, 1], X_test = [[6.1]]

Output [1]

Equal variances and priors: the boundary is the midpoint, 6.

Input X_train = [[0], [1], [2], [0], [20]], y_train = [0, 0, 0, 1, 1], X_test = [[1]]

Output [0]

Class 1 is so spread out that its density at 1 is low: class 0 wins.

Constraints

  • 2 ≤ n ≤ 5000, 1 ≤ d ≤ 50
  • Every class has at least two training rows
  • Labels are integers

Hints

Hint 1

np.unique(y) gives the classes. For each, take the mean and np.var of its rows.

Hint 2

The log density of a normal is −½ log(2πσ²) − (x − μ)²/(2σ²). Sum it over features.

Hint 3

Broadcast test rows against class means with T[:, None, :] − mu[None]: shape (n_test, n_classes, d). Sum over the last axis, add the log priors, take argmax over classes.

Where candidates go wrong

  • Multiplying densities instead of adding log densities: with fifty features the products underflow and every class scores zero.
  • Using the unbiased variance. Naive Bayes, like scikit-learn, uses the maximum-likelihood estimate.
  • Forgetting the class prior, which matters whenever the classes are unbalanced.
  • Returning the index of the class rather than the class label when labels are not 0, 1, 2, …
Console⌘/Ctrl + Enter runs

Python runs in your browser with NumPy. The first run downloads the runtime, which takes a few seconds.


Why interviewers ask it

It is the simplest generative classifier, and writing it tests three things quickly: whether you work in log space, whether you can vectorise over test points, classes and features at once, and whether you know scikit-learn's variance-smoothing convention or can reason your way to it.

The theory behind it is in the lesson Naive Bayes, EM, Viterbi and Markov chains from scratch.


Keep going