Naive Bayes and generative models

Bayes classifier, parameters, smoothing, Gaussian NB

11 lessons · 37 past questions · 94.5 marks in the papers collected here

Open the interactive lessons →Naive Bayes and generative models past questions

Diagrams, animations, quizzes and checked solutions are on the interactive pages.

Contents

  1. Orientation: what you will learn and why
  2. Big picture: concept map, comparison table and the recipe
  3. Start here: the probability you need, from zero
  4. Generative versus discriminative models
  5. The Bayes classifier and the posterior
  6. Counting the parameters of a model
  7. The Naive Bayes model and the naive assumption
  8. Estimating the parameters by counting (MLE)
  9. Predicting with Naive Bayes: scores, joint and posterior
  10. Laplace smoothing: removing impossible zeros
  11. Gaussian Naive Bayes and mixed features

1. Orientation: what you will learn and why

A generative model learns how the data of each class is produced. Naive Bayes is the simplest and most examined generative classifier: it learns a few counts from the training data, and then classifies a new point by asking "which class would most likely have produced these features?". This topic teaches the idea, the counting, the prediction rule and every small trick the exam uses.

What you will be able to do

Why this topic matters for Quiz 2

The numbers below are counted only from the past-year questions (PYQs) supplied in this project. They are not a prediction.

What the PYQs askPYQsMarks
Generative vs discriminative12
Bayes classifier: posterior, uniform and Gaussian densities410
Gaussian Naive Bayes and mixed features37.5
Counting parameters720
The Naive Bayes model and assumption38
Estimating parameters by counting1124
Prediction: scores, joint probability, posterior618
Laplace smoothing25

In total this topic has 37 PYQs worth 94.5 marks, spread over all 10 papers in the bank (7 MCQ, 1 MSQ, 29 numeric). Counting from a data matrix and predicting is the largest block, so the goal of the middle of this page is to make those two routines automatic.

How this topic connects

From the Decision Trees topic you already know proportions (a class fraction) and "choose the option with the larger score". Naive Bayes reuses both: priors are class fractions and the prediction is "larger score wins". The Ridge, Lasso and MAP topic uses the same probability language: priors and the Gaussian density.

Tags used on this site: [SRC] comes from your files, [DERIVED] is an answer I worked out because the bank gives no key, [ADDED] is my own explanation or example, [FLAG] marks a source error or ambiguity. A question I made up is called "exam-style [ADDED]", never a PYQ.
How to use this page

Read a section, open each worked example one step at a time (try to predict the next step first), then do the quick check at the end of the section. Attempt every PYQ yourself before opening its solution.

What is new in this upgrade [ADDED]

The route through this topic
probability basicsBayes classifierestimate by countingpredict, smooth, Gaussian

2. Big picture: concept map, comparison table and the recipe

[ADDED] Read this page first. It shows what naive Bayes does and how the tools fit together.

The concept map

Training datafeatures + labelsCount / averageP(y), P(x_j | y)Smoothno zero countsModeltables of numbersNew point xread its feature valuesScore per classP(y) times product of P(x_j|y)Predictlargest score (argmax)The naive assumption (features independent given the class) turns one huge table into d small ones:parameters grow like K d instead of K 2^d. The price: probabilities can be badly off, though the argmax is often right.
Learn by counting, smooth the counts, store small tables. To predict, multiply the table entries for each class and pick the largest score.

Generative and discriminative side by side

Generative (naive Bayes)Discriminative (logistic, SVM)
What is modelled$P(x\mid y)$ and $P(y)$$P(y\mid x)$ or the boundary directly
Can it produce new data?yesno
How it learnscounting and averaging (closed form)optimisation
Handles missing features?easily, just drop the factorharder
Weak pointthe independence assumptionneeds more tuning

Which number to count: a lookup [ADDED]

Question saysFormulaExample
classes $K$, $d$ binary features, naive$(K-1)+Kd$$K=4,d=6$: $3+24=27$
classes $K$, $d$ binary features, full joint$K2^d-1$$K=3,d=4$: $3\cdot16-1=47$
probability of feature value$k/n_y$count over the class size
feature never seen in the class$(k+1)/(n_y+2)$add-one smoothing
real-valued featuremean and variance (divide by $n_c$)values $1,2,3$: $\mu=2$, $\sigma^2=2/3$

Mnemonics and recognition cues [ADDED]

Analogy and its limit [ADDED]

AnalogyGood forWhere it breaks
Voting committee: every feature casts an independent votewhy we multiply per-feature probabilitiesreal features are not independent: two words that always appear together vote twice, so the committee double-counts

Recall questions

Naive Bayes with $K=2$, $d=12$ binary features: how many free parameters?

$(2-1)+2\cdot12=25$ (the full joint needs $2^{13}-1=8191$).

What does "naive" refer to?

Features are assumed independent given the class.

Tips and tricks
  • Work in two layers: class prior, then one factor per feature.
  • Compare class scores; divide by their sum only if a probability is asked.

3. Start here: the probability you need, from zero

Naive Bayes is only counting plus six small probability ideas. Read them slowly once; every later page uses them.

Idea 1. Probability is a fraction of "all the cases"

Definition: probability of an event

If we look at a large collection of cases (for example, 100 emails), the probability of an event $A$ is $P(A)=\dfrac{\text{number of cases where }A\text{ happens}}{\text{all cases}}$. It is always between $0$ and $1$. The probabilities of all the possible outcomes of one question (spam / not spam) add up to $1$.

Plain words: "out of everything we looked at, what fraction was like this?". This is exactly the "proportion" $p$ of the Decision Trees topic.

Idea 2. Conditional probability: shrink the world first

Definition: conditional probability

$P(A\mid B)$ is read "the probability of $A$ given $B$". It means: throw away every case where $B$ did not happen, then find the fraction of the remaining cases where $A$ happens. $$P(A\mid B)=\frac{P(A,B)}{P(B)}$$ $P(A,B)$ is the probability that both happen (the joint probability).

Everyday analogy

"Among the students who passed the exam, what fraction studied more than 5 hours?" You first look only at the passed students (the new, smaller world), and only then take a fraction. Where the analogy stops: the denominator changes with the condition, which is the whole point; the fraction is not out of everybody.

Worked example: a spam table

Problem. Out of $100$ emails, $40$ are spam and $60$ are not. The word "offer" appears in $30$ of the spam emails and in $6$ of the non-spam emails. Find $P(\text{spam})$, $P(\text{offer})$, $P(\text{offer}\mid\text{spam})$ and $P(\text{spam}\mid\text{offer})$.

What is asked. Four probabilities; the last two look similar but are different.

Idea / formula used. Count cases, then divide by the size of the (possibly shrunk) world.

