Gaussian Naive Bayes
Most classifiers learn directly. Naive Bayes goes the other way round: it models how the features are distributed within each class, , and flips it with Bayes' rule. To make that tractable it assumes the features are independent given the class, an assumption that is almost never true and yet often good enough. The result trains in one pass over the data, needs very few examples, and handles thousands of features. The Machine Learning course shows it in scikit-learn; this lesson builds the Gaussian version and shows where the "naive" assumption costs you.
Bayes' rule with a naive likelihood
For class and features :
The product is the naive step: the joint distribution of features is replaced by one-dimensional ones. Gaussian naive Bayes models each as a normal density with its own mean and variance , estimated from the training rows of class . Products of many small densities underflow, so everything is done in logs:
The prediction is the class with the largest value; probabilities come from normalising with the log-sum-exp trick. Because each class has its own variances, the boundaries are quadratic curves. Background: Bayes' Theorem, The Gaussian Distribution, and Naive Bayes Classifiers in the Probability course.
From scratch
import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
X, y = load_iris(return_X_y=True)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3, random_state=0, stratify=y)
class GaussianNaiveBayes:
def fit(self, X, y, var_smoothing=1e-9):
self.classes_ = np.unique(y)
self.prior_ = np.array([np.mean(y == c) for c in self.classes_])
self.mean_ = np.array([X[y == c].mean(axis=0) for c in self.classes_])
eps = var_smoothing * X.var(axis=0).max() # as scikit-learn: keeps variances above zero
self.var_ = np.array([X[y == c].var(axis=0) for c in self.classes_]) + eps
return self
def joint_log_likelihood(self, X):
# log p(c) + sum_j log N(x_j | mean_cj, var_cj), for every row and class
ll = -0.5 * (np.log(2 * np.pi * self.var_)[None] + (X[:, None, :] - self.mean_[None]) ** 2 / self.var_[None]).sum(axis=2)
return np.log(self.prior_)[None] + ll
def predict_proba(self, X):
jll = self.joint_log_likelihood(X)
jll -= jll.max(axis=1, keepdims=True) # normalise in log space (log-sum-exp trick)
p = np.exp(jll)
return p / p.sum(axis=1, keepdims=True)
ours = GaussianNaiveBayes().fit(X_tr, y_tr)
sk = GaussianNB().fit(X_tr, y_tr)
print("class means for petal length:", ours.mean_[:, 2].round(3))
print("probabilities match sklearn:", np.allclose(ours.predict_proba(X_te), sk.predict_proba(X_te)))
print("first test flower:", ours.predict_proba(X_te[:1]).round(4), " true class", y_te[0])
print("test accuracy:", round(np.mean(ours.predict_proba(X_te).argmax(1) == y_te), 3))class means for petal length: [1.434 4.229 5.609]
probabilities match sklearn: True
first test flower: [[0. 0. 1.]] true class 2
test accuracy: 0.978
Training is just counting: a prior, a mean and a variance per class and feature (here numbers). The var_smoothing term adds a tiny fraction of the largest feature variance to every variance, so a feature that is constant within a class does not cause a division by zero. The probabilities match GaussianNB on every test flower, and 44 of the 45 are classified correctly.
When the naive assumption bites
The independence assumption counts correlated evidence several times. Below, 4 of the 10 features are informative and 4 more are linear combinations of them (redundant copies of the same evidence). Naive Bayes and logistic regression are trained on growing slices of one pool and tested on the same 2000 rows; then naive Bayes' probabilities are checked:
import numpy as np
from sklearn.datasets import make_classification
from sklearn.naive_bayes import GaussianNB
from sklearn.linear_model import LogisticRegression
from sklearn.calibration import CalibratedClassifierCV
from sklearn.metrics import brier_score_loss
# 4 informative features plus 4 redundant ones (linear combinations of them): the naive assumption is false
X, y = make_classification(n_samples=4000, n_features=10, n_informative=4, n_redundant=4,
n_clusters_per_class=1, random_state=0)
X_pool, y_pool, X_te, y_te = X[:2000], y[:2000], X[2000:], y[2000:]
for n in [10, 30, 100, 2000]:
nb = GaussianNB().fit(X_pool[:n], y_pool[:n])
lr = LogisticRegression(max_iter=1000).fit(X_pool[:n], y_pool[:n])
print(f"{n:5d} training rows: naive Bayes {nb.score(X_te, y_te):.3f} logistic regression {lr.score(X_te, y_te):.3f}")
p = GaussianNB().fit(X_pool, y_pool).predict_proba(X_te)[:, 1]
print("naive Bayes probabilities below 0.01 or above 0.99:", f"{np.mean((p < 0.01) | (p > 0.99)):.1%}")
cal = CalibratedClassifierCV(GaussianNB(), method="isotonic", cv=5).fit(X_pool, y_pool).predict_proba(X_te)[:, 1]
print("Brier score raw", round(brier_score_loss(y_te, p), 4), " calibrated", round(brier_score_loss(y_te, cal), 4)) 10 training rows: naive Bayes 0.623 logistic regression 0.988
30 training rows: naive Bayes 0.952 logistic regression 0.978
100 training rows: naive Bayes 0.978 logistic regression 0.981
2000 training rows: naive Bayes 0.984 logistic regression 0.991
naive Bayes probabilities below 0.01 or above 0.99: 97.7%
Brier score raw 0.0135 calibrated 0.0077
On this data logistic regression is ahead at every size; with only 10 rows (about 5 per class) naive Bayes' variance estimates are poor. From 100 rows on, naive Bayes' accuracy is close, because double-counted evidence still points the right way. Its probabilities are another matter: 97.7 % of them are below 0.01 or above 0.99, far more certain than a model with 98 % accuracy has any right to be. Calibrating the scores on held-out folds (isotonic regression via CalibratedClassifierCV) almost halves the Brier score (the mean squared error of the probabilities). Use naive Bayes' rankings and labels freely; calibrate before trusting its probabilities.
Hyperparameters, strengths, weaknesses
GaussianNB has just priors (fix the class priors instead of estimating them) and var_smoothing. Naive Bayes trains in a single pass, needs little data, scales to many features, handles missing features by simply leaving their terms out, and supports partial_fit for streaming data. It assumes conditional independence and (here) Gaussian features: skewed or multimodal features fit badly (a log transform or a quantile transform helps), and probabilities are overconfident when features are correlated. Use it as a fast baseline, for very small data sets, or when training must be incremental and cheap; for text use the multinomial variant.
Pitfalls
- Trusting the probabilities. Correlated features make them extreme; calibrate.
- Non-Gaussian features. Counts, binary flags and heavy-tailed amounts break the Gaussian model; use the matching variant (multinomial, Bernoulli, categorical) or transform the feature.
- Zero variance. Without smoothing, a constant feature within a class gives an infinite log density.
Practice
- A disease affects 1 % of people. A test feature has and . What is ?
Answer
. The prior matters: even a good test leaves the probability low for a rare disease.
- You duplicate one feature three times. How does naive Bayes' log-odds for that evidence change, and what does logistic regression do?
Answer
Naive Bayes adds the feature's log-likelihood ratio once per copy, so its evidence counts three times and the probabilities become more extreme. Logistic regression fits one weight per copy jointly; the three weights share the original effect (their sum stays about the same), so its predictions barely change.
Test yourself
What is the 'naive' assumption of naive Bayes?
- All classes are equally likely
- Features are independent of each other given the class
- Features are Gaussian
- The data is linearly separable
Why does the implementation work with log probabilities?
- Logs are faster to compute
- Products of many small densities underflow to zero
- Bayes' rule requires logs
- To make features independent
Naive Bayes is accurate on your data but most predicted probabilities are near 0 or 1. What is the most likely cause?
- Too much training data
- Correlated features whose evidence is counted several times
- The priors are wrong
- Variance smoothing is too large