Curriculum02. Supervised LearningLesson 7 of 7

Naive Bayes

Conditional probability and conditional independence assumptions.

16 min readBeginnerModule 02
01 // CORE INTUITION

Core Intuition: Weighing Independent Clues

Suppose you open an email containing "urgent", "wire", and "invoice". Even without reading grammar, your brain starts from a baseline spam rate (prior) and multiplies how surprisingly frequent each clue word is in spam compared to normal mail (likelihoods).

Naive Bayes formalizes this clue-multiplication trick. It makes the bold simplifying assumption that every feature acts independently once the class is known, turning impossible joint probability tables into fast multiplication.

Takeaway:Naive Bayes combines class base rates with independent per-feature likelihoods via Bayes theorem.
02 // THE PROBLEM IT SOLVES

The Problem It Solves: Exponential Joint Tables

Modeling the exact joint probability P(x1,x2,…,xd∣y)P(x_1, x_2, \dots, x_d \mid y) across d=50d = 50 binary indicators requires estimating 2502^{50} combinations per class, which far exceeds the atoms in any dataset.

By assuming features are conditionally independent given class yy, Naive Bayes shrinks 2d2^d parameters down to dd simple one-dimensional statistics per class, letting models train in a single linear pass even when features outnumber samples.

Takeaway:Conditional independence reduces an exponential O(2d)O(2^d) probability table to an O(K⋅d)O(K \cdot d) linear estimate.
03 // STEP-BY-STEP MECHANISM

Step-by-Step Mechanism: Priors, Likelihoods, Posteriors

Naive Bayes trains by counting or computing column summary statistics per class:

1. Estimate Priors: Compute class proportions P(y=c)=mc/mP(y = c) = m_c / m.

2. Fit Feature Distributions: For each class cc and feature jj, store empirical word frequencies (Multinomial NB) or Gaussian mean μc,j\mu_{c,j} and standard deviation σc,j\sigma_{c,j} (Gaussian NB).

3. Multiply & Normalize in Log Space: For query x\mathbf{x}, sum ln⁡P(y=c)+∑j=1dln⁡P(xj∣y=c)\ln P(y=c) + \sum_{j=1}^d \ln P(x_j \mid y=c) and pick the highest class.

Takeaway:Training requires zero iterative optimization: just one pass to record class priors and per-feature likelihood parameters.
04 // INTERACTIVE SANDBOX

Interactive Sandbox: Gaussian Contours & Posterior Odds

Adjust the query coordinates (x1,x2)(x_1, x_2) across two class clusters modeled by axis-aligned Gaussian distributions.

Inspect the class-conditional mean ellipses, individual prior probabilities P(y)P(y), feature likelihoods P(x1∣y)⋅P(x2∣y)P(x_1 \mid y) \cdot P(x_2 \mid y), and normalized posterior probability P(y=1∣x)P(y=1 \mid \mathbf{x}) updating instantaneously.

Gaussian Naive Bayes Posterior Engine
P(y=0|x): 6.3%P(y=1|x): 93.7%
QUERY x₁185
QUERY x₂110
Feature x₁Feature x₂
Class 0 (2σ contour)
Class 1 (2σ contour)
Takeaway:Axis-aligned Gaussian Naive Bayes forms quadratic (curved) decision boundaries from class means and per-axis variances.
05 // MATHEMATICAL FORMULATION

Mathematical Formulation: Factored Bayes Rule

Summing logarithms preserves the exact argmax ranking while avoiding floating-point underflow when multiplying thousands of small probabilities (e.g. 0.011000=0.00.01^{1000} = 0.0 in IEEE-754 floats). Because the marginal evidence P(x)P(\mathbf{x}) is identical across all classes cc, argmax drops the denominator cleanly.

PRIMARY OBJECTIVE FORMULATION
Variable & Symbol Definitions
P(y=c)P(y=c)Prior probability of class cc estimated from training class frequency
P(xj∣y=c)P(x_j \mid y=c)Conditional likelihood of observing feature value xjx_j given class cc
∑j=1d\sum_{j=1}^dLog-space sum replacing raw probability products to prevent underflow
y^\hat{y}Maximum A Posteriori (MAP) class prediction maximizing posterior odds
Takeaway:Computing posteriors in log-space turns products into numerically stable sums without changing the predicted class.
06 // KEY ASSUMPTIONS