$P(\text{spam})=40/100=0.40$.
Emails with "offer": $30+6=36$. $P(\text{offer})=36/100=0.36$.
$P(\text{offer}\mid\text{spam})$: keep only the $40$ spam emails; $30$ of them have the word. $30/40=0.750$.
$P(\text{spam}\mid\text{offer})$: keep only the $36$ emails with the word; $30$ of them are spam. $30/36=0.8333$.
Answer: $0.40,\ 0.36,\ 0.750,\ 0.8333$
Thinking $P(\text{offer}\mid\text{spam})$ and $P(\text{spam}\mid\text{offer})$ are the same. They have different denominators ($40$ versus $36$) and answer different questions. Naive Bayes is exactly the trick of getting the second from the first.

Idea 3. The product rule

Formula: product rule

$$P(A,B)=P(B)\,P(A\mid B)=P(A)\,P(B\mid A)$$

  • $P(A,B)$: both $A$ and $B$ happen.
  • $P(B)$: $B$ happens (the world we shrink to).
  • $P(A\mid B)$: inside that world, $A$ happens.

Why it works: it is just the conditional-probability definition multiplied out. In the email example, $P(\text{spam},\text{offer})=P(\text{spam})\,P(\text{offer}\mid\text{spam})=0.40\times0.75=0.30$, which matches $30/100$.

Idea 4. Independence, and conditional independence

Definition: independent events

$A$ and $B$ are independent if knowing one tells you nothing about the other: $P(A,B)=P(A)\,P(B)$. They are conditionally independent given $C$ if, once you know $C$, they tell you nothing about each other: $P(A,B\mid C)=P(A\mid C)\,P(B\mid C)$.

Everyday analogy

On a hot day, "ice cream sales" and "swimming-pool visitors" both go up, so across all days they move together (not independent). But on days when we are told "it is hot" (given $C$), knowing the ice cream sales does not help predict pool visitors any more; both are explained by the heat. This is conditional independence. Where the analogy stops: in real data the independence is only approximate; Naive Bayes simply assumes it.

Trap: independent versus conditionally independent

These are different statements. The Naive Bayes assumption is conditional independence given the class, not independence of the features overall. A wrong option in the exam often drops the "given $y$".

Idea 5. Bayes' rule

Formula: Bayes' rule

