SDE & MLE Prep

Gaussian Naive Bayes

Key idea: per class, model each feature as an independent Gaussian. Predict argmax_c log p(c) + Σ_j log N(x_j; μ_cj, σ²_cj) — work in log space to avoid underflow.

import numpy as np

class GaussianNB:
    def fit(self, X, y):
        self.classes = np.unique(y)
        self.mu = np.array([X[y == c].mean(0) for c in self.classes])
        self.var = np.array([X[y == c].var(0) + 1e-9 for c in self.classes])
        self.logprior = np.log(np.array([(y == c).mean() for c in self.classes]))
        return self

    def predict(self, X):
        # (N, C): log prior + sum of per-feature Gaussian log-likelihoods
        ll = -0.5 * (np.log(2 * np.pi * self.var)[None] + (X[:, None, :] - self.mu[None]) ** 2 / self.var[None]).sum(-1)
        return self.classes[(ll + self.logprior).argmax(1)]

rng = np.random.default_rng(3)
X = np.vstack([rng.normal([0, 0], 1, (200, 2)), rng.normal([3, 3], 1, (200, 2))])
y = np.r_[np.zeros(200, int), np.ones(200, int)]
acc = (GaussianNB().fit(X, y).predict(X) == y).mean()
assert acc > 0.95
print("ok acc", acc)