All lessons in Machine Learning Engineering: Reliable Predictive Models
Naive Bayes and Conditional Independence
Compute posterior odds and test the independence approximation.
25 minutes · Free lesson
What you will learn
- Convert class counts into prior odds, per-feature likelihood ratios, and a posterior probability for a single dispatch row.
- Apply additive smoothing to a zero count and explain why an unsmoothed zero destroys all other evidence.
- Test the conditional independence approximation with joint counts and quantify how much a correlated feature pair inflates the posterior odds.
Naive Bayes is the smallest probabilistic classifier worth knowing well. It models each class by the frequencies of feature values inside that class, then multiplies those frequencies together as if the features were unrelated once the class is known. The parcel carrier case makes the assumption easy to inspect: at dispatch we know whether the weather risk is high, whether it is a weekend, and whether the van is heavily loaded, and we want the probability that a parcel arrives late. Everything in this lesson is hand-computable from a small count table, which is the point. You will see exactly where the model gets its confidence and exactly where that confidence is unearned.
This lesson is optional, so it recaps the probability it needs. If you have already worked through the logistic regression and calibration lessons, the additive log-odds form will look familiar; if not, nothing here depends on them.
From Bayes' rule to odds
Bayes' rule says the posterior probability of a class given the observed features is proportional to the prior probability of the class times the likelihood of the features under that class. For two classes, late and on time, it is cleaner to work with odds. The posterior odds of late are the posterior probability of late divided by the posterior probability of on time. Because the normalising constant is the same for both classes, it cancels, and the posterior odds equal the prior odds multiplied by the likelihood ratio: the probability of the features given late divided by the probability of the features given on time.
Under that assumption the likelihood of the whole feature vector factorises into a product of per-feature likelihoods, so the posterior odds become the prior odds times one likelihood ratio per feature. Each likelihood ratio is the frequency of that feature value among late parcels divided by its frequency among on-time parcels. Taking logarithms turns the product into a sum, which is why naive Bayes is numerically stable when you implement it with log probabilities and why its decision boundary is linear in the log-likelihood terms, much like logistic regression but with coefficients estimated by counting rather than by optimisation.
The posterior probability recovers from odds as odds divided by one plus odds.
Estimating the pieces from counts
Suppose the carrier's training set holds 1,000 parcels, 200 late and 800 on time. For binary features the per-class frequencies are just counts divided by the class size. The table below is the fixture used throughout this lesson.
| Feature value | Count among 200 late | Count among 800 on time |
|---|---|---|
| high weather risk | 120 | 160 |
| weekend | 80 | 240 |
| heavy load | 150 | 200 |
The complementary counts follow by subtraction: low weather risk is 80 late and 640 on time, weekday is 120 late and 560 on time, light load is 50 late and 600 on time.
Worked example
Posterior odds for a high-risk weekend parcel on a heavy van
- Prior odds of late equal 200 divided by 800, which is 0.25.
- Likelihood ratio for high weather risk: among late, 120 of 200 gives 0.6; among on time, 160 of 800 gives 0.2; ratio 0.6 divided by 0.2 equals 3.0.
- Likelihood ratio for weekend: 80 of 200 gives 0.4; 240 of 800 gives 0.3; ratio 0.4 divided by 0.3 equals 1.3333.
- Likelihood ratio for heavy load: 150 of 200 gives 0.75; 200 of 800 gives 0.25; ratio equals 3.0.
- Posterior odds equal 0.25 × 3.0 × 1.3333 × 3.0. Step by step: 0.25 × 3.0 is 0.75; 0.75 × 1.3333 is 1.0; 1.0 × 3.0 is 3.0.
- Posterior probability of late equals 3.0 divided by 4.0, which is 0.75.
- Interpretation: the model has moved from a 20 percent base rate to 75 percent on this row. Whether that 75 percent deserves to be believed depends on whether the three features are really conditionally independent, which the next section tests.
Smoothing zero counts
A count of zero in one class makes that class's likelihood zero for any row with that value, and a zero factor wipes out every other piece of evidence. Additive smoothing, often called Laplace smoothing when the added amount is one, adds a small constant to every count and adds the constant times the number of categories to the denominator. With smoothing amount alpha and k categories, the smoothed frequency is the count plus alpha, divided by the class size plus alpha times k. The effect is largest on rare values and vanishes as counts grow. In practice alpha is a tuning knob you choose on validation data, not a fixed truth.
Continuous features such as the raw dispatch load need a different likelihood. Gaussian naive Bayes models each feature inside each class by a normal distribution with its own class-specific mean and variance; the likelihood ratio is then the ratio of two normal densities evaluated at the observed value. The independence assumption is unchanged, only the per-feature likelihood changes. Binning a continuous feature into a few categories and using counts is a legitimate alternative when the normal shape is clearly wrong.
Testing the independence approximation
The assumption is checkable. Inside each class, compare the observed joint count of two feature values with the count predicted by multiplying the two marginal frequencies. A gap can reflect dependence or finite-sample variation. Repeated or sufficiently strong discrepancies motivate investigating the approximation; a single empirical table is not proof of population dependence. The probability distortion can have different directions in different cells.
Worked example
Joint counts for high weather risk and heavy load
- Among the 200 late parcels, suppose 110 have both high weather risk and a heavy load. Under independence the expected joint count is 0.6 × 0.75 × 200, which is 90. The observed 110 exceeds 90.
- Among the 800 on-time parcels, suppose 100 have both. Under independence the expected count is 0.2 × 0.25 × 800, which is 40. The observed 100 is far above 40.
- The joint likelihood ratio for the pair is the joint frequency among late, 110 of 200 or 0.55, divided by the joint frequency among on time, 100 of 800 or 0.125. That is 0.55 divided by 0.125, which equals 4.4.
- Naive Bayes instead multiplies the two separate ratios, 3.0 × 3.0, which equals 9.0, roughly double the joint-frequency estimate for this pair.
- Recompute the posterior odds for the row in the first example using the joint ratio, still assuming weekend is independent of the pair within each class: 0.25 × 4.4 × 1.3333. Step by step: 0.25 × 4.4 is 1.1; 1.1 × 1.3333 is 1.4667.
- Posterior probability equals 1.4667 divided by 2.4667, which is 0.5946, about 0.59.
- Interpretation: the naive model said 0.75; a model that respects the dependence says about 0.59. The ranking of parcels may be barely affected, but the probability scale is pushed toward the extremes, which matters for cost-based thresholds and for log loss. This is a count fixture, not a measurement from the workbook.
This inflation is exactly what happens when a signal feature and a noisy proxy of it both enter the model, which is why the workbook's synthetic dispatch_load and load_proxy pair is a natural place to look. Options when you find dependence include dropping one feature of the pair, merging a pair into a single joint categorical feature so its likelihood is estimated directly, or accepting the inflated scale but recalibrating the output on held-out predictions, as described in the calibration lesson.
Exercises
Exercise
Using the count table from this lesson (200 late, 800 on time; high weather 120 late and 160 on time; weekend 80 late and 240 on time; heavy load 150 late and 200 on time), compute the naive Bayes posterior probability of late for a parcel with low weather risk, dispatched on a weekday, on a heavy van. No smoothing.
Check your answer
Prior odds are 200 divided by 800, which is 0.25. Low weather risk: 80 of 200 is 0.4 among late, 640 of 800 is 0.8 among on time, ratio 0.5. Weekday: 120 of 200 is 0.6 among late, 560 of 800 is 0.7 among on time, ratio 0.857143. Heavy load ratio is 3.0 as before. Posterior odds are 0.25 × 0.5 × 0.857143 × 3.0. Compute 0.25 × 0.5 equals 0.125; 0.125 × 3.0 equals 0.375; 0.375 × 0.857143 equals 0.321429. Posterior probability equals 0.321429 divided by 1.321429, which is 0.2432, about 0.24. The heavy load pushes the parcel above the 0.20 base rate, but the low weather risk and weekday pull most of that back.
Exercise
In this separate hand fixture, a five-valued categorical feature called category_code is added; it is not the workbook’s continuous noise_code. Code E appears 0 times among the 200 late parcels and 40 times among the 800 on-time parcels. Compute the likelihood ratio for code E without smoothing and with additive smoothing using alpha equal to 1, and state what each does to the posterior odds of a row carrying code E.
Check your answer
Without smoothing the frequency among late is 0 of 200, so the likelihood ratio is 0 and the posterior odds become 0 regardless of weather, weekend, or load; the model declares the parcel certainly on time on the strength of one absent count. With alpha equal to 1 and 5 categories, the smoothed frequency among late is (0 + 1) divided by (200 + 5), which is 1 divided by 205, or 0.004878. Among on time it is (40 + 1) divided by (800 + 5), which is 41 divided by 805, or 0.050932. The ratio is 0.004878 divided by 0.050932, which equals 0.0958, equivalently 805 divided by 8405. The smoothed ratio still cuts the posterior odds by a factor of about ten, a strong but finite adjustment that other evidence can still outweigh.
Exercise
Split the weather and load pair into one four-valued feature. Among late parcels the counts are: both high risk and heavy 110, high risk only 10, heavy only 40, neither 40. Among on-time parcels: both 100, high risk only 60, heavy only 100, neither 540. For the value heavy only (low weather risk and heavy load), compute the joint likelihood ratio and compare it with what naive Bayes would multiply together from the two separate features. Do the same for high risk only. Which of the two naive products is more distorted?
Check your answer
First confirm the counts sum correctly: 110 + 10 + 40 + 40 equals 200 and 100 + 60 + 100 + 540 equals 800, and the marginals match the earlier table. Heavy only: joint frequency among late is 40 of 200, or 0.2; among on time 100 of 800, or 0.125; joint ratio 0.2 divided by 0.125 equals 1.6. The naive product is the low-risk ratio 0.5 times the heavy ratio 3.0, which equals 1.5. The gap is small. High risk only: joint frequency among late is 10 of 200, or 0.05; among on time 60 of 800, or 0.075; joint ratio 0.6667. The naive product is the high-risk ratio 3.0 times the light-load ratio, which is 50 of 200 or 0.25 among late divided by 600 of 800 or 0.75 among on time, giving 0.3333; the product is 3.0 × 0.3333, which equals 1.0. Naive Bayes says this combination is neutral while the joint counts say it lowers the odds by a third. The high risk only cell is more distorted, in relative terms a factor of 1.5, versus about 1.07 for heavy only. The dependence does not distort every cell equally, so checking only one combination can be misleading.
Two mistakes that recur
The first is treating naive Bayes outputs as calibrated probabilities. Even when its ranking is good, the double counting shown above pushes probabilities toward 0 and 1. Measure calibration on held-out predictions before using the scores in a cost-based threshold, and fit any calibrator on out-of-sample predictions, never on the rows the classifier was trained on.
The second is multiplying raw probabilities in code. With dozens of features the product underflows to zero and every row looks identical. Sum log likelihoods instead, and convert back to a probability only at the end.
Practical investigation
Download the Machine learning investigation workbook, unzip it, create a Python 3.12 environment, install requirements.txt, then run python ml_workbook.py --development-only --output results and python -m unittest discover -s tests -v. The workbook's models are dummy, logistic, forest, and boosting, selected by validation log loss; naive Bayes is not among them, so this is a learner extension. Inspect the source to find where models are fitted on the training split and scored on the validation split, add a naive Bayes variant of your choice alongside them, and compare its validation log loss and a reliability plot with the logistic model. Then test the independence assumption directly on synthetic-parcels.csv: within each outcome class, tabulate dispatch_load binned into a few ranges against load_proxy binned the same way, and compare observed joint counts with the product of marginals. Refit naive Bayes with only one of the pair and record how the validation log loss and the spread of predicted probabilities change. Keep the sealed final split untouched; this is a development-stage comparison, and the workbook's rows are iid synthetic data, not a validation of any real carrier.
Further reading
scikit-learn naive Bayes guide — compare the multinomial, Bernoulli, categorical, and Gaussian variants and note the smoothing parameter for each.
scikit-learn probability calibration guide — see why naive Bayes is a standard example of a classifier whose scores need recalibration.
Probabilistic Machine Learning: An Introduction — the generative classifier chapters give the derivation behind the likelihood-ratio form used here.
Summary
Naive Bayes turns class counts into a prior odds times one likelihood ratio per feature, which becomes an additive log-odds model. Zero counts need additive smoothing or they veto all other evidence. Joint-count comparisons can reveal evidence against conditional independence, although pairwise checks do not establish full mutual independence. A signal and its proxy can cause double counting and distort the probability scale. The fix is to drop or merge dependent features, or to recalibrate on held-out predictions, and in every case to judge the result by validation log loss and a reliability check rather than by the model's own confidence.
Next action
Within each outcome class of the training rows in synthetic-parcels.csv, build the binned joint table for dispatch_load against load_proxy, compute the ratio of observed to expected counts for the most populated cell, and write one sentence predicting how much that dependence will distort a naive Bayes posterior before you fit the model.