Gaussian Naive Bayes: Bell Curves for Every Class

Classic MLHard+20 XP+20

Gaussian Naive Bayes: Bell Curves for Every Class

Bernoulli naive Bayes handles yes/no features. Gaussian naive Bayes handles continuous ones — height, temperature, price — by assuming each feature follows a bell curve whose centre and width it learns separately for every class.

Training is just bookkeeping. For each class, from its training rows only:

  • the prior: that class's share of the training data,
  • each feature's mean,
  • each feature's variance, dividing by n (the population form, not n - 1).

Predicting scores every class for a row and keeps the highest. Working in logs, as always:

log⁡P(class∣x)∝log⁡P(class)+∑i[−12log⁡(2πσi2)−(xi−μi)22σi2]\log P(\text{class} \mid x) \propto \log P(\text{class}) + \sum_i \left[ -\tfrac{1}{2}\log(2\pi\sigma_i^2) - \frac{(x_i - \mu_i)^2}{2\sigma_i^2} \right]logP(class∣x)∝logP(class)+i∑​[−21​log(2πσi2​)−2σi2​(xi​−μi​)2​]

Task: write gnb_predict(X_train, y_train, X_test) returning the predicted label for each test row.

  • X_train and X_test are lists of rows of numbers; y_train holds the labels, which may be numbers or strings.
  • Every class has at least two training rows and no feature is constant within a class, so no variance is ever zero.
  • If two classes score exactly the same, return the smaller label.
  • Return the labels themselves, not indices.

That formula is just the log of the normal density. The first term depends only on the class's width — a class with wide spread pays a constant penalty — and the second is the squared distance from the class's centre, measured in units of its own variance. Naive Bayes is, in the end, asking which class's bell curve your row looks least surprising under.

Examples

X_train = [[1], [2], [8], [9]]
y_train = [0, 0, 1, 1]
X_test = [[1.5], [8.5]]
returns [0, 1]
X_train = [[1, 1], [2, 2], [8, 8], [9, 9]]
y_train = [0, 0, 1, 1]
X_test = [[1, 2], [9, 8], [5, 5]]
returns [0, 1, 0]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run