$$P(y\mid x)=\frac{P(x\mid y)\,P(y)}{P(x)},\qquad P(x)=\sum_{y'}P(x\mid y')\,P(y')$$

  • $P(y)$: the prior, how common class $y$ is before looking at $x$.
  • $P(x\mid y)$: the likelihood, how likely the features $x$ are inside class $y$.
  • $P(y\mid x)$: the posterior, how likely class $y$ is after seeing $x$.
  • $P(x)$: the evidence; the same for every class, so it is only a normaliser.

Why it works: write the product rule both ways, $P(x,y)=P(y)P(x\mid y)=P(x)P(y\mid x)$, and divide by $P(x)$. Check with the emails: $\dfrac{P(\text{offer}\mid\text{spam})P(\text{spam})}{P(\text{offer})}=\dfrac{0.75\times0.40}{0.36}=0.8333$, the same $30/36$ as before.

Idea 6. Reading the data matrix $X$ of shape $(d,n)$

In this course the data matrix $X$ has shape $(d,n)$: $d$ rows are the features and $n$ columns are the data points. So the first column is the first data point, and the first row lists feature 1 over all data points. The labels sit in a vector $y$ of length $n$.

Worked example: reading a matrix

Problem. $X=\begin{bmatrix}1&0&0&0\\0&1&0&0\\0&1&1&0\end{bmatrix}$ and $y=[1,0,1,0]^T$ (this is the Aug 2023 matrix). How many features and data points are there, and what are the data points?

What is asked. The shape, and the data points as vectors.

Idea / formula used. $X$ has $d$ rows and $n$ columns; each column is one data point.

The matrix has $3$ rows and $4$ columns, so $d=3$ features and $n=4$ data points.
Column 1 is $(1,0,0)$, column 2 is $(0,1,1)$, column 3 is $(0,0,1)$, column 4 is $(0,0,0)$.
Pair each column with its label: $(1,0,0)\to1$, $(0,1,1)\to0$, $(0,0,1)\to1$, $(0,0,0)\to0$.
Answer: 4 data points: $(1,0,0){:}1,\ (0,1,1){:}0,\ (0,0,1){:}1,\ (0,0,0){:}0$
Reading the rows as data points. Row 1 is $(1,0,0,0)$, which is feature 1 across the four data points, not a data point.
Rewrite first

Whenever a PYQ gives $X$ as a $d\times n$ matrix, first rewrite it as a list of $n$ data points (the columns) with their labels. Every later counting step becomes easy and error-free.

Memory line

Conditional probability: restrict to the condition, then count.

Conditional probability by counting
fix the conditionkeep only those rowscount the event among themdivide

4. Generative versus discriminative models

Picture it

Learning to speak two languages against only learning to tell them apart.

Every classifier is, in the end, a way of getting from features $x$ to a label $y$. There are two very different ways of doing it, and the exam asks you to tell them apart.

Intuition

Imagine you must tell cats from dogs.

Everyday analogy

Discriminative way: you only learn the dividing rule ("pointy ears and thin face means cat"). You never learn what a cat or a dog looks like in full. Generative way: you learn what a typical cat looks like and what a typical dog looks like (so you could draw one), and to classify a new animal you ask "which of my two pictures explains this animal better?". Where the analogy stops: the generative model also needs the prior, how common cats and dogs are.

Definitions

Definition: discriminative model

A model of the label given the features: it learns $P(y\mid x)$ directly (or just a decision rule). It is not interested in how the features $x$ themselves are distributed. Examples in this course: logistic regression, decision trees, SVM [ADDED].

Definition: generative model

A model of how the data is generated: it learns the joint distribution $$P(x,y)=P(y)\,P(x\mid y)$$ that is, the prior $P(y)$ and, for each class, how the features $x$ are distributed ($P(x\mid y)$). Naive Bayes and Gaussian Naive Bayes are generative.

To classify, a generative model uses Bayes' rule to get the posterior $P(y\mid x)$ from the joint. The story it tells is: first choose the class $y$ with probability $P(y)$; then generate the features $x$ from that class's distribution $P(x\mid y)$. Because it can run this story, a generative model can also produce new data points, which a discriminative model cannot.

DiscriminativeGenerative
Models$P(y\mid x)$$P(x,y)=P(y)P(x\mid y)$
Interested in how features are generated?NoYes
Can create new example points?NoYes
ExamplesLogistic regression, decision tree, SVMNaive Bayes, Gaussian Naive Bayes
NeedsDirect fitting of a boundary or $P(y\mid x)$Prior and class-conditional distributions
Trap: swapping the two

The exam wording often swaps them: "in a generative model we model $p(y\mid x)$" is false (that is the discriminative statement); "Gaussian Naive Bayes is a discriminative model" is false. Memorise: generative $=$ joint $=$ how features are generated.

Worked example: classify each statement

Problem. Decide true or false: (i) A generative model is interested in how the features are generated. (ii) A discriminative model models $p(y\mid x)$. (iii) Naive Bayes can be used to sample a new email. (iv) Logistic regression learns $p(x\mid y)$.

What is asked. Four true/false verdicts.

Idea / formula used. Generative $=$ $P(x,y)$; discriminative $=$ $P(y\mid x)$.

(i) A generative model learns $P(x\mid y)$, the way features are produced in each class. True.
(ii) A discriminative model goes directly for $P(y\mid x)$. True.
(iii) Naive Bayes learns $P(y)$ and $P(x\mid y)$, so we can pick a class, then sample features. True.
(iv) Logistic regression models $P(y\mid x)$ only; it never models how $x$ is distributed. False.
Answer: True, True, True, False
Treating "uses Bayes' rule" as the definition of a generative model. Only the model that learns the joint is generative.
Tips and tricks
  • A model of $P(x,y)$ is generative; a model of only $P(y\mid x)$ or a boundary is discriminative.
  • If it can produce new examples, it models how the data arise.
Memory line

Generative models the data; discriminative models the decision.

Two ways to classify
data with labelsgenerative: model P(x, y)discriminative: model P(y | x)predict the likelier label

5. The Bayes classifier and the posterior

Picture it

A doctor starts with how common each illness is and updates it with the symptoms.

Once a generative model gives you $P(y)$ and $P(x\mid y)$, the question is: what label should we announce for a new point $x$?

Intuition

Choose the class that is most probable given what we saw. That is the posterior $P(y\mid x)$, and the rule is simply "pick the biggest".

Definition: Bayes classifier

$$\hat y=\arg\max_{y}\,P(y\mid x)=\arg\max_{y}\,P(y)\,P(x\mid y)$$

The second form holds because $P(x)$ in Bayes' rule is the same for every class and cannot change which class is biggest. For two classes with labels $1$ and $0$: predict $1$ when $P(y{=}1)\,P(x\mid 1)\ \ge\ P(y{=}0)\,P(x\mid 0)$, otherwise predict $0$. When the two are equal (a tie) the exam tells you which way to break it.

In many PYQs the prior is written $\hat p$ ("an estimate for $P(y=1)$") and is estimated by MLE, which means simply the fraction of training points with label 1.

Case 1. The joint probabilities are given

If you are told $P(X=x,Y=c)$ for each class $c$, the posterior is the joint divided by the sum of the joints: $$P(Y=c\mid X=x)=\frac{P(X=x,Y=c)}{\sum_{c'}P(X=x,Y=c')}$$ Reason: the denominator is $P(X=x)$ by the total-probability rule, so this is the conditional-probability definition.

Worked example: Posterior from two joint probabilities

Problem. For one transaction $x$: $P(x,\text{Fraud})=0.004$ and $P(x,\text{Genuine})=0.016$.

What is asked. $P(\text{Fraud}\mid x)$.

Idea / formula used. Divide the joint by the total over both classes.

$P(x)=0.004+0.016=0.020$.
$0.004/0.020=0.20$.
Check: the other posterior is $0.80$.
Answer: $0.20$
Common mistake: answering $0.004$, which is a joint probability.

Case 2. Class-conditional densities (uniform, Gaussian)

For a continuous feature $P(x\mid y)$ is a density, a height on a curve, not a probability. The rule still works: compare $P(y)\times\text{height}$ for each class. Two shapes appear in the PYQs.

Definition: uniform density

$x\mid y\sim\text{Uniform}[a,b]$ has density $\dfrac1{b-a}$ for $a\le x\le b$ and $0$ outside. A shorter interval has a taller density (the same total area $1$ squeezed into a smaller width).

Worked example: uniform densities and the prior threshold

Problem. Exam-style [ADDED]: $x\mid y{=}1\sim U[0,6]$ and $x\mid y{=}0\sim U[2,4]$. Let $p=P(y{=}1)$. For which $p$ does the Bayes classifier predict $1$ at $x=3$ (ties go to class 1)? What does it predict at $x=5$?

What is asked. A condition on $p$, then a label.

Idea / formula used. Predict $1$ when $p\,f_1(x)\ge(1-p)\,f_0(x)$.

Heights at $x=3$: $f_1(3)=1/6=0.1667$ and $f_0(3)=1/2=0.50$ (both $3$ is inside $[0,6]$ and inside $[2,4]$).
Condition: $p\cdot\tfrac16\ \ge\ (1-p)\cdot\tfrac12$.
Multiply both sides by $6$: $p\ge3(1-p)=3-3p$.
Add $3p$: $4p\ge3$, so $p\ge\tfrac34$.
At $x=5$: $f_0(5)=0$ because $5$ is outside $[2,4]$, while $f_1(5)=1/6>0$. So $p/6\ge0$ holds for every $p>0$: predict $1$.
Answer: $p\ge3/4$ at $x=3$; at $x=5$ always $1$ (for $p>0$)
Forgetting that the density is $0$ outside its interval, which makes the other class win automatically there. Also flipping the inequality when you multiply: both sides are multiplied by a positive number, so $\ge$ stays $\ge$.
Definition: Gaussian density

$x\mid y\sim N(\mu,\sigma^2)$ has density $\displaystyle f(x)=\frac1{\sqrt{2\pi\sigma^2}}\exp\!\Big(-\frac{(x-\mu)^2}{2\sigma^2}\Big)$. Here $\mu$ is the mean (centre), $\sigma^2$ the variance, and $\exp(t)=e^{t}$. It is tallest at $x=\mu$ and falls as $x$ moves away.

Worked example: Gaussian class densities

Problem. Exam-style [ADDED]: $x\mid y{=}0\sim N(0,1)$, $x\mid y{=}1\sim N(3,1)$, $\hat p=P(y{=}1)=0.5$. Predict at $x=1$.

What is asked. A label for $x=1$.

Idea / formula used. Compare $\hat p\,f_1(1)$ with $(1-\hat p)\,f_0(1)$; with equal priors compare $f_1(1)$ with $f_0(1)$.

$f_0(1)=\dfrac1{\sqrt{2\pi}}e^{-1/2}=0.3989\times0.6065=0.2420$.
$f_1(1)=\dfrac1{\sqrt{2\pi}}e^{-(1-3)^2/2}=0.3989\times0.1353=0.0540$.
Multiply by the priors (both $0.5$): $0.1210$ versus $0.0270$.
The class-0 score is larger, so predict $0$. Sanity: $x=1$ is only $1$ away from $\mu_0=0$ but $2$ away from $\mu_1=3$.
Answer: predict $0$
Comparing the mean values ($0$ and $3$) instead of the heights at $x$, or using the variance as if it were the standard deviation in the exponent.

The Bayes error: how often does even the best rule err?

Even the Bayes classifier can be wrong where the classes overlap. At each $x$ it picks the larger of $P(y)P(x\mid y)$, so the part it loses is the smaller one. Over all $x$ the expected error is $\displaystyle\int\min\{P(y{=}1)f_1(x),\,P(y{=}0)f_0(x)\}\,dx$. Example: positives uniform on $[0,4]$ (height $1/4$), negatives uniform on $[3,5]$ (height $1/2$), $p=0.5$. They overlap only on $[3,4]$, where the weighted heights are $0.125$ (positive) and $0.25$ (negative). The smaller one is the error, over a length of $1$: error $=0.125$.

Trap: tie-break and the boundary

Read the tie rule in the question ("tie-breaker is predicted in class 1"). It decides whether the answer is $p\ge\tfrac23$ or $p>\tfrac23$. Also check whether the point sits exactly on the end of an interval: for $U[2,4]$ the density at $x=2$ is still $1/2$ (the interval is closed).

Tips and tricks
  • The denominator is the same for every class, so it never changes the winner.
  • Posteriors over all classes must add to 1.
Memory line

Posterior is proportional to prior times likelihood.

Bayes classifier
prior of each classtimes likelihood of xcompare the productspick the largest

6. Counting the parameters of a model

"How many parameters do we need to estimate?" appears in many PYQs (7 of them). The idea is simple once you see the one rule behind it.

Intuition

A parameter is a number the model must learn from data. Probabilities that add up to $1$ are not all free: if you know all but one, the last is forced. So we count free (independent) parameters.

Everyday analogy

You are told how a pie is cut into 4 slices. You only need to be told the sizes of 3 slices; the fourth is "whatever is left". A distribution over $m$ outcomes therefore has $m-1$ free parameters. A coin has $1$ (just $P(\text{heads})$), a die has $5$. Where the analogy stops: a Gaussian is not a pie; it has two free numbers, the mean $\mu$ and the variance $\sigma^2$.

Formula: the one counting rule

$$\#\text{free parameters of a categorical distribution over }m\text{ outcomes}=m-1$$

Why it works: the $m$ probabilities must sum to $1$, which removes one degree of freedom.

Case 1. The full joint model (no independence assumption)

A generative model that learns $P(x,y)$ for $d$ binary features and $K$ classes must give a probability to every possible pair $(x,y)$. There are $2^d$ feature vectors and $K$ classes, so $K\cdot2^d$ outcomes, and one number is forced by the sum-to-one rule: $$K\cdot2^d-1$$ For $K=2$ labels and $d$ binary features this is $2^{d+1}-1$. Example: $d=12$, $K=2$: $2^{13}-1=8191$.

Equivalent view: $K-1$ numbers for the prior, plus for each class $2^d-1$ numbers for $P(x\mid y)$: $(K-1)+K(2^d-1)=K\cdot2^d-1$. Same total.

Case 2. With the naive (class-conditional independence) assumption

Now $P(x\mid y)=\prod_jP(x_j\mid y)$, so for each class and each binary feature we need just one number, $P(x_j=1\mid y)$ (the other is $1$ minus it): $$\underbrace{(K-1)}_{\text{prior}}+\underbrace{K\,d}_{\text{one per class per feature}}$$ Example: $K=3$, $d=4$: $2+12=14$.

Formula: Naive Bayes, binary features

$$\#\text{free parameters}=(K-1)+K\,d$$

  • $K$: number of classes; $d$: number of binary features.
  • $K-1$: the prior $P(y)$ over $K$ classes.
  • $Kd$: the Bernoulli parameter $P(x_j=1\mid y)$ for every class $y$ and feature $j$.

It grows linearly in $d$ instead of exponentially, which is the whole reason for the naive assumption.

Some solutions store the prior as $K$ numbers and count $K+Kd$. The Mar 2024 PYQ accepts both ($19$ to $20$ for $K=5$, $d=3$). Use $K-1$ when the question says "free" or "independent", and match the options if they are given (the Mar 2025 options $5k$, $6k-1$, $(6k-1)^5$, $3k-3$ contain $6k-1=(k-1)+5k$).

Case 3. Gaussian features

A real-valued feature in a class is modelled by a Gaussian with two free numbers, the mean $\mu$ and the variance $\sigma^2$. If the question says "the variances are equal for both classes", then the variance is shared and is counted once.

Worked example: mixed features

Problem. Predict pass/fail ($K=2$) from hours studied (Gaussian, variances equal for both classes) and attendance at review sessions (binary). Features are conditionally independent given the outcome. How many parameters?

What is asked. A parameter count for a Naive Bayes classifier with one Gaussian and one binary feature.

Idea / formula used. Count the prior, then each feature separately.

Prior over $2$ classes: $2-1=1$.
Hours (Gaussian): one mean per class $=2$ means; one shared variance $=1$. Total $3$.
Attendance (binary): one Bernoulli parameter per class $=2$.
Add: $1+3+2=6$.
Answer: $6$
Counting two variances (one per class). The question says they are equal, so there is only one. If the variances were not equal the total would be $7$.
Worked example: four classes, six binary features

Problem. Exam-style [ADDED]: $K=4$ classes, $d=6$ binary features. Count the free parameters (a) for the full joint model and (b) for Naive Bayes.

What is asked. Two counts.

Idea / formula used. Full joint: $K\,2^d-1$. Naive Bayes: $(K-1)+Kd$.

(a) $K\,2^d=4\times64=256$ outcomes, minus $1$: $255$.
(b) Prior: $K-1=3$. Features: $Kd=4\times6=24$. Total $3+24=27$.
Compare: $255$ versus $27$, so the naive assumption reduces the number a lot.
Answer: (a) $255$, (b) $27$
Using $2^d$ per class without subtracting $1$, or forgetting the prior $K-1$.
Trap: common slips
  • Counting $2^d\cdot K$ and forgetting the $-1$ of the sum-to-one rule.
  • Counting $d$ numbers for the whole model instead of $d$ numbers per class.
  • Forgetting the prior.
  • For three-valued features the per-class, per-feature number is $3-1=2$, not $1$.

How fast the counts grow: a figure [ADDED]

1101001k10k123456810128191 (full joint)25 (naive Bayes)number of binary features d (K = 2 classes, log scale)free parameters
The full joint model needs $K2^d-1$ parameters and doubles with every extra feature; naive Bayes needs $(K-1)+Kd$ and grows by $K$ per feature. At $d=12$: 8191 against 25.
$d$Full joint ($K=2$)Naive Bayes ($K=2$)
3157
612713
12819125

Counting slips: the prior contributes $K-1$ (not $K$); each binary feature contributes one number per class (not two); Gaussian features need a mean and a variance per class per feature.

Why $K-1$ for the prior?

The class probabilities sum to 1, so the last is fixed.

$K=5$, $d=3$ binary features, naive: parameters?

$4+15=19$.

Tips and tricks
  • For $d$ binary features and $K$ classes, Naive Bayes needs $(K-1)+Kd$ parameters.
  • Without the naive assumption it is $(K-1)+K(2^d-1)$.
Memory line

Count free numbers only: probabilities that must add to 1 lose one.

7. The Naive Bayes model and the naive assumption

Picture it

Judging each clue separately once you assume who the culprit is.

Case 1 of the last section showed the trouble: the full class-conditional $P(x\mid y)$ over $d$ binary features needs $2^d-1$ numbers per class. With $d=12$ that is already $4095$ per class, far more than any realistic training set can pin down. Naive Bayes gets out of this with one bold simplification.

The naive assumption

Definition: class-conditional independence (the naive assumption)

Given the class label $y$, the features are independent of each other: $$P(x\mid y)=P(x_1\mid y)\,P(x_2\mid y)\cdots P(x_d\mid y)=\prod_{j=1}^{d}P(x_j\mid y)$$

In words: once I tell you the class, knowing one feature tells you nothing new about the others. It is "naive" because real features are rarely independent given the class (in emails, "free" and "offer" tend to appear together even within spam). The model is still very useful because it needs so few numbers.

Formula: Naive Bayes classifier

$$\hat y=\arg\max_{y}\;P(y)\prod_{j=1}^{d}P(x_j\mid y)$$

  • $P(y)$: prior of class $y$ (a class fraction).
  • $P(x_j\mid y)$: how likely feature $j$ takes its observed value in class $y$.
  • The product over $j$ is the naive assumption at work.

The full posterior is $P(y\mid x)=\dfrac{P(y)\prod_jP(x_j\mid y)}{P(x)}$. The denominator is the same for every class, so for predicting we compare only the numerators.

Trap: look-alike formulas

Four formulas look alike; only one is the naive assumption.

FormulaWhat it is
$P(x,y)=P(y)\,P(x\mid y)$The product rule. Always true.
$P(y\mid x)=\dfrac{P(y)P(x\mid y)}{P(x)}$Bayes' rule. Always true.
$P(x)=P(x_1)P(x_2)P(x_3)$Full independence of the features without the class. Not the Naive Bayes assumption.
$P(x\mid y)=P(x_1\mid y)P(x_2\mid y)P(x_3\mid y)$The naive assumption (conditional on $y$).
$\prod_iP(y\mid x_i)$Multiplying posteriors of single features. Not valid; the prior and the evidence are wrong.

Which Naive Bayes? Match the model to the feature type

The naive assumption fixes the product form. What changes between versions of Naive Bayes is the distribution used for one feature $P(x_j\mid y)$.

Feature $x_j$ is...ModelParameter per class and feature
0 or 1 (present / absent)Bernoulli Naive Bayes$P(x_j=1\mid y)$
one of several categoriesCategorical Naive BayesOne probability per category (they sum to 1)
a count (how many times a word occurs)Multinomial Naive BayesProbability of each word per class
a real numberGaussian Naive BayesMean and variance
Worked example: choosing the model

Problem. The Jul 2022 PYQ shows training points at the corners of the unit square, $(0,0),(1,0),(0,1),(1,1)$. Which Naive Bayes fits best: Bernoulli, Categorical, Multinomial or Gaussian?

What is asked. The best-matching model type.

Idea / formula used. Look at the values each feature takes.

Both features take only the values $0$ and $1$: they are binary.
Gaussian is for real-valued features that spread continuously; four exact corners are not Gaussian-looking.
Multinomial is for counts such as word frequencies; here the features are not counts of anything.
Categorical would work (two categories each) but Bernoulli is its specialised, simplest form for binary features. Best choice: Bernoulli.
Answer: Bernoulli NB
Choosing Gaussian just because the points are plotted on axes. What matters is the set of values, not the picture.
Worked example: writing the expression

Problem. Exam-style [ADDED]: three binary features. Write $P(y{=}1\mid x)$ under the naive assumption.

What is asked. A formula.

Idea / formula used. Bayes' rule plus the naive assumption.

Bayes' rule: $P(y{=}1\mid x)=\dfrac{P(y{=}1)\,P(x\mid y{=}1)}{P(x)}$.
Naive assumption: $P(x\mid y{=}1)=P(x_1\mid1)P(x_2\mid1)P(x_3\mid1)$.
Substitute: $\dfrac{P(y{=}1)\,P(x_1\mid1)\,P(x_2\mid1)\,P(x_3\mid1)}{P(x)}$.
Answer: $\dfrac{P(y{=}1)\prod_{j=1}^3P(x_j\mid y{=}1)}{P(x)}$
Writing $\prod_jP(x_j)$ in the numerator (without "$\mid y$") or dropping the prior $P(y{=}1)$.
Tips and tricks
  • Independence is assumed within each class, not overall.
  • For a feature value of 0 use $1-p$, not $p$.
Memory line

Independent features, given the class.

The naive assumption
pick a classtreat each feature on its ownmultiply the feature probabilitiesmultiply by the prior

8. Estimating the parameters by counting (MLE)

Picture it

Taking a class register and turning tallies into fractions.

The model needs the prior $P(y)$ and, for each class and feature, $P(x_j=1\mid y)$. All of them are estimated by counting in the training data. This is the most common calculation in the PYQs (11 questions), so we will do it slowly.

Intuition

If $3$ of $4$ emails in the spam pile contain the word "offer", the natural estimate for "a spam email contains 'offer'" is $3/4$. The best guess of a probability is the fraction you actually saw. In statistics this is the maximum likelihood estimate (MLE).

Definition: the Naive Bayes estimates

With $n$ training points, $n_1$ of them in class 1, and, inside class $y$, $k_{jy}$ points having feature $j$ equal to $1$: $$\hat p=\frac{n_1}{n},\qquad \hat p_j^{\,y}=\frac{k_{jy}}{n_y}$$ The notation $\hat p_j^{\,y}$ means "estimate of $P(f_j=1\mid \text{label}=y)$": the subscript is the feature and the superscript is the class. The complements are $P(f_j=0\mid y)=1-\hat p_j^{\,y}$ and $P(y=0)=1-\hat p$.

Why counting is the MLE. Suppose a coin lands heads $k$ times out of $n$. The likelihood of that outcome for a bias $q$ is $q^{k}(1-q)^{n-k}$. Taking logs, $L(q)=k\ln q+(n-k)\ln(1-q)$. Setting the derivative to zero: $\dfrac kq-\dfrac{n-k}{1-q}=0\Rightarrow k(1-q)=(n-k)q\Rightarrow k=nq\Rightarrow q=k/n$. Inside each class and feature the data is exactly such a coin, so the estimate is the fraction.

The five-step routine

  1. Rewrite $X$ as a list of data points (the columns of the $(d,n)$ matrix), each with its label.
  2. Split the points into the label-1 group and the label-0 group.
  3. Count the points in each group ($n_1$, $n_0$) and divide by $n$ for the prior.
  4. Inside one group, for the feature you need, count the points where it equals 1.
  5. Divide that count by the size of that group (not by $n$).
Worked example: a full table, step by step

Problem. Training data (rows are points $(f_1,f_2)$ with label $y$): $(1,1){:}1$, $(1,0){:}1$, $(0,1){:}0$, $(0,0){:}0$, $(1,1){:}1$, $(0,0){:}0$. Find $\hat p$ and all four $\hat p_j^{\,y}$ (exam-style [ADDED]).

What is asked. Six numbers.

Idea / formula used. Counting inside each class.

Label-1 group: $(1,1),(1,0),(1,1)$, so $n_1=3$. Label-0 group: $(0,1),(0,0),(0,0)$, so $n_0=3$. Prior $\hat p=3/6=0.50$.
Class 1, feature 1: values $1,1,1$; three ones out of $3$. $\hat p_1^{\,1}=3/3=1.000$.
Class 1, feature 2: values $1,0,1$; two ones out of $3$. $\hat p_2^{\,1}=2/3=0.6667$.
Class 0, feature 1: values $0,0,0$; zero ones out of $3$. $\hat p_1^{\,0}=0/3=0.000$.
Class 0, feature 2: values $1,0,0$; one one out of $3$. $\hat p_2^{\,0}=1/3=0.3333$.
Answer: $\hat p=0.5$; $\hat p_1^{\,1}=1$, $\hat p_2^{\,1}=0.6667$, $\hat p_1^{\,0}=0$, $\hat p_2^{\,0}=0.3333$
Dividing by $n=6$ instead of the class size $3$. The denominator is always the size of the class you are inside.
Worked example: From a $(d,n)$ matrix

Problem. $X=\begin{bmatrix}1&1&0&1&0\\0&1&1&0&0\end{bmatrix}$, $y=(1,1,0,0,1)^T$. Find $\hat p_1^{\,1}$ and $\hat p_2^{\,1}$.

What is asked. Two class-1 feature probabilities.

Idea / formula used. Columns are data points; feature $j$ is row $j$.

Label-1 columns: 1, 2 and 5, so $n_1=3$.
Row 1 in those columns: $1,1,0$, giving $2/3$.
Row 2: $0,1,0$, giving $1/3$.
Answer: $\hat p_1^{\,1}=2/3$, $\hat p_2^{\,1}=1/3$
Common mistake: reading rows as data points.

Weighted-count tables

Sometimes the data comes as a table "feature vector, number of points, label" (the Jul 2022 passage). The routine is the same, but now you add the numbers of points instead of counting rows. For class 1:

$(x_1,x_2)$points
$(0,0)$12
$(0,1)$18
$(1,0)$9
$(1,1)$15

There are $12+18+9+15=54$ points; those with $x_1=1$ number $9+15=24$, so $\hat p_1^{\,1}=24/54\approx0.444$.

Truncate, do not round, when told

If a question says not to round up, report $24/54=0.444\ldots$ as $0.44$, and $5/9=0.5555\ldots$ as $0.55$, not $0.56$.

Trap: zero counts

If the count is zero then $\hat p=0$ (e.g. $\hat p_2^{\,1}=0$ in the Aug 2023 PYQ). It is a legitimate answer here, but later, in prediction, it vetoes a class. See Laplace smoothing.

Common estimation slips [ADDED]

SlipWhat happensFix
divide by $n$ instead of $n_y$probabilities do not describe the classuse class size
mix up rows and columns of the $(d,n)$ matrixwrong countsa column is one sample
round earlylast digit offcarry fractions, round at the end
forget the priorwrong winner when classes are unbalancedmultiply by $P(y)$
Class 1 has $4$ points; $3$ have $f_2=1$. Estimate $P(f_2=1\mid y=1)$.

$3/4$.

Memory line

MLE here is counting.

Estimating by counting
split the rows by classclass share gives the priorfeature share inside a classuse these as parameters

9. Predicting with Naive Bayes: scores, joint and posterior

Picture it

Each class gets a score; the highest score wins.

With the parameters in hand, we classify a new data point. The calculation is short, but three different numbers get confused: the likelihood, the joint and the posterior. We separate them here.

The score of a class

Definition: Naive Bayes score

For a test point $x=(x_1,\dots,x_d)$ and class $c$: $$s_c=\hat P(c)\prod_{j=1}^{d}q_{jc}(x_j),\qquad q_{jc}(x_j)=\begin{cases}\hat p_j^{\,c}&\text{if }x_j=1\\[2pt]1-\hat p_j^{\,c}&\text{if }x_j=0\end{cases}$$

The only subtle step is the choice per feature: use $\hat p_j^{\,c}$ when the test point has a $1$ in feature $j$, and $1-\hat p_j^{\,c}$ when it has a $0$. The predicted label is the class with the larger score.

NumberMeaningFormula
Likelihood $P(x\mid c)$How typical is $x$ inside class $c$ (no prior)$\prod_jq_{jc}(x_j)$
Joint $P(x,c)$Prior and likelihood together$\hat P(c)\prod_jq_{jc}(x_j)=s_c$
Posterior $P(c\mid x)$Joint, rescaled so classes add up to 1$s_c\big/\sum_{c'}s_{c'}$

The routine

  1. Write the table of estimates $\hat P(c)$ and $\hat p_j^{\,c}$ (from counting).
  2. For each class, go feature by feature: write $\hat p_j^{\,c}$ if $x_j=1$, or $1-\hat p_j^{\,c}$ if $x_j=0$.
  3. Multiply them, and multiply by the prior. That is $s_c$.
  4. Largest $s_c$ wins. (If asked for the posterior, divide each $s_c$ by $s_0+s_1$.)
Worked example: Prediction with given estimates

Problem. $\hat p=P(y{=}1)=0.3$; $\hat p_1^{\,0}=0.6$, $\hat p_2^{\,0}=0.2$, $\hat p_1^{\,1}=0.8$, $\hat p_2^{\,1}=0.7$. Predict $x=(1,0)^T$.

What is asked. A label.

Idea / formula used. Compare prior times feature probabilities for both classes.

A feature that is $0$ contributes $1-\hat p$.
$s_0=0.7\times0.6\times0.8=0.336$.
$s_1=0.3\times0.8\times0.3=0.072$.
Answer: label $0$ (posterior $0.336/0.408\approx0.82$)
Common mistake: using $\hat p_2$ instead of $1-\hat p_2$ when $x_2=0$.
Worked example: A joint probability from data

Problem. Six points $(X_1,X_2,X_3){:}Y$: $(0,1,1){:}1$, $(1,1,0){:}1$, $(0,0,1){:}0$, $(1,0,0){:}0$, $(1,1,1){:}1$, $(0,1,0){:}1$. Find $P(X,Y{=}1)$ for $X=(0,1,1)$.

What is asked. A prior times three feature probabilities.

Idea / formula used. $P(X,Y{=}1)=P(Y{=}1)\prod_jP(X_j\mid Y{=}1)$.

Class 1 has points 1, 2, 5, 6, so $P(Y{=}1)=4/6$.
$P(X_1{=}0\mid1)=2/4$.
$P(X_2{=}1\mid1)=4/4$.
$P(X_3{=}1\mid1)=2/4$.
Product: $\tfrac23\cdot\tfrac12\cdot1\cdot\tfrac12$.
Answer: $1/6$
Common mistake: taking the fraction of rows equal to $(0,1,1)$, which is not the naive Bayes estimate.
Worked example: A zero probability that decides everything

Problem. Class 0 has $\hat p_1^{\,0}=0$; the test point has $f_1=1$. Class 1 has score $s_1=0.02$.

What is asked. Why does class 0 lose, and what is its posterior?

Idea / formula used. Scores are products; one zero factor makes the product zero.

Class 0 uses the factor $\hat p_1^{\,0}=0$, so $s_0=0$ whatever the other features say.
Posterior $=0/(0+0.02)=0$.
Answer: predict class 1; posterior of class 0 is $0$
Common mistake: averaging the factors, or ignoring the zero one.
Tips and tricks
  • Multiply prior and all factors for each class before comparing anything.
  • One zero factor makes the whole score zero.
Memory line

Prior times every factor, then compare.

Making a prediction
score = prior times factorsdo it for every classlargest score winsnormalise only if asked

Why the binary Naive Bayes boundary is a straight line [ADDED]

Take the logarithm of (score of class $1$) divided by (score of class $0$). Every factor becomes a term, and because each $f_j$ is $0$ or $1$ the result has the form $w^Tx+b$. Predict $1$ when it is at least $0$.

Weights and bias

$$w_j=\ln\frac{\hat p_j^{\,1}(1-\hat p_j^{\,0})}{\hat p_j^{\,0}(1-\hat p_j^{\,1})},\qquad b=\sum_j\ln\frac{1-\hat p_j^{\,1}}{1-\hat p_j^{\,0}}+\ln\frac{\hat p}{1-\hat p}$$

Worked check

$\hat p=0.4$, $\hat p^{\,1}=(0.75,\,0.25)$, $\hat p^{\,0}=(\tfrac16,\,0.5)$. Then $w\approx(2.708,\,-1.099)$ and $b\approx-1.204$. At $x=(1,0)$: $w^Tx+b=1.504=\ln(0.225/0.05)$, positive, so class $1$, the same answer as multiplying the scores.

This needs every $\hat p_j^{\,y}$ strictly between $0$ and $1$, which smoothing guarantees.

10. Laplace smoothing: removing impossible zeros

Picture it

Giving every runner a head start of one step so that nobody sits at zero.

Counting has one weakness. If a feature value never appeared with a class in the training data, its estimated probability is exactly $0$, and then the product kills that class however well all the other features match. A single unlucky absence in a small data set should not make a class "impossible".

Intuition

Smoothing says: before counting, pretend we have seen each value a tiny bit. Add a small pseudo-count to every count so that no estimate is exactly $0$ (or exactly $1$).

Definition: Laplace smoothing (add-$\alpha$)

For a binary feature with pseudo-count $\alpha$ (usually $\alpha=1$): $$\hat p_j^{\,y}=\frac{k_{jy}+\alpha}{n_y+2\alpha}$$ For a feature with $m$ possible values the denominator is $n_y+m\alpha$.

The $2\alpha$ in the denominator ($m\alpha$ for $m$ values) is there because we added $\alpha$ pseudo-points to each of the $2$ ($m$) possible values, so the probabilities still add up to $1$.

Formula: add-one smoothing, binary feature

$$\hat p_j^{\,y}=\frac{k_{jy}+1}{n_y+2}$$

  • $k_{jy}$: number of class-$y$ points with $f_j=1$.
  • $n_y$: number of class-$y$ points.

Check: the smoothed probabilities of the values $1$ and $0$ are $\frac{k+1}{n+2}$ and $\frac{(n-k)+1}{n+2}$; they add to $\frac{n+2}{n+2}=1$ ✓.

Purpose in one line (Mar 2025 PYQ): to ensure unseen values receive small but nonzero probabilities. It is not about the variance of Gaussian features, and it does not strengthen certain features.

Worked example: Smoothing in action

Problem. Class 0 has four training points, all with $f_3=0$. Estimate $P(f_3=1\mid y=0)$ without and with add-one smoothing.

What is asked. Two estimates.

Idea / formula used. Plain $k/n$; smoothed $(k+1)/(n+2)$.

$k=0$, $n=4$.
Plain: $0/4=0$, which would veto class 0 for any test point with $f_3=1$.
Smoothed: $1/6$.
Answer: $0$ and $1/6$
Common mistake: adding $1$ to the numerator but not $2$ to the denominator.

A second way: add synthetic points

The Apr 2026 PYQ smooths by adding synthetic samples to the data instead of using the formula. It adds one all-ones sample with $Y=1$ and one all-ones sample with $Y=0$, then recounts as usual. The result can differ from the formula because the recipe is different: for $P(X_2=1\mid Y=1)$ the class-1 group has $n_1=3$ points with $X_2$ values $0,1,0$ (so $k=1$). Adding one all-ones class-1 sample gives $k=2$, $n=4$, so $2/4=0.5$. The add-one formula would give $(1+1)/(3+2)=0.4$.

Trap: follow the recipe the question uses

If the question describes added samples, count with them. If it says "Laplace smoothing" and gives no recipe, use $(k+1)/(n+2)$ for a binary feature. Do not mix the two.

What smoothing does, as a picture [ADDED]

00.250.50.7510.000.20k = 00.330.40k = 10.670.60k = 21.000.80k = 3plain k/n(k+1)/(n+2)k = number of class points with feature = 1, out of n = 3
With $n=3$ class points, plain estimates jump between $0$ and $1$; add-one estimates stay between $0.2$ and $0.8$. Smoothing pulls every estimate toward $1/2$.

One full example, plain against smoothed [ADDED] (not a PYQ)

Six emails: three spam, three ham, prior $0.5$ each. Feature 1 ("free") is present in $2$ spam and $1$ ham email. Feature 2 ("meeting") is present in $0$ spam and $2$ ham emails. New email has both words.

SpamHam
Plain score$0.5\cdot\frac23\cdot0=0.0000$$0.5\cdot\frac13\cdot\frac23=0.1111$
Smoothed score$0.5\cdot\frac35\cdot\frac15=0.0600$$0.5\cdot\frac25\cdot\frac35=0.1200$

Both ways predict ham here. The difference: plain says spam is impossible (score exactly $0$); smoothed says spam is possible but less likely. Normalising the smoothed scores gives $P(\text{ham}\mid x)=0.6667$ ($2/3$).

Smoothed estimate for $k=0$, $n=4$?

$(0+1)/(4+2)=1/6$.

Does smoothing change which class wins in the example above?

No, ham wins both ways; it only removes the impossible zero.

Tips and tricks
  • Add to the top and the bottom of each estimate, so the values of a feature still add to 1.
  • Read how the question describes the extra points, since that decides whether the prior changes too.
Memory line

Add to top and bottom so no probability is 0.

11. Gaussian Naive Bayes and mixed features

Picture it

Judging which bell-shaped hill a point sits higher on.

So far every feature was binary. Real data has measurements (height, temperature, hours studied). The recipe is unchanged; only the one-feature distribution $P(x_j\mid y)$ changes.

Gaussian Naive Bayes

For each class $c$ and each real feature $j$, assume $x_j\mid c\sim N(\mu_{jc},\sigma_{jc}^2)$. Its density is $f_{jc}(x)=\dfrac1{\sqrt{2\pi\sigma^2_{jc}}}\exp\!\big(-\tfrac{(x-\mu_{jc})^2}{2\sigma^2_{jc}}\big)$. The naive assumption multiplies the densities of the features.

Formula: Gaussian Naive Bayes score

$$s_c=\hat P(c)\prod_{j=1}^{d}f_{jc}(x_j),\qquad f_{jc}(x)=\frac{1}{\sqrt{2\pi\sigma_{jc}^2}}e^{-(x-\mu_{jc})^2/(2\sigma_{jc}^2)}$$

  • $\mu_{jc}$ and $\sigma^2_{jc}$ are the mean and variance of feature $j$ among the class-$c$ training points.
  • MLE: $\hat\mu=\frac1{n_c}\sum x$, $\hat\sigma^2=\frac1{n_c}\sum(x-\hat\mu)^2$ (divide by $n_c$).
  • A mixed model uses a Bernoulli probability for each binary feature and a Gaussian density for each real feature, all multiplied together.
Worked example: estimating a Gaussian by counting and averaging

Problem. Exam-style [ADDED]: one feature; class 0 values $1,2,3$ and class 1 values $4,6,8$. Estimate $\mu$ and $\sigma^2$ per class.

What is asked. Four numbers.

Idea / formula used. $\hat\mu$ is the average; $\hat\sigma^2$ is the average squared distance from it.

Class 0: $\hat\mu_0=(1+2+3)/3=2.0$.
Class 0: deviations $-1,0,1$; squares $1,0,1$; average $2/3=0.6667$.
Class 1: $\hat\mu_1=(4+6+8)/3=6.0$.
Class 1: deviations $-2,0,2$; squares $4,0,4$; average $8/3=2.6667$.
Answer: $\hat\mu_0=2,\ \hat\sigma_0^2=0.6667,\ \hat\mu_1=6,\ \hat\sigma_1^2=2.6667$
Dividing by $n-1$ instead of $n$. In this course the MLE divides by $n_c$.

Densities are heights, not probabilities

A density can be larger than $1$ (a very narrow Gaussian is tall). That is fine: we only compare scores, and for continuous features the "probability" of one exact value is zero. The PYQ phrase "the probability that the point is $[0,0]$" means the product of the binary probability and the Gaussian height, which is what we compute.

Worked example: Mixed features: likelihood under a class

Problem. $P(y{=}1)=0.25$; binary $f_1$ with $\hat p_1^{\,0}=0.7$, $\hat p_1^{\,1}=0.2$; $f_2\mid y{=}0\sim N(2,1)$, $f_2\mid y{=}1\sim N(0,1)$.

What is asked. $P(x=(1,2)\mid y=0)$.

Idea / formula used. Multiply the binary probability by the Gaussian height; no prior in a likelihood.

$f_1=1$ under class 0: $0.7$.
$f_2=2$ is the class-0 mean: height $1/\sqrt{2\pi}=0.3989$.
Product $0.7\times0.3989$.
Answer: about $0.279$
Common mistake: multiplying by the prior $0.75$, which gives a joint instead.
Worked example: Mixed features: prediction

Problem. Same model, test point $(1,1)^T$.

What is asked. A label.

Idea / formula used. Score $=$ prior $\times$ binary factor $\times$ Gaussian height.

Both class means are $1$ away from $f_2=1$, so both heights are $0.2420$.
$s_0=0.75\times0.7\times0.2420=0.127$.
$s_1=0.25\times0.2\times0.2420=0.0121$.
Answer: class $0$
Common mistake: comparing only the Gaussian heights, which are equal here.

[ADDED] Side fact (not asked in PYQs): with equal variances and equal priors, two Gaussian classes in one dimension are separated at the midpoint of the two means; with unequal variances the boundary is curved.

Gaussian naive Bayes, drawn [ADDED]

0123456789boundary x = 3.40class 0: mean 2, var 1class 1: mean 5, var 2.25feature value x (equal priors)
Class 0 has mean $2$, variance $1$; class 1 has mean $5$, variance $2.25$; equal priors. The classes swap at $x=3.40$, where the two heights are equal. The wider class keeps higher density far from its mean, so it wins the right-hand tail.

Values for the page's estimation example: class 0 (values $1,2,3$): mean $2$, variance $2/3$; class 1 (values $4,6,8$): mean $6$, variance $8/3$. The code recomputes these.

Is a Gaussian density value a probability?

No, it is a height; it can exceed 1 for small variance.

Which divisor for the variance MLE?

$n_c$ (not $n_c-1$).

Tips and tricks
  • Check whether the question gives a variance or a standard deviation.
  • With equal variances and equal priors, the nearer class mean wins in one dimension.
Memory line

One mean and one variance per feature per class.

Shape of the Gaussian boundary [ADDED]

Covariances of the two classesBoundary
Equal, $\Sigma_1=\Sigma_0=\Sigma$Linear
Both the identity, and equal priorsPerpendicular bisector of the segment joining the two means
DifferentCurved (quadratic)
Equal covariance: predict 1 when

$$(\mu_1-\mu_0)^T\Sigma^{-1}x+\tfrac12\big(\mu_0^T\Sigma^{-1}\mu_0-\mu_1^T\Sigma^{-1}\mu_1\big)+\ln\frac{p}{1-p}\ge0$$

Worked example

$\mu_0=(0,0)$, $\mu_1=(4,2)$, $\Sigma=I$, $p=0.5$: the rule is $4x_1+2x_2-10\ge0$. The midpoint $(2,1)$ gives exactly $0$, as a perpendicular bisector should.

Practise this topic →

Weeks covering this topic

Other MLT topics