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)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. Rule: 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.