7 routes42 sections324 units

Unit 2.7 · about 3 h

142 / 324

Naive 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

  1. Naive Bayes: independence, smoothing and parameter counts
    Tom 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)

  2. Naive Bayes in the generative family
    An Introduction to Statistical Learning with Python

    Chapter 4, Section 4.4.4 (p. 158): the naive Bayes model beside LDA and QDA

  3. Naive Bayes on binary MNIST pixels
    Dive 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)

  4. Event models, smoothing and estimator limits
    scikit-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 (MultinomialNB smoothing formula, Laplace at \(\alpha = 1\) versus Lidstone below 1) and 1.9.4 (BernoulliNB decision rule, explicit penalty on non-occurrence, binarize behavior)

  5. Gaussian naive Bayes lab on Smarket
    An Introduction to Statistical Learning with Python

    Naive Bayes section: GaussianNB fit on Smarket with classes_ and class_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 float64 while the log sum stays finite at -762.46; \(\operatorname{argmax}\) needs only the sums.

Reproduce closed-book

Derive the MAP rule \(\operatorname{argmax}_y P(y)\prod_i P(x_i \mid y)\) from conditional independence. From a blank file implement Bernoulli naive Bayes with \(\alpha = 1.0\): on 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 BernoulliNB or magnitudes to a binary model without thought. BernoulliNB binarizes continuous input at binarize = 0.0 by 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_proba as 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

  1. A test word never appeared in training. What happens with and without smoothing?

  2. When does Bernoulli beat multinomial on text, and why?

  3. Write the smoothed discrete likelihood and name its prior.

  4. XOR data with labels [0,1,1,0]. Does naive Bayes succeed, and which assumption fails?

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.

Mark passed, then open 2.8 Only mark this when you can do it without notes.

Leads to

Comes after

Resources for this unit

  • An Introduction to Statistical Learning with Python
    James, Witten, Hastie, Tibshirani and Taylorprimarytheory
    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
    D2L authorsrequiredimplementation
    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
    scikit-learnreferencereference
    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
    Tom Mitchell, Carnegie Mellon Universityrequiredtheory
    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
    Aurelien Geron (O'Reilly, 2025)supportimplementation
    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
    NeetCodesupportpractice
    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
    Deep-MLsupportpractice
    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.

Quick find

Search Michi

Type to search every route, section, unit, topic and resource.

Enter opens the first result Esc closes

Reference

Keyboard shortcuts

n
Continue to the first unit not passed
j / k
Next / previous unit
1 2 3
Toggle learned, practised, passed
/
Open search
?
Show this help
Esc
Close open panels