Bayes classifier, parameters, smoothing, Gaussian NB
Open the interactive lessons →Naive Bayes and generative models past questions
Contents
- Orientation: what you will learn and why
- Big picture: concept map, comparison table and the recipe
- Start here: the probability you need, from zero
- Generative versus discriminative models
- The Bayes classifier and the posterior
- Counting the parameters of a model
- The Naive Bayes model and the naive assumption
- Estimating the parameters by counting (MLE)
- Predicting with Naive Bayes: scores, joint and posterior
- Laplace smoothing: removing impossible zeros
- 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
- Say the difference between a generative and a discriminative model, and name which is which.
- Use Bayes' rule to turn a joint probability $P(x,y)$ or a pair (prior, likelihood) into a posterior $P(y\mid x)$ and a predicted label.
- Run the Bayes classifier with uniform and Gaussian class densities, including finding the prior threshold at which the prediction flips.
- Count parameters: for a full joint model, for Naive Bayes with binary features, and for Gaussian features.
- State the naive assumption exactly and recognise the correct formula among look-alikes.
- Estimate the Naive Bayes parameters by counting from a data matrix $X$ of shape $(d,n)$ (columns are data points).
- Predict with Naive Bayes, compute a joint probability or a posterior, and handle zero counts with Laplace smoothing.
- Work with Gaussian Naive Bayes and mixed binary and Gaussian features.
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 ask | PYQs | Marks |
|---|---|---|
| Generative vs discriminative | 1 | 2 |
| Bayes classifier: posterior, uniform and Gaussian densities | 4 | 10 |
| Gaussian Naive Bayes and mixed features | 3 | 7.5 |
| Counting parameters | 7 | 20 |
| The Naive Bayes model and assumption | 3 | 8 |
| Estimating parameters by counting | 11 | 24 |
| Prediction: scores, joint probability, posterior | 6 | 18 |
| Laplace smoothing | 2 | 5 |
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.
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]
- A big picture section (next): concept map, generative versus discriminative table, formula lookup, mnemonics.
- Figures: parameter growth, the effect of smoothing, Gaussian class densities; one fully worked plain-versus-smoothed example.
- Recall questions, a PYQ pattern map, variations and a flowchart. All new material is tagged [ADDED].
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
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? | yes | no |
| How it learns | counting and averaging (closed form) | optimisation |
| Handles missing features? | easily, just drop the factor | harder |
| Weak point | the independence assumption | needs more tuning |
Which number to count: a lookup [ADDED]
| Question says | Formula | Example |
|---|---|---|
| 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 feature | mean and variance (divide by $n_c$) | values $1,2,3$: $\mu=2$, $\sigma^2=2/3$ |
Mnemonics and recognition cues [ADDED]
- "Count, divide by class size." The denominator is $n_y$, never $n$.
- "One zero kills the product." That is why we smooth.
- "Naive means: multiply." $P(x\mid y)=\prod_jP(x_j\mid y)$.
- "Pie rule:" $m$ outcomes need $m-1$ numbers.
- Cue "how many parameters": check naive or not, binary or Gaussian (Gaussian: two per class per feature).
- Cue "predict the label": compute a score per class, compare, no need for the denominator.
Analogy and its limit [ADDED]
| Analogy | Good for | Where it breaks |
|---|---|---|
| Voting committee: every feature casts an independent vote | why we multiply per-feature probabilities | real 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.
- 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"
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
$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).
"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.
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.
Idea 3. The 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
$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)$.
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.
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
$$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$.
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.
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.
Conditional probability: restrict to the condition, then count.
4. Generative versus discriminative models
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.
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
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].
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.
| Discriminative | Generative | |
|---|---|---|
| Models | $P(y\mid x)$ | $P(x,y)=P(y)P(x\mid y)$ |
| Interested in how features are generated? | No | Yes |
| Can create new example points? | No | Yes |
| Examples | Logistic regression, decision tree, SVM | Naive Bayes, Gaussian Naive Bayes |
| Needs | Direct fitting of a boundary or $P(y\mid x)$ | Prior and class-conditional distributions |
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.
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)$.
- 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.
Generative models the data; discriminative models the decision.
5. The Bayes classifier and the posterior
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".
$$\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.
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.
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.
$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).
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)$.
$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.
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)$.
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$.
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).
- The denominator is the same for every class, so it never changes the winner.
- Posteriors over all classes must add to 1.
Posterior is proportional to prior times likelihood.
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.
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$.
$$\#\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$.
$$\#\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.
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.
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.
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$.
- 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]
| $d$ | Full joint ($K=2$) | Naive Bayes ($K=2$) |
|---|---|---|
| 3 | 15 | 7 |
| 6 | 127 | 13 |
| 12 | 8191 | 25 |
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$.
- 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)$.
Count free numbers only: probabilities that must add to 1 lose one.
7. The Naive Bayes model and the naive assumption
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
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.
$$\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.
Four formulas look alike; only one is the naive assumption.
| Formula | What 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... | Model | Parameter per class and feature |
|---|---|---|
| 0 or 1 (present / absent) | Bernoulli Naive Bayes | $P(x_j=1\mid y)$ |
| one of several categories | Categorical Naive Bayes | One probability per category (they sum to 1) |
| a count (how many times a word occurs) | Multinomial Naive Bayes | Probability of each word per class |
| a real number | Gaussian Naive Bayes | Mean and variance |
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.
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.
- Independence is assumed within each class, not overall.
- For a feature value of 0 use $1-p$, not $p$.
Independent features, given the class.
8. Estimating the parameters by counting (MLE)
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).
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
- Rewrite $X$ as a list of data points (the columns of the $(d,n)$ matrix), each with its label.
- Split the points into the label-1 group and the label-0 group.
- Count the points in each group ($n_1$, $n_0$) and divide by $n$ for the prior.
- Inside one group, for the feature you need, count the points where it equals 1.
- Divide that count by the size of that group (not by $n$).
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.
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$.
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$.
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$.
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]
| Slip | What happens | Fix |
|---|---|---|
| divide by $n$ instead of $n_y$ | probabilities do not describe the class | use class size |
| mix up rows and columns of the $(d,n)$ matrix | wrong counts | a column is one sample |
| round early | last digit off | carry fractions, round at the end |
| forget the prior | wrong winner when classes are unbalanced | multiply by $P(y)$ |
Class 1 has $4$ points; $3$ have $f_2=1$. Estimate $P(f_2=1\mid y=1)$.
$3/4$.
MLE here is counting.
9. Predicting with Naive Bayes: scores, joint and posterior
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
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.
| Number | Meaning | Formula |
|---|---|---|
| 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
- Write the table of estimates $\hat P(c)$ and $\hat p_j^{\,c}$ (from counting).
- 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$.
- Multiply them, and multiply by the prior. That is $s_c$.
- Largest $s_c$ wins. (If asked for the posterior, divide each $s_c$ by $s_0+s_1$.)
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.
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)$.
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.
- Multiply prior and all factors for each class before comparing anything.
- One zero factor makes the whole score zero.
Prior times every factor, then compare.
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$.
$$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}$$
$\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
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$).
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$.
$$\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.
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)$.
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$.
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]
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.
| Spam | Ham | |
|---|---|---|
| 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.
- 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.
Add to top and bottom so no probability is 0.
11. Gaussian Naive Bayes and mixed features
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.
$$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.
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.
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.
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.
Problem. Same model, test point $(1,1)^T$.
What is asked. A label.
Idea / formula used. Score $=$ prior $\times$ binary factor $\times$ Gaussian height.
[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]
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$).
- 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.
One mean and one variance per feature per class.
Shape of the Gaussian boundary [ADDED]
| Covariances of the two classes | Boundary |
|---|---|
| Equal, $\Sigma_1=\Sigma_0=\Sigma$ | Linear |
| Both the identity, and equal priors | Perpendicular bisector of the segment joining the two means |
| Different | Curved (quadratic) |
$$(\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$$
$\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.