4.5.1 · D3Generative Models

Worked examples — Generative vs discriminative models

3,668 words17 min readBack to topic

This page is the hands-on drill room for the parent topic. We will not re-explain the theory from scratch — but we will re-earn every symbol the moment we use it, so a reader who lands here cold can still follow.

Before any worked example, here is the one-line meaning of the two objects everything spins around:


The scenario matrix

Every generative-vs-discriminative problem you'll be asked lives in one of these cells. The rest of the page hits every cell.

# Cell (the case class) What makes it tricky Covered by
A Two-class, one feature — the baseline Getting the Bayes plumbing right Ex 1
B Sign / boundary case: Posterior collapses to the prior Ex 2
C Degenerate input: a word/feature never seen in a class () Zero kills the whole product — need smoothing Ex 3
D Missing feature at test time Generative marginalises; discriminative stalls Ex 4
E Continuous feature (Gaussian class model) Density, not probability; compare ratios Ex 5
F Limiting behaviour: prior or One class swamps the posterior Ex 6
G Discriminative side: logistic regression from the same data Same answer, different route Ex 7
H Real-world word problem (medical test) Base-rate fallacy Ex 8
I Exam twist: recover knowing only ratios Priors cancel or don't Ex 9

Figure 0 below is the map of the machine every generative example on this page runs. Read it as a flow from the two inputs on the left (features , teal; label , plum) into the orange score box, then down into normalise. It has no axes because it is a data-flow diagram, not a plot; the colour of each box tells you whether it comes from the likelihood side (teal) or the prior side (plum). Every worked example below labels its steps "score" and "normalise" to match this figure.

Figure — Generative vs discriminative models

The takeaway: every generative classifier is the same two-step machine(1) score each class with , (2) normalise so the scores sum to 1. We will name those two steps explicitly in Ex 1 and then just point back to them.


Cell A — the baseline: two classes, one feature

  1. Score each class (the "score" box of Figure 0) with . Why this step? This is the numerator of Bayes' theorem, . The score is "likelihood prior" — how much evidence votes for this class.

  2. Add the scores to get the evidence (the "normalise" box, part 1). Why this step? — the email had to come from some class, so we sum over all of them. This is the denominator.

  3. Divide to get the posterior (the "normalise" box, part 2). Why this step? Dividing by the total forces the two class-probabilities to add to — that's what makes them honest probabilities.

Verify: The other class must fill the rest: , and ✓. Sanity: "free" is 8× more likely in spam, so pushing well above the prior is right.


Cell B — the boundary: when the feature says nothing

  1. Score each class. Why this step? Same score box as Ex 1, but notice the two likelihoods are now identical ( and ) — watch what that identical factor does when we divide.

  2. Add the scores to get the evidence . Why this step? Denominator . Here every term carries the same likelihood , so is a common factor of numerator and denominator — a strong hint it will cancel.

  3. Divide to get the posterior. Why this step? The common likelihood cancels top and bottom, leaving only the prior structure.

Verify: equals the prior exactly ✓. Algebra confirms it: if , then .


Cell C — degenerate input: the zero-probability trap

  1. Write the naive-Bayes likelihood (features independent given class): Why this step? Naive Bayes multiplies each word's likelihood; that's how it combines evidence from many features.

  2. Plug in the zero. Why this matters: One zero factor annihilates the entire product. So , and — the model is infinitely certain it's not spam, on the strength of a single unseen word. That's a bug, not a feature.

  3. See where the counts come from. Why this step? Before smoothing, each word estimate is literally a fraction of counts collected from data: Concretely, imagine the spam emails contained only distinct words with counts . Then total word-slots, and "invoice" has count — that is exactly how the fatal arose.

  4. Fix with Laplace (add-one) smoothing. Why this step? We pretend every one of the vocabulary words was seen one extra time, so no estimate is ever exactly . Add to the numerator (the pretend extra sighting of this word) and add to the denominator (one pretend sighting for each of the words, so the smoothed estimates still sum to across the vocabulary): Now , and the posterior is finite and usable. In general you apply the same formula to every word and every class, not just the missing one — that keeps the whole set of estimates consistent.

Verify: Before smoothing (product with a zero) ✓; the counts give ; smoothed word estimate and after smoothing ✓.


Cell D — missing feature: generative marginalises, discriminative stalls

  1. Marginalise out the missing feature. Why this step? A generative model knows the joint , so to "forget" the unreadable we sum over every value it could have taken: Under naive independence , and (probabilities of all outcomes of add to one), so the factor cleanly disappears, leaving just .

  2. Why a discriminative model can't do this (the derivation). Why this matters: A discriminative model stores only the function . To drop honestly it would need which is a weighted average requiring the factor — a piece of the input distribution the discriminative model never learned (it only ever modelled given the inputs, never how the inputs are distributed). With unavailable, it cannot form this sum; plugging a guessed or zero value for is unprincipled. The generative model, storing , has the missing ingredient — that is the whole advantage.

  3. Score each class with the marginalised likelihood. Why this step? We are back to the ordinary score box, now feeding it from step 1 instead of a full joint.

  4. Add and divide (normalise). Why this step? Denominator forces the posteriors to sum to .

