134. Predict with Gaussian Naive Bayes
Naive Bayes assumes features are independent given the class. With Gaussian features, each class needs only a prior, a mean per feature and a variance per feature.
Write gnb_predict(X_train, y_train, X_test). For each class c (sorted ascending):
- prior = share of training rows with class c
- mean and population variance per feature, plus 1e-9 added to every variance
Score each test row with log prior + sum over features of log N(x; mean, var). Return a list of the best class per test row (ints).
Work in log space so tiny probabilities do not underflow.
def gnb_predict(X_train, y_train, X_test)Example 1
Input: gnb_predict([[0.0], [1.0], [10.0], [11.0]], [0, 0, 1, 1], [[0.5], [9.0]])
Output: [0, 1]
Constraints
- Python 3 with NumPy. Code runs in your browser.
- Run checks the sample tests. Submit checks the full hidden test set (Pro).
Hint 1
log N(x; m, v) = -0.5 log(2 pi v) - (x - m) ** 2 / (2 v).
Hint 2
Build a (n_test, n_classes) score matrix and take argmax.
Common mistakes
- The buggy version drops it and the prior, so it just picks the class with the smallest scaled distance.
Understand the idea
Gaussian Naive Bayes pretends features are independent once you know the class. Then each class is described by a prior and, per feature, a bell curve with its own mean and variance. To classify, add the log prior to the sum of each feature's log bell-curve height and pick the class with the highest total. Logs turn tiny products into safe sums. Worked example, one feature, equal priors 0.5: class 0 trained on [0, 2] has mean 1, variance 1; class 1 trained on [9, 11] has mean 10, variance 1. For x = 4, the shared parts cancel, leaving -(4 - 1)^2 / 2 = -4.5 for class 0 and -(4 - 10)^2 / 2 = -18 for class 1, so predict 0. When variances differ, the -0.5 log(2 pi var) term matters: a tight class has a taller peak.
score_c = log prior_c + sum over features of [-0.5 log(2 pi var) - (x - mean)^2 / (2 var)], with population variance plus 1e-9
Spam filters used Naive Bayes for years.
Topics
Companies1
- Meta a candidate reported this question Timed ML screen: concept questions then classic models from scratch (Land the Lab)
From public interview reports and guides. Not affiliated with or endorsed by these companies.