Sub topic 3
Classification as modeling P(x | y) and P(y)
This chapter assumes you know joint and conditional probability, have seen Bayes' theorem, and can read short Python. It covers the change in viewpoint behind naive Bayes. You stop asking "what class is this example?" directly. Instead you model how each class produces examples, then reverse that model.
Two ways to build a classifier
A classifier's goal is the posterior, P(y | x): the probability of class y given the feature vector x. There are two ways to get it.
- Discriminative models learn P(y | x) directly. Logistic regression, decision trees, and neural networks with a softmax output belong here. They learn a boundary or a mapping from x to y and make no claim about how x is distributed.
- Generative models learn two simpler pieces and combine them with Bayes' theorem:
- P(y), the class prior: how common each class is.
- P(x | y), the class-conditional likelihood: what examples of class y look like.
Bayes' theorem combines the pieces:
P(y | x) = P(x | y) * P(y) / P(x)The name "generative" comes from the story the model tells. Nature first picks a class from P(y). It then produces features by sampling from P(x | y). Classification runs that story backwards. You observe x and ask which class most plausibly produced it.
The decision rule needs no evidence term
The denominator P(x) is the probability of seeing these features at all, summed over every class:
P(x) = sum over y' of P(x | y') * P(y')It is the same number for every candidate class. To pick the most probable class, you can drop it:
y_hat = argmax over y of P(x | y) * P(y)This shortcut explains why generative classifiers are cheap at prediction time. It also has a cost. The product P(x | y) * P(y) is an unnormalized score, not a probability. If you need real posteriors, you must divide by the sum of scores across classes. Skipping that step is a common bug when people print "probabilities" from a hand-written model.
A worked example with full joint counts
Start with the most direct version of the generative approach: count how often each exact feature combination appears in each class. The data below has two binary features, such as "contains the word free" and "contains the word now".
from collections import Counter
data = [
((1, 1), "spam"),
((1, 0), "spam"),
((1, 1), "spam"),
((0, 0), "ham"),
((0, 1), "ham"),
((0, 0), "ham"),
((1, 0), "ham"),
((0, 0), "ham"),
]
class_counts = Counter(y for _, y in data)
joint_counts = Counter(data) # counts of (x, y) pairs
n = len(data)
def prior(y):
return class_counts[y] / n
def likelihood(x, y):
return joint_counts[(x, y)] / class_counts[y]
def posterior(x):
scores = {y: likelihood(x, y) * prior(y) for y in class_counts}
evidence = sum(scores.values()) # this is P(x)
return {y: s / evidence for y, s in scores.items()}
print(posterior((1, 1)))
print(posterior((1, 0)))The output is:
{'spam': 1.0, 'ham': 0.0}
{'spam': 0.5, 'ham': 0.5}Read the first result through the two pieces. Eight examples give P(spam) = 3/8 and P(ham) = 5/8. Among spam, the pattern (1, 1) appears in 2 of 3 examples, so P(x | spam) = 2/3. Among ham, it never appears, so P(x | ham) = 0. The ham score is 0 and spam wins with probability 1.0.
That certainty is not warranted. It comes from a pattern that is merely absent from five ham examples. The second result shows the opposite case. The pattern (1, 0) gives scores of 1/3 × 3/8 and 1/5 × 5/8. Both equal 0.125, so the model reports an exact tie.
Why full joint counting does not scale
The example above works only because there are two features. A full table for P(x | y) needs one entry for every possible feature combination in every class. With d binary features, that is 2^d − 1 free parameters per class, because the entries for one class must sum to 1.
| Binary features (d) | Free parameters per class |
|---|---|
| 2 | 3 |
| 10 | 1,023 |
| 20 | 1,048,575 |
| 30 | 1,073,741,823 |
A text classifier easily has 10,000 vocabulary features. No dataset covers a table of 2^10000 cells, so most combinations would never be seen in training. Their estimated likelihood would be 0, as in the example above, and the model would generalize badly.
This is the problem the next chapters solve. The generative view is sound, but P(x | y) is too large to estimate without structure. Naive Bayes adds a structural assumption that shrinks the table from exponential size to one entry per feature per class.
What the generative view gives you
Modeling how each class generates data has practical consequences, some good and some bad.
- Training is counting. Priors and likelihoods come from frequencies, so there is no iterative optimization. Adding new data means updating counts.
- Missing features are easy to handle. If a feature is unobserved, you can leave its likelihood term out of the score. Discriminative models usually need imputation.
- Small datasets suit it. A model with few parameters can be estimated from little data. Ng and Jordan's well-known comparison found that generative classifiers can reach their (higher) error floor faster than logistic regression, while logistic regression wins given enough data.
- You can sample from it. Because you model P(x | y), you can generate synthetic examples. That is rarely the goal, but it is a useful sanity check on whether the model resembles your data.
- It spends effort on modeling x. A discriminative model only needs the boundary between classes. A generative model must also describe the shape of each class. If that description is wrong, classification can suffer even when the boundary would have been easy to learn.
Common errors
- Confusing P(x | y) with P(y | x). The likelihood answers "how likely are these features if the class is spam?" The posterior answers "how likely is spam given these features?" A word that is very common in spam, such as "the", can still say little about spam, because it is just as common in ham.
- Ignoring the prior. With a rare class, a high likelihood can still lose to a large prior. Dropping P(y) turns the rule into a maximum-likelihood classifier, which is correct only when the classes are equally common.
- Estimating priors from a resampled training set. If you balance classes by oversampling or undersampling, the counted priors reflect the balanced set, not production traffic. Either set the priors by hand to the real class frequencies or accept that the decision threshold has shifted.
- Treating the unnormalized score as a probability. The score P(x | y) P(y) is only proportional to the posterior. Normalize across classes before reporting it.
- Treating densities as probabilities. For continuous features, P(x | y) is a density, which can exceed 1. This is fine for comparing classes, but the value is not a probability.
- Trusting a zero. A single unseen feature value makes a whole class score 0, as the first output showed. The remedy, smoothing, appears in a later chapter.
Exercise
A training set has 90 non-fraud and 10 fraud transactions. For one new transaction, a model estimates P(x | fraud) = 0.02 and P(x | non-fraud) = 0.005. Compute the posterior probability of fraud, and say which class the rule picks.
Show answer
Unnormalized scores: fraud = 0.02 × 0.10 = 0.002. Non-fraud = 0.005 × 0.90 = 0.0045. The evidence is 0.002 + 0.0045 = 0.0065. Posterior for fraud = 0.002 / 0.0065 ≈ 0.31, and for non-fraud ≈ 0.69. The rule picks non-fraud, even though the likelihood ratio favors fraud 4 to 1. The prior is 9 to 1 against fraud.
Exercise
A classifier uses 15 binary features and models P(x | y) as a full joint table for 3 classes. How many free parameters does it need for the likelihoods, and how many for the priors?
Show answer
Each class needs 2^15 − 1 = 32,767 free parameters, so the likelihoods need 3 × 32,767 = 98,301. The priors need 3 − 1 = 2 free parameters, because the three values must sum to 1.