Key Assumptions: Conditional Independence

Naive Bayes makes one central structural assumption: given class label yy, features x1,…,xdx_1, \dots, x_d are statistically independent, meaning covariance matrices have zero off-diagonal entries.

Although real-world features almost always correlate (words like "machine" and "learning" appear together), classification ranking often stays surprisingly accurate even when raw probability estimates become overconfident.

Takeaway:Correlated features cause Naive Bayes to double-count evidence, skewing probability confidence while often preserving class rank.
07 // COMMON PITFALLS

Common Pitfalls: Zero-Frequency Collapse

If a rare word "cryptocurrency" never appeared in legitimate training emails, its empirical likelihood P(word∣ham)P(\text{word} \mid \text{ham}) equals exact 0.0. Multiplying by 0.0 wipes out every other piece of evidence in the email, locking posterior probability to zero regardless of other clues.

Laplace smoothing adds a pseudocount α\alpha (typically α=1.0\alpha = 1.0) to every feature count so no likelihood ever hits zero.

Algorithmic Checkpoint

In a spam classifier without Laplace smoothing, a legitimate email contains one unseen word that appeared only in spam training rows. What happens to P(ham | email)?

Takeaway:Always enable additive Laplace smoothing (alpha=1.0) in Multinomial/Bernoulli Naive Bayes and var_smoothing in Gaussian NB.
08 // COMPLEXITY

Computational Complexity: Single-Pass Linear Scaling

Training Naive Bayes scans the dataset once to accumulate per-class counts or means and variances, taking exact O(m⋅d)O(m \cdot d) time with no iterative gradient loops and O(K⋅d)O(K \cdot d) parameter memory.

Inference evaluates KK class scores across dd active features in O(K⋅d)O(K \cdot d) operations (or O(K⋅dnonzero)O(K \cdot d_{\text{nonzero}}) on sparse text vectors).

Takeaway:Naive Bayes trains in one single O(m⋅d)O(m \cdot d) pass and updates effortlessly on streaming data.
09 // REAL-WORLD USE

Real-World Use: Spam Filtering & Real-Time Text Triage

Multinomial and Complement Naive Bayes remain classic real-time baselines for email spam detection, support-ticket routing, and abusive-content triage over massive sparse vocabularies.

Because updating counts for a new labeled document only increments a handful of entries, Naive Bayes also powers online streaming classifiers that adapt continuously without full retraining.

Takeaway:Use Naive Bayes as an instant ultra-fast baseline for high-dimensional sparse text and streaming classification.
10 // PRODUCTION CODE

Production Code: Gaussian & Multinomial Naive Bayes

Implement Gaussian Naive Bayes from scratch in NumPy and train GaussianNB in scikit-learn.

Production Implementation
import numpy as np

X = np.array([[1.0, 1.2], [1.4, 0.9], [1.8, 1.5], [5.0, 5.2], [5.4, 4.9], [5.8, 5.5]])
y = np.array([0, 0, 0, 1, 1, 1])

# Fit per-class priors, means, and variances
classes = np.unique(y)
stats = {}
for c in classes:
    Xc = X[y == c]
    stats[c] = (len(Xc) / len(X), Xc.mean(axis=0), Xc.var(axis=0) + 1e-6)

def predict_log_posterior(x_q: np.ndarray):
    scores = []
    for c in classes:
        prior, mu, var = stats[c]
        log_lik = -0.5 * np.sum(np.log(2 * np.pi * var) + ((x_q - mu) ** 2) / var)
        scores.append(np.log(prior) + log_lik)
    return int(classes[np.argmax(scores)])

print("Predicted class for [2.0, 1.6]:", predict_log_posterior(np.array([2.0, 1.6])))
Implementation Walkthrough:

In NumPy, adding 1e-6 to variance prevents division by zero if a feature is constant within one class, and computing log-likelihoods sums across dimensions without underflow. Scikit-learn GaussianNB stores learned class means in .theta_, variances in .var_, and exposes normalized posteriors via .predict_proba().

Takeaway:Compute Naive Bayes posteriors in log-space and pair GaussianNB or MultinomialNB with smoothing to handle zero-variance edge cases.