Unit 2.7 · about 3 h
142 / 324Naive Bayes: event models, smoothing and log-space scoring
Naive Bayes is the smallest complete probabilistic classifier: counting, smoothing and log-space scoring in one place. Its failure mode, confident scores from false independence, previews every calibration problem later.
- derive
- implement
You can now
- Derive the naive Bayes decision rule from conditional independence and count its free parameters per event model.
- Implement Bernoulli naive Bayes with Laplace smoothing and log-space scoring, handling unseen values and single-class training data.
- Select the event model (Bernoulli, multinomial, Gaussian) from the feature type and state what each independence assumption ignores.
Covers
- Bernoulli, multinomial and Gaussian naive Bayes
- Priors, smoothing, conditional independence and log-space scoring
Study, in this order
5 steps
- Naive Bayes: independence, smoothing and parameter countsTom Mitchell - Generative and Discriminative Classifiers: Naive Bayes and Logistic Regression
Sections 2.1-2.3 (conditional independence, the naive Bayes derivation, discrete inputs with the smoothed estimate (7) and Laplace at \(l = 1\), prior smoothing (9), \(n(J - 1)K\) plus \(K - 1\) free parameters) and 2.4 (Gaussian naive Bayes with \(2nK\) mean and variance parameters)
- Naive Bayes in the generative familyAn Introduction to Statistical Learning with Python
Chapter 4, Section 4.4.4 (p. 158): the naive Bayes model beside LDA and QDA
- Naive Bayes on binary MNIST pixelsDive into Deep Learning - linear models slice
Section 22.9: The Probabilistic Model for Classification, The Naive Bayes Classifier, Training on pixels binarized at 128, then Exercises 1 (XOR failure) and 2 (unseen values without smoothing)
- Event models, smoothing and estimator limitsscikit-learn - linear models, discriminant analysis and naive Bayes
Section 1.9 (MAP rule, the bad-estimator warning on
predict_proba), 1.9.1 (GaussianNB), 1.9.2 (MultinomialNBsmoothing formula, Laplace at \(\alpha = 1\) versus Lidstone below 1) and 1.9.4 (BernoulliNBdecision rule, explicit penalty on non-occurrence,binarizebehavior) - Gaussian naive Bayes lab on SmarketAn Introduction to Statistical Learning with Python
Naive Bayes section:
GaussianNBfit on Smarket withclasses_andclass_prior_readouts
Focus on
- Smoothing is a MAP estimate under a Dirichlet prior, not a hack. Mitchell's \((\text{count} + l)/(\text{total} + lJ)\) at \(l = 1\) is Laplace, and
BernoulliNB's \(\alpha = 1.0\) is the same add-one per value; without it one unseen value zeroes the whole product. - Bernoulli penalizes absent indicator features while multinomial ignores absent counts. That is why occurrence vectors can beat count vectors on short documents, and why the two models are not interchangeable.
- Score in log space always. A product of 1100 halves is exactly 0.0 in
float64while the log sum stays finite at -762.46; \(\operatorname{argmax}\) needs only the sums.
Reproduce closed-book
X = [[1,0],[1,1],[0,0],[0,1]] with y = [1,1,0,0] match sklearn feature_log_prob_ rows [-1.3863, -0.6931] for class 0 and [-0.2877, -0.6931] for class 1, predict [1] for [[1,0]], and return the majority class when trained on one class only.Traps
- Feeding counts to
BernoulliNBor magnitudes to a binary model without thought.BernoulliNBbinarizes continuous input atbinarize = 0.0by default, silently turning magnitudes into presence flags. - Multiplying raw probabilities and comparing. Beyond underflow, one unsmoothed zero vetoes the class; sum logs and smooth first.
- Reading
predict_probaas calibrated confidence. The guide calls naive Bayes a bad estimator: use the scores to rank, then threshold or calibrate downstream.
Practice
Deep-ML 140: Bernoulli Naive Bayes Classifier
NaiveBayes class with forward (Laplace smoothing at 1.0) and predict in log space; tests check a 5-row fit and a symmetric single-feature case, and the spec requires single-class training data to work
Match sklearn BernoulliNB on the same inputs before submitting.
ISLP Lab 4.7.5: Naive Bayes on the Smarket data
Naive Bayes section: GaussianNB fit with classes_ and class_prior_ readouts beside the LDA and QDA fits
Compare its confusion matrix with the LDA one and attribute the differences to the diagonal-covariance assumption.
Self-test
-
A test word never appeared in training. What happens with and without smoothing?
Without smoothing its likelihood is 0 and the whole class product is 0 regardless of other evidence. With Laplace \(\alpha = 1\) it contributes a small nonzero factor that rarely decides the \(\operatorname{argmax}\) alone. -
When does Bernoulli beat multinomial on text, and why?
With occurrence vectors on short documents: Bernoulli explicitly penalizes the non-occurrence of indicator words while multinomial ignores absent counts. sklearn advises evaluating both when time permits. -
Write the smoothed discrete likelihood and name its prior.
\((\text{count} + l)/(\text{class total} + lJ)\): the MAP estimate under a symmetric Dirichlet prior with parameters \(l + 1\), equivalently the posterior mean under parameters \(l\); \(l = 1\) is Laplace. Priors smooth the same way with \(lK\) in the denominator. -
XOR data with labels [0,1,1,0]. Does naive Bayes succeed, and which assumption fails?
No. Each feature alone is uninformative about the label, so conditional independence destroys the interaction. Allowing explicit dependence between the inputs fixes it.
Completion criterion
Stop when
Your Bernoulli implementation matches sklearn feature_log_prob_ to 1e-8, survives unseen values and single-class fits, and you can choose the event model from the feature type alone.
Leads to
- 2.8 Probability estimates, class priors and asymmetric thresholds Correct the overconfident scores before thresholding them.
- 5.3 ROC AUC, average precision, log loss and Brier score Score the outputs with log loss and Brier rather than accuracy.
Comes after
- 3.1 Probability axioms and random variablesClass-conditional probabilities need a clean sample space first.
- 3.2 Joint, marginal and conditional distributions, and independenceNaive Bayes is this unit's conditional-independence assumption applied to features.
- 4.2 Maximum likelihood and MAP estimationApply count likelihoods and distinguish smoothing conventions.
- 2.6 LDA, QDA and generative versus discriminative classifiersShrink the Gaussian assumption to diagonal covariance and smoothed counts.
Resources for this unit
- An Introduction to Statistical Learning with Python Use Chapters 3, 4 and 6 with their Python labs as the first pass: least squares and its diagnostics, logistic regression, LDA, QDA and naive Bayes, basis expansion and regularization paths.
- Dive into Deep Learning - linear models slice Use 3.1, 3.4, 3.6, 3.7, 4.1, 4.4, 22.7 and 22.9 for linear regression, generalization, weight decay, softmax, maximum likelihood and naive Bayes. Implement with NumPy first and use the PyTorch versions only as a differential reference.
- scikit-learn - linear models, discriminant analysis and naive Bayes Use the official Linear Models, LDA and QDA, and Naive Bayes guides to verify estimator semantics and selected edge cases after the independent implementation works.
- Tom Mitchell - Generative and Discriminative Classifiers: Naive Bayes and Logistic Regression Read Sections 2 (naive Bayes, the smoothed estimates (7) and (9), parameter counts), 3 (Gaussian naive Bayes implies the logistic form, gradient ascent, the \(L_2\) penalty, the \(K\)-class rules) and 4 (generative versus discriminative, Ng and Jordan rates). This is the CS446 reading for Lectures 6-8; rework each derivation on a hand-sized dataset.
Also in this section
- Hands-On Machine Learning with Scikit-Learn and PyTorch - classification and linear models Read the Chapter 3 and 4 sections each unit names, then run notebooks 03 and 04 for classification diagnostics, linear and polynomial regression, regularization and logistic regression. Recreate the target mechanism independently before inspecting worked exercise code.
- NeetCode ML - linear-model closing drill After the section gate, solve Gradient Descent, Sigmoid and ReLU, Softmax, Cross-Entropy Loss, Linear Regression Forward and Linear Regression Training cold. Repeat only failed items from a blank file with changed values.
- Deep-ML - linear and probabilistic model problems Use 15 Linear Regression Using Gradient Descent, 106 Train Logistic Regression with Gradient Descent and 140 Bernoulli Naive Bayes Classifier as unit checks after the local implementation passes. Their tests were read in review; each card states what they pin. The local implementation remains the evidence.