Sub topic 9
Gaussian naive Bayes for continuous features
This chapter assumes you know the naive Bayes decision rule, the conditional independence assumption, and why we sum log probabilities. It also assumes you can read basic NumPy and scikit-learn code. Earlier chapters handled word counts. Here the features are real numbers, such as petal length in centimeters or a sensor reading.
The problem with continuous features
Count-based estimation works for words because each word has a small set of observed outcomes. A continuous feature almost never repeats an exact value. If you tried to estimate P(x_j = 5.1 | y = c) by counting, you would get zero for nearly every unseen value.
Gaussian naive Bayes avoids this by choosing a parametric model for each feature within each class. It assumes that, given class c, feature j follows a normal distribution:
P(xj | y = c) = N(xj; μcj, σ²cj)
The density is:
N(x; μ, σ²) = (1 / sqrt(2πσ²)) · exp(−(x − μ)² / (2σ²))
The naive assumption still applies. The model treats features as independent given the class, so the joint likelihood is a product of one-dimensional Gaussians. It does not model covariance between features.
Decision rule in log space
Taking logs turns the product into a sum. The score for class c on an input x with d features is:
log P(y = c) + Σj [ −½ log(2πσ²cj) − (xj − μcj)² / (2σ²_cj) ]
The predicted class is the one with the highest score. Each feature adds a penalty proportional to its squared distance from the class mean, measured in units of that class's variance. A class with a small variance on a feature punishes deviations harder, but it also gets a larger reward from the −½ log σ² term.
Estimating the parameters
Training stores three things.
- The prior for each class is its fraction of the training rows.
- The mean μ_cj is the average of feature j over rows of class c.
- The variance σ²_cj is the average squared deviation from that mean over the same rows.
The maximum likelihood variance divides by nc, not nc − 1. scikit-learn does the same. Training is one pass over the data, and the model has 2 × d × k parameters for k classes plus k priors.
Implementation from scratch
The code below follows the formulas directly. It also adds a small constant to every variance, the same trick scikit-learn uses, and compares the result against GaussianNB.
import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
def fit_gaussian_nb(X, y, var_smoothing=1e-9):
classes = np.unique(y)
epsilon = var_smoothing * X.var(axis=0).max()
priors = np.array([np.mean(y == c) for c in classes])
means = np.array([X[y == c].mean(axis=0) for c in classes])
variances = np.array([X[y == c].var(axis=0) for c in classes]) + epsilon
return classes, priors, means, variances
def log_scores(X, priors, means, variances):
diff = X[:, None, :] - means[None, :, :] # shape (n, k, d)
log_like = -0.5 * (np.log(2 * np.pi * variances) + diff**2 / variances)
return np.log(priors) + log_like.sum(axis=2) # shape (n, k)
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=0, stratify=y
)
classes, priors, means, variances = fit_gaussian_nb(X_train, y_train)
mine = classes[np.argmax(log_scores(X_test, priors, means, variances), axis=1)]
sk = GaussianNB().fit(X_train, y_train)
print("my accuracy:", np.mean(mine == y_test))
print("sklearn accuracy:", sk.score(X_test, y_test))
print("same predictions:", np.array_equal(mine, sk.predict(X_test)))
print("means match:", np.allclose(means, sk.theta_))The two models should agree on every prediction. The key array shapes are means[k, d] and variances[k, d]. The subtraction X[:, None, :] - means[None, :, :] uses broadcasting to compute every row-class-feature deviation at once.
Smoothing the variance
A feature can have zero variance within a class. This happens when the class has one row, or when the feature is constant for that class. The density then divides by zero, and any test value that differs from the constant gets an infinitely bad score.
GaussianNB handles this with var_smoothing. It adds var_smoothing * max(variance of each feature over all training data) to every variance. The default is 1e-9. The fitted value is stored in epsilon_. This plays the same role as Laplace smoothing for counts. It keeps a single degenerate estimate from vetoing a class.
Raise var_smoothing if you have small classes or near-constant features. A larger value flattens each Gaussian, so the model relies less on exact class statistics. Treat it as a hyperparameter and tune it with cross-validation. A log-spaced grid from 1e-9 to 1e-1 is a reasonable start.
Densities are not probabilities
The Gaussian density is not a probability. For a feature with a tiny variance, the density at the mean can be much larger than 1, and its log is positive. This is fine. The comparison across classes only needs consistent relative values, and the posterior is normalized afterward. Do not read a single log likelihood term as "the probability of this value."
Decision boundaries
Compare two classes by subtracting their scores. If every class has its own variances, the quadratic terms in x do not cancel, so the boundary is a quadratic surface. If the classes shared the same variances, the quadratic terms would cancel and the boundary would be linear. Gaussian naive Bayes is therefore more flexible than a linear classifier in that respect. Its axes are fixed, though. The covariance matrix per class is diagonal, so ellipses can stretch along feature axes but never tilt.
Failure modes
- Non-Gaussian features. Skewed or heavy-tailed features, such as income or durations, fit a normal curve poorly. A log transform often helps. Counts and binary flags are better served by multinomial or Bernoulli naive Bayes.
- Multimodal classes. If one class has two clusters on a feature, a single Gaussian puts its mean between them, where there is no data.
- Correlated features. Highly correlated features get counted as separate evidence. This inflates confidence, which is covered in the calibration chapter.
- Outliers. One extreme value inflates a class variance and loosens that class's likelihood on that feature. Check for outliers before fitting.
- Scaling. Rescaling a feature changes its means and variances together, so the log-likelihood differences between classes stay the same. The scores shift by a constant that is the same for every class. Scaling is therefore not required. The one exception is the variance-smoothing constant, which depends on the largest feature variance.
Using scikit-learn
The estimator follows the usual API. The following snippet shows the useful fitted attributes and a small tuning run.
from sklearn.datasets import load_iris
from sklearn.model_selection import GridSearchCV
from sklearn.naive_bayes import GaussianNB
X, y = load_iris(return_X_y=True)
model = GaussianNB().fit(X, y)
print("priors:", model.class_prior_)
print("means shape:", model.theta_.shape)
print("variances shape:", model.var_.shape)
grid = GridSearchCV(
GaussianNB(),
{"var_smoothing": [1e-9, 1e-6, 1e-3, 1e-1]},
cv=5,
)
grid.fit(X, y)
print("best:", grid.best_params_, round(grid.best_score_, 3))You can also pass priors=[...] to set class priors by hand instead of learning them from the data. This is useful when the class mix in training differs from the mix you expect in deployment.
Exercise
A class has three training rows with feature values 2.0, 2.0, 2.0 for one feature. At test time the feature value is 2.1. What goes wrong without variance smoothing, and what does GaussianNB do about it?
Show answer
The estimated variance for that class and feature is 0, so the density has a division by zero and the log score for the class becomes infinitely negative (or undefined) for any value other than 2.0. The class could never win on this feature. GaussianNB adds epsilon = var_smoothing * max feature variance to every variance, which gives the Gaussian a small width so that 2.1 gets a finite, very low score instead of an infinite penalty.
Exercise
You standardize every feature (zero mean, unit variance over the whole training set) before fitting GaussianNB. Should you expect different predictions than with the raw features? Why?
Show answer
Almost none. Standardizing is a linear change per feature, so each class mean and variance change in the same way. The squared-deviation term is unchanged, and the log-variance term shifts by the same constant for every class. That constant cancels when classes are compared. Small differences can arise only through the variance-smoothing constant, which depends on the largest feature variance.