MoonSay /Tutorials/Machine Learning Interview #6
Contents
  1. 01Introduction
  2. 02Two ways to learn
  3. 03Bayes’ theorem
  4. 04What generative models create
  5. 05What discriminative models do
  6. 06Who wins? Small data versus big data
  7. 07Beyond accuracy
  8. 08Side by side
  9. 09Interview questions and model answers
  10. 10Summary
  11. References

03Bayes’ theorem: how a generative model classifies

3.1Bayes’ theorem as a classifier

A generative model knows p(y) and p(x\mid y). Bayes’ theorem turns them into the posterior:

p(y=c\mid x)=\frac{p(x\mid y=c)\,p(y=c)}{p(x)},\qquad p(x)=\sum_{c'}p(x\mid y=c')\,p(y=c'). \tag{2}

The numerator scores each class by how well it explains x (the likelihood) times how common it is (the prior); the denominator, the evidence, only makes the scores sum to one. To pick the most probable class we can ignore it: \hat y(x)=\arg\max_c\,p(x\mid y=c)\,p(y=c).

Worked example 1 (A photo: cat or dog?). The cat model says a given photo is fairly typical of cats, p(x\mid\text{cat})=0.30; the dog model finds it unusual, p(x\mid\text{dog})=0.05. With equal priors, the joint scores are 0.30\times0.5=0.15 and 0.05\times0.5=0.025, the evidence is 0.175, and

p(\text{cat}\mid x)=\frac{0.15}{0.175}=0.857.

Table 1 lays out the steps. If the photo comes from a site where only 20\% of the photos are cats, the priors change and p(\text{cat}\mid x)=0.06/(0.06+0.04)=0.60: the same evidence, a less certain conclusion.

Prior p(y)Likelihood p(x\mid y)Prior \times likelihoodPosterior p(y\mid x)
Cat0.50.300.1500.857
Dog0.50.050.0250.143
Sum (the evidence p(x))0.1751
Table 1. Bayes’ theorem as a classifier, for Example 1 (illustrative numbers, as in the companion video).
Try itBayes' theorem as a classifier

Set how well each class model explains the photo, p(x\mid\text{cat}) and p(x\mid\text{dog}), and how common cats are. The bars show the prior, prior \times likelihood, and the posterior p(\text{cat}\mid x)=p(x\mid\text{cat})\,p(\text{cat})/p(x), equation (2).

For two classes it is convenient to work with the log-odds. Dividing (2) for y=1 by the same expression for y=0, the evidence cancels:

a(x)=\log\frac{p(y=1\mid x)}{p(y=0\mid x)}=\underbrace{\log\frac{p(x\mid y=1)}{p(x\mid y=0)}}_{\text{evidence from }x}+\underbrace{\log\frac{\pi_1}{\pi_0}}_{\text{prior odds}}. \tag{3}

Solving for the posterior, with p(y=0\mid x)=1-p(y=1\mid x), gives

p(y=1\mid x)=\frac{1}{1+e^{-a(x)}}=\sigma\big(a(x)\big). \tag{4}

So every two-class posterior is the logistic function of the log-odds; the question is only what a(x) looks like. In the example, a=\log 6+0=1.79 and \sigma(1.79)=0.857.

3.2Gaussian discriminant analysis

The most classic generative classifier models each class by a Gaussian, p(x\mid y=c)=\mathcal N(x\mid\mu_c,\Sigma_c) (Murphy, 2022, §9.2).

Fitting. The log-likelihood of the labelled data splits into a part for the priors and one part per class,

\log p(D\mid\theta)=\sum_{n}\log\pi_{y_n}+\sum_c\sum_{n:\,y_n=c}\log\mathcal N(x_n\mid\mu_c,\Sigma_c),

so each piece is maximized separately, and the maximum likelihood estimates are counts and averages:

\hat\pi_c=\frac{N_c}{N},\qquad \hat\mu_c=\frac1{N_c}\sum_{n:\,y_n=c}x_n,\qquad \hat\Sigma_c=\frac1{N_c}\sum_{n:\,y_n=c}(x_n-\hat\mu_c)(x_n-\hat\mu_c)^\top, \tag{5}

where N_c is the number of examples of class c. No iterative optimization is needed: the painter learns each class on its own.

Shared covariance gives a linear boundary. Suppose all classes share one covariance, \Sigma_c=\Sigma (estimated by pooling all classes). Then the log-odds (3) of two classes is

\begin{aligned} a(x)&=-\tfrac12(x-\mu_1)^\top\Sigma^{-1}(x-\mu_1)+\tfrac12(x-\mu_0)^\top\Sigma^{-1}(x-\mu_0)+\log\frac{\pi_1}{\pi_0}\\ &=-\tfrac12x^\top\Sigma^{-1}x+\mu_1^\top\Sigma^{-1}x-\tfrac12\mu_1^\top\Sigma^{-1}\mu_1+\tfrac12x^\top\Sigma^{-1}x-\mu_0^\top\Sigma^{-1}x+\tfrac12\mu_0^\top\Sigma^{-1}\mu_0+\log\frac{\pi_1}{\pi_0}, \end{aligned}

where the normalizing constants (2\pi)^{-D/2}|\Sigma|^{-1/2} cancelled because they are the same for both classes. The quadratic terms \mp\frac12x^\top\Sigma^{-1}x cancel too, and what remains is linear in x:

p(y=1\mid x)=\sigma\!\left(w^\top x+b\right),\quad w=\Sigma^{-1}(\mu_1-\mu_0),\quad b=-\tfrac12\mu_1^\top\Sigma^{-1}\mu_1+\tfrac12\mu_0^\top\Sigma^{-1}\mu_0+\log\frac{\pi_1}{\pi_0}. \tag{6}

This is linear discriminant analysis (LDA), and (6) has exactly the form of logistic regression (Bishop, 2006, §4.2.1), (Murphy, 2022, §9.2.3). The prior only enters b: it shifts the boundary but does not turn it. If the covariances differ, the quadratic terms no longer cancel, the boundary is quadratic, and the method is called quadratic discriminant analysis (QDA).

Gaussian discriminant analysis in one dimension. (a) Equal variances: the posterior is exactly logistic, \sigma(2.5x-0.625), with the boundary at x=0.25; with the prior \pi_1=0.2 it moves to x=0.81. (b) Unequal variances: the wider class wins on both sides, and there are two boundaries (x=-1.09 and x=0.89). Computed for this tutorial.
Figure 3. Gaussian discriminant analysis in one dimension. (a) Equal variances: the posterior is exactly logistic, \sigma(2.5x-0.625), with the boundary at x=0.25; with the prior \pi_1=0.2 it moves to x=0.81. (b) Unequal variances: the wider class wins on both sides, and there are two boundaries (x=-1.09 and x=0.89). Computed for this tutorial.
Try itWhen is the posterior logistic?

Two Gaussian classes, p(x\mid y=c)=\mathcal N(\mu_c,\sigma_c^2), with prior \pi_1. With equal variances the posterior is exactly \sigma(wx+b) with w=(\mu_1-\mu_0)/\sigma^2, equation (6); with unequal variances the boundary is quadratic. Move the sliders and watch the dark curve.

Worked example 2 (One feature, equal variances). Let p(x\mid y=0)=\mathcal N(-1,1) and p(x\mid y=1)=\mathcal N(1.5,1) with equal priors. In one dimension (6) reads w=(\mu_1-\mu_0)/\sigma^2=2.5 and b=-(\mu_1^2-\mu_0^2)/(2\sigma^2)=-(2.25-1)/2=-0.625, so p(y=1\mid x)=\sigma(2.5x-0.625), Figure 3(a). The boundary, 2.5x-0.625=0, is x=0.25, halfway between the means. With \pi_1=0.2, b gains \log(0.2/0.8)=-1.386 and the boundary moves to x=(0.625+1.386)/2.5=0.805, towards the rarer class: we now need stronger evidence to say “class 1”.

Worked example 3 (The cats and dogs, by linear discriminant analysis). For the 13 cats and 13 dogs of Figure 1, (5) gives \hat\mu_{\text{cat}}=(0.276,0.695), \hat\mu_{\text{dog}}=(0.679,0.323) and the pooled covariance \hat\Sigma=\left(\begin{smallmatrix}0.0096&0.0010\\0.0010&0.0106\end{smallmatrix}\right). Equation (6) with cat as class 1 gives w=(-46.37,\,39.50) and b=2.02: a long snout counts against “cat”, pointy ears for it. Logistic regression fitted directly (with a mild penalty on \|w\|^2, Section 5) gives w=(-5.60,\,5.08), b=0.02. The two weight vectors point in almost the same direction (the cosine of the angle between them is 0.999), so the boundaries nearly coincide, but their lengths differ, and so does the confidence: at the new photo x=(0.16,0.30), LDA says p(\text{cat}\mid x)=0.998 and the penalized logistic regression 0.66. Same form, different fitting: we return to this in Section 3.4.

3.3Naive Bayes

With many features, a full covariance matrix has D(D+1)/2 entries per class, too many to estimate from little data. Naive Bayes makes the opposite extreme assumption: the features are independent given the class,

p(x\mid y=c)=\prod_{d=1}^Dp(x_d\mid y=c). \tag{7}

The assumption is “naive” because features are rarely independent, yet the classifier often works well, partly because it has only O(CD) parameters and is hard to overfit (Murphy, 2022, §9.3).

Binary features. For x_d\in\{0,1\} (a word appears in an e-mail or not, a pixel has ink or not), each feature is a coin with probability \theta_{dc}=p(x_d=1\mid y=c). Maximum likelihood counts: \hat\theta_{dc}=N_{dc}/N_c, the fraction of class-c examples in which feature d is on. A word never seen in spam would get probability exactly 0 and veto the class forever, so in practice one adds one imaginary “on” and one “off” example, \hat\theta_{dc}=(N_{dc}+1)/(N_c+2): add-one (Laplace) smoothing, the posterior mean under a flat prior (Murphy, 2022, §9.3.3).

Naive Bayes is linear too. Insert (7) with Bernoulli features into the log-odds (3):

\begin{aligned} a(x)&=\log\frac{\pi_1}{\pi_0}+\sum_{d}\left[x_d\log\frac{\theta_{d1}}{\theta_{d0}}+(1-x_d)\log\frac{1-\theta_{d1}}{1-\theta_{d0}}\right]\\ &=\sum_d\underbrace{\log\frac{\theta_{d1}(1-\theta_{d0})}{\theta_{d0}(1-\theta_{d1})}}_{w_d}\,x_d+\underbrace{\log\frac{\pi_1}{\pi_0}+\sum_d\log\frac{1-\theta_{d1}}{1-\theta_{d0}}}_{b}. \end{aligned} \tag{8}

Again p(y=1\mid x)=\sigma(w^\top x+b). Each weight w_d is the log of an odds ratio: how much more often feature d is on in class 1 than in class 0. The same holds for categorical features and, more generally, for class-conditional densities in the exponential family with shared parameters (Bishop, 2006, §4.2.4).

Bernoulli naive Bayes on the 361 handwritten 4s and 9s (8\times8 pixels, ink if the grey level is above 7 of 16). (a), (b) The fitted probability of ink at each pixel (add-one smoothing). (c) The weights w_d of (8): red pixels are evidence for a 9, blue for a 4. (d) The weights of logistic regression fitted to the same data. Data: Alpaydin and Kaynak (1998); computed for this tutorial.
Figure 4. Bernoulli naive Bayes on the 361 handwritten 4s and 9s (8\times8 pixels, ink if the grey level is above 7 of 16). (a), (b) The fitted probability of ink at each pixel (add-one smoothing). (c) The weights w_d of (8): red pixels are evidence for a 9, blue for a 4. (d) The weights of logistic regression fitted to the same data. Data: Alpaydin and Kaynak (1998); computed for this tutorial.

Worked example 4 (Naive Bayes on handwritten digits). Figure 4 fits Bernoulli naive Bayes to the 4s and 9s of the classic 8\times8 handwritten digits (Alpaydin and Kaynak, 1998) (181 fours, 180 nines, 64 binary pixels). Fitting is just counting ink, and the weights (c) are readable: ink across the top and down the right side (the loop and tail of a 9) is evidence for a 9, ink in the middle rows on the left (the crossbar and left stroke of a 4) evidence for a 4. Naive Bayes misclassifies 1.4\% of these images, logistic regression none of them. Their weights are related (correlation 0.77) but not equal, because naive Bayes estimates each pixel separately while logistic regression fits all weights together. For scale, Murphy (2022, §9.3.1) reports 84.3\% test accuracy for Bernoulli naive Bayes on all ten classes of binarized MNIST.

A real case: the spam filter. Naive Bayes over word occurrences was proposed for junk e-mail by Sahami et al. (1998) and became the classic spam filter: it is trained by counting words, so it is fast and easy to update as new mail arrives.

3.4Generative–discriminative pairs

Equations (6) and (8) show that linear discriminant analysis and naive Bayes produce the same functional form as logistic regression, \sigma(w^\top x+b). They are called generative–discriminative pairs (Ng and Jordan, 2002). The difference is only in how w and b are chosen:

\text{generative: }\max_\theta\sum_n\log p(x_n,y_n\mid\theta),\qquad\text{discriminative: }\max_{w,b}\sum_n\log p(y_n\mid x_n,w,b). \tag{9}

The generative fit maximizes the joint likelihood and derives w from the class models; the discriminative fit maximizes the conditional likelihood directly. When the class models are right, both reach the same answer; when they are wrong, the discriminative fit is still the best linear boundary it can find, while the generative fit inherits the errors of its assumptions (Murphy, 2022, §9.2.3). The converse of (6) does not hold: a logistic posterior does not imply Gaussian classes (Poisson class models, for example, also give one) (Ng and Ma, 2023). Logistic regression makes the weaker assumption.

Pause and think. In (6), what happens to the boundary if the two classes have the same mean, \mu_1=\mu_0, but different priors?

Show the answer

Then w=0 and p(y=1\mid x)=\sigma(\log(\pi_1/\pi_0))=\pi_1 for every x: the features carry no information, and the posterior equals the prior. The classifier always picks the more common class.