Sub topic 9
Gaussian naive Bayes for continuous features
This chapter assumes you know the naive Bayes decision rule, how class priors are estimated, and why we sum log probabilities. Here we handle features that are real numbers, such as petal length, instead of counts.
The idea
With count features, the likelihood P(xj | y) comes from counting words. A continuous feature has no counts to tally. Gaussian naive Bayes assumes that, within each class, each feature follows a normal distribution. So P(xj | y = c) is the normal density with a class-specific mean and variance.
Training is short. For each class c and each feature j, compute:
- the mean of feature j over the training rows of class c
- the variance of feature j over those same rows
- the class prior, which is the fraction of rows in class c
The conditional independence assumption still applies. Each feature gets its own one-dimensional Gaussian, and the model never estimates covariances between features.
The scoring rule in log space
The log of the normal density for one feature is:
log N(x; mu, var) = -0.5 * (log(2 * pi * var) + (x - mu)^2 / var)The class score is the log prior plus this value summed over all features. The predicted class is the one with the highest score.
From scratch
This NumPy version trains and predicts on the iris dataset. The small constant added to the variance prevents division by zero.
import numpy as np
from sklearn.datasets import load_iris
X, y = load_iris(return_X_y=True)
classes = np.unique(y)
mean = np.array([X[y == c].mean(axis=0) for c in classes])
var = np.array([X[y == c].var(axis=0) for c in classes]) + 1e-9
log_prior = np.log(np.array([(y == c).mean() for c in classes]))
def predict(x):
log_pdf = -0.5 * (np.log(2 * np.pi * var) + (x - mean) ** 2 / var)
scores = log_prior + log_pdf.sum(axis=1)
return classes[np.argmax(scores)]
print(predict(X[0]), y[0])Here mean and var have shape (3, 4), one row per class and one column per feature. Broadcasting subtracts the sample from every class row at once.
With scikit-learn
GaussianNB does the same work and adds probability output.
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_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=0, stratify=y
)
model = GaussianNB()
model.fit(X_train, y_train)
print("accuracy:", model.score(X_test, y_test))
print("class priors:", model.class_prior_)
print("first test row probabilities:", model.predict_proba(X_test[:1]))The fitted attributes theta_ (means) and var_ (variances) match the arrays in the from-scratch version.
Common errors
- Zero variance. A feature that is constant within a class gives a variance of 0, so the density is undefined. scikit-learn adds
var_smoothingtimes the largest feature variance to every variance. The default is 1e-9. Raise it if you see unstable results. - Non-Gaussian features. Skewed or multimodal features fit the normal curve badly. Try a log or power transform first.
- Correlated features. Highly correlated columns count the same evidence twice. This makes the scores overconfident.
- Wrong variant. Use
GaussianNBonly for real-valued features. For word counts, use multinomial naive Bayes.
Exercise
In a two-class problem, a feature has mean 5.0 and variance 1.0 in class A, and mean 8.0 and variance 1.0 in class B. For x = 6.0, which class gives the larger log density for this feature, and why?
Show answer
Class A. The log density depends on (x - mu)^2 / var when the variances are equal. For A it is (6 - 5)^2 = 1. For B it is (6 - 8)^2 = 4. The smaller squared distance gives the higher log density, so A scores higher on this feature.