Verify: ; sum ✓. The generative model produced a clean answer using marginalisation — exactly the "handles missing features" row of the parent's comparison table.


Cell E — continuous feature: Gaussian class-conditionals

Figure 1 below plots the two class densities and the test point. Reading it: the horizontal axis is the diameter in cm; the vertical axis is the density (a height, not a probability, per the definition above). The orange curve is apples (), the teal curve is oranges (); the two dotted vertical lines mark their means and the plum dashed line marks the test point , where both curves reach the same height.

Figure — Generative vs discriminative models
  1. Use the Gaussian density for each class-conditional. Why a density, not a probability? Because is continuous (see the definition box), so we compare densities . Both are equal, so the constant will cancel in the ratio, leaving only the exponentials — this is why comparing densities is legitimate even though each single point's probability is zero.

  2. Evaluate the exponents at . Why this step? With equal the comparison reduces to the squared distance inside each exponential — whichever mean is closer wins. On Figure 1 the plum dashed line at hits both curves at the same height: Both exponents equal , so .

  3. Normalise with equal priors. Why this step? The posterior is as always; with equal priors the priors cancel too, leaving only the (equal) densities.

Verify: Both densities equal ; their ratio is ; posterior ✓. Move to and apples must win (closer to ).


Cell F — limiting behaviour: a lopsided prior

  1. Score each class with the tiny prior. Why this step? Only the prior changed from Ex 1 — same likelihoods and — so recomputing the scores isolates the effect of the prior alone.

  2. Add and divide (normalise). Why this step? Denominator ; dividing gives an honest posterior.

Verify: for ham; ✓. And it is far below the of Ex 1 — the only thing we changed was the prior, and it moved the answer the expected direction ✓.


Cell G — the discriminative route to the same answer

  1. Compute the target logit from the answer we already have. Why this step? is invertible: the log-odds . Discriminative and generative models must agree on this if they agree on the posterior.

  2. Check it against the generative log-odds. Why this step? Bayes gives (the cancels inside the ratio). Plug Ex-1 numbers:

  3. Squash back. Why this step? Applying undoes the log-odds and returns to a probability, closing the loop.

Verify: Both routes give and , matching Ex 1 ✓.


Cell H — real-world word problem: the base-rate trap

  1. Set up as generative classification — this is Bayes' theorem. Why this framing? / are the labels ; the test result is the feature . We want the posterior .

  2. Score both classes with . Why this step? Feed the score box the two priors and two likelihoods. The healthy group is enormous, so even a small false-positive rate produces more positives than the tiny sick group does — watch the numbers.

  3. Add and divide (normalise). Why this step? Denominator is the total probability of a positive test; dividing gives the honest posterior.

Verify: ; the complement ; sum ✓.


Cell I — exam twist: only likelihood ratios given

  1. Write the posterior as odds. Why this step? When only a ratio is known, work in odds — the unknown cancels:

  2. Equal priors → prior odds : Why this step? With their ratio is , so posterior odds likelihood ratio.

  3. Now shift the prior to → prior odds : Why this step? The stronger evidence () and the weaker prior () exactly cancel — the twist the examiner is testing.

Verify: Equal-prior case ✓. Skewed-prior case posterior odds ✓.


Wrap-up

Recall Did we cover every cell?

A baseline (Ex 1), boundary/uninformative feature (Ex 2), zero-probability degenerate (Ex 3), missing feature (Ex 4), continuous Gaussian (Ex 5), prior limit (Ex 6), discriminative equivalent (Ex 7), real-world base-rate (Ex 8), exam ratio twist (Ex 9). Every row of the scenario matrix is hit. ✓

Recall Quick self-test

A feature is equally likely in both classes. What does the posterior equal? ::: The prior — the feature carries no information (Cell B). A word appears zero times in a class. What breaks and what fixes it? ::: The likelihood product becomes ; Laplace/add-one smoothing fixes it (Cell C). How does a generative model handle a missing feature? ::: By marginalising (summing/integrating) it out of (Cell D). Why can't a discriminative model marginalise a missing input? ::: It never learned the input distribution needed to average over the missing value (Cell D). Why do we write not for a diameter? ::: Continuous values have zero point-probability, so we use a density (a height whose area gives probability) (Cell E). "99% accurate test, positive result" — biggest thing people forget? ::: The base rate / prior (Cell H).

Connections