Sub topic 1
Naive Bayes Classifiers: From Bayes' Theorem to Text Classification
Prerequisites
Assume you know basic probability, conditional probability, supervised classification, train/test splits, Python, and logarithms.
Conditional probability
Conditional probability measures how likely an event is when another event is known. For events \(A\) and \(B\):
\[ P(A \mid B) = \frac{P(A \cap B)}{P(B)} \]
Here, \(P(A \mid B)\) means “the probability of \(A\) given \(B\).” For classification, \(A\) might be “the message is spam,” while \(B\) is the observed message features.
Bayes' theorem
Bayes' theorem reverses a conditional probability:
\[ P(y \mid x) = \frac{P(x \mid y)P(y)}{P(x)} \]
- \(P(y)\) is the prior: how common class \(y\) is before seeing the features.
- \(P(x \mid y)\) is the likelihood: how probable the observed features \(x\) are for class \(y\).
- \(P(y \mid x)\) is the posterior: the updated probability of class \(y\).
- \(P(x)\) is evidence shared by every candidate class.
For choosing the most likely class, \(P(x)\) can be ignored because it does not change the ranking.
Classification as a generative model
A naive Bayes classifier models how each class could generate an observation. It estimates \(P(y)\) and \(P(x \mid y)\), then selects the class with the largest posterior score.
The naive assumption
Let \(x1,\ldots,xd\) be features. Naive Bayes assumes they are conditionally independent given the class:
\[ P(x \mid y) = \prod{j=1}^{d} P(xj \mid y) \]
This assumption is often false. Words in a sentence, for example, influence one another. It makes the model simple and fast, however, and its classification ranking can still work well.
The naive Bayes decision rule
Combining Bayes' theorem with the assumption gives:
\[ \hat y = \arg\maxy P(y)\prodj P(x_j \mid y) \]
In practice, calculate logarithms:
\[ \hat y = \arg\maxy \left[\log P(y) + \sumj \log P(x_j \mid y)\right] \]
Adding logs avoids numerical underflow when multiplying many small probabilities.
Estimating parameters from data
For labeled training data:
- Estimate the prior with the class frequency: \(P(y)=N_y/N\).
- Estimate each likelihood from feature counts within that class.
- Use additive, or Laplace, smoothing so an unseen feature does not create a zero score:
\[ P(xj \mid y)=\frac{\text{count}(xj,y)+\alpha}{\text{class feature count}+\alpha V} \]
Here, \(V\) is the number of possible feature values and \(\alpha>0\) controls smoothing.
Exercise
Why can one unseen feature make an unsmoothed naive Bayes class score zero?
Show answer
Its likelihood is zero, and multiplying by that likelihood makes the entire class score zero.