Classes w1,…,wc; priors p(wi), ∑ip(wi)=1; class-conditional density p(X∣wi)=fi(X); posterior p(wi∣X). Φ = standard normal CDF, ϕ = its density.
Python helpers — run once, checks below reuse them
import numpy as npfrom scipy.stats import normfrom scipy.optimize import minimize_scalarPhi = norm.cdf # standard normal CDF
flowchart LR
P["prior p(w)"] --> B((Bayes))
L["likelihood p(X|w)"] --> B
B --> Q["posterior p(w|X)"]
Q --> D["decide argmax"]
C14. The Bayes Decision Rule
Intuition
Before seeing data you hold a prior belief about each class. After seeing X you update to a posterior. The best you can do is pick the class with the highest posterior.
Using only the prior (“always say the biggest class”) ignores the evidence.
Formal definition
Bayes’ theorem:
p(wi∣X)=p(X)p(X∣wi)p(wi)=∑j=1cp(X∣wj)p(wj)p(X∣wi)p(wi).Bayes decision rule: assign X to wi if p(wi∣X)≥p(wj∣X)∀j=i, equivalently
p(X∣wi)p(wi)≥p(X∣wj)p(wj)∀j=i.
Ties are resolved arbitrarily.
Derivation (why the denominator can be dropped)
p(X)=∑jp(X∣wj)p(wj) is the same for every class, so comparing p(wi∣X)≥p(wj∣X) reduces to comparing numerators. The joint form: p(wi,X)=p(wi∣X)p(X)=p(X∣wi)p(wi).
Special case: two Gaussian classes with common variance (1-D)
Decide w1 iff lnp1−2σ2(x−μ1)2≥lnp2−2σ2(x−μ2)2. Using (x−μ2)2−(x−μ1)2=(μ1−μ2)(2x−μ1−μ2) and assuming μ1<μ2:
x≤2μ1+μ2+μ2−μ1σ2ln(p1/p2).
Key insights
The prior-only rule is a degenerate case (p(X∣wi) ignored).
A larger prior moves the threshold toward the other class’s mean (enlarging its own region).
In practice, p(X∣wi) and p(wi) must be estimated; optimality (C15) holds only if they are right.
Worked examples
Example 1 — Very Easy · Spam with no evidence
Problem: A data set has 300 spam and 700 ham mails. A new mail is classified using only the prior. Which class?
Asked: Prior-only decision.
Concept: Prior rule.
Approach: Priors =0.3,0.7.
Solution:p(ham)=0.7>0.3=p(spam) → ham for every mail.
Final answer: Ham (always).
Key lesson
The prior alone never flags spam — we need the likelihood.
Example 2 — Easy · Evidence overturns the prior
Problem:p(w1)=0.6,p(w2)=0.4; at the observed X: p(X∣w1)=0.2,p(X∣w2)=0.5. Find the posteriors and the decision.
The same data point flips class when priors change.
Example 5 — Very Hard · Same mean, different spread
Problem: Equal priors, f1=N(0,1), f2=N(0,4) (variance 4). Find the decision regions and the Bayes error.
Asked: Regions and error R.
Concept: Unequal variances → two thresholds; R=∫min.
Approach: Compare densities; integrate.
Solution: Decide w1 iff f1≥f2: 2π1e−x2/2≥22π1e−x2/8⟺e−3x2/8≥21⟺x2≤38ln2=1.8484⟺∣x∣≤1.3596. So w1 in the middle, w2 in both tails. Error: R=21[P(∣X∣≤1.3596∣w2)+P(∣X∣>1.3596∣w1)]. Under w2, X/2∼N(0,1): P(∣X∣≤1.3596)=2Φ(0.6798)−1=0.5034. Under w1: 2(1−Φ(1.3596))=0.1740. R=21(0.5034+0.1740)=0.3387.
C15. Probability of Error and Optimality of the Bayes Rule
Intuition
A classifier’s mistakes are the regions where it picks the less likely class. The Bayes rule always picks the more likely one, so it makes the minimum possible total error.
Formal definition
For h:Rm→{w1,w2} with decision regions Ti(h)={X:h(X)=wi}:
R(h)=∫T2(h)p(w1)f1(X)dX+∫T1(h)p(w2)f2(X)dX.
For the Bayes rule:
R(hBayes)=∫min(p(w1)f1(X),p(w2)f2(X))dX.
Derivation (optimality)
Every point X contributes either p(w1)f1 (if placed in T2) or p(w2)f2 (if placed in T1). The smallest possible contribution is the minimum of the two, achieved by placing X in T1 when p(w1)f1≥p(w2)f2 — exactly Bayes. Therefore R(h)≥R(hBayes) for every h. ∎
Closed form for equal-variance Gaussians
fi=N(μi,σ2), μ1<μ2, equal priors; Bayes threshold 2μ1+μ2:
R=21P(X>2μ1+μ2∣w1)+21P(X≤2μ1+μ2∣w2)=21[1−Φ(2σμ2−μ1)]+21Φ(2σμ1−μ2).
Using 1−Φ(z)=Φ(−z), both brackets equal Φ(2σμ1−μ2), so
R=Φ(2σμ1−μ2)=Φ(−2d),d=σ∣μ2−μ1∣.
Key insights
The Bayes error is a floor; no learner (kNN, SVM, NN, …) can beat it with the true distribution.
If the densities are estimated, optimality is no longer guaranteed.
Error shrinks as the means move apart relative to σ.
Worked examples
Example 1 — Very Easy · A discrete feature
Problem: A discrete feature takes values a,b,c. Joint probabilities p(w1,x)=(0.20,0.15,0.05) and p(w2,x)=(0.05,0.10,0.45) for x=a,b,c. Give the Bayes decision per value and the Bayes error.
Asked: Decisions and R.
Concept:R=∑min.
Approach: The larger joint wins; the smaller is the error mass.
Pushing the error from 5 % to 1 % needs ≈41% more separation (4.65/3.29=1.41).
Example 5 — Very Hard · Bayes vs ignoring the prior vs always-majority
Problem:f1=N(0,1), f2=N(2,1), priors 0.8,0.2. Compute (a) the Bayes error; (b) the error of the threshold 1 (which ignores priors); (c) the error of “always w1”.
Bayes beats both the “ignore-prior” threshold and the trivial majority classifier.
Common mistakes
Writing R as an integral of posteriors instead of p(wi)fi (the lecture’s “minimum posterior” means the minimum joint).
Using Φ with the wrong sign.
Exam traps
Optimality needs the true densities; estimated densities may not be optimal.
R=Φ(2σμ1−μ2) requires equal priors and equal variances.
Connections: C14, C16 (bounds), 1-NN vs Bayes (C23).
Mastery checklist
Prove the Bayes rule minimises R.
Derive R=Φ(−d/2).
Compute R with unequal priors.
C16. Chernoff and Bhattacharyya Error Bounds
Intuition
The Bayes error integral ∫min(⋅,⋅) is usually impossible to evaluate. Replace min(u,v) by the smooth upper bound uαv1−α (a geometric-type mean), which does integrate in closed form for Gaussians.
Formal results
For u,v≥0 and 0≤α≤1: min(u,v)≤uαv1−α. Hence
R(h)≤p(w1)αp(w2)1−α∫f1αf21−αdX.
For Gaussians fi=N(μi,Σi): ∫f1αf21−αdX=e−I(α),
I(α)=2α(1−α)(μ2−μ1)T[αΣ1+(1−α)Σ2]−1(μ2−μ1)+21ln∣Σ1∣α∣Σ2∣1−α∣αΣ1+(1−α)Σ2∣.R≤p(w1)αp(w2)1−αe−I(α).
Chernoff bound: minimise the right side over α∈[0,1] (tightest).
Bhattacharyya bound: the easy choice α=21.
Derivation of min(u,v)≤uαv1−α
Suppose u<v (so min=u). Then uαv1−α=u(v/u)1−α≥u because v/u>1 and 1−α≥0. The case v≤u is symmetric (use v(u/v)α≥v). ∎
Special case: equal covariance
Σ1=Σ2=Σ ⇒ log-term =0 and I(α)=2α(1−α)ΔTΣ−1Δ, maximal (so the bound is tightest) at α=21when priors are equal.
Key insights
Every α gives a valid bound; α is a tuning knob.
For equal priors and equal covariances, Chernoff = Bhattacharyya.
If all classes are equally likely and spread identically round their means (a round “ball” of unit variance), the most likely class is simply the class whose mean is nearest.
For Σi=σ2I and unequal priors the rule is: maximise gi(X)=lnp(wi)−2σ2∥X−μi∥2. For general common Σ it is the Mahalanobis-distance rule (X−μi)TΣ−1(X−μi).
Boundary between two means
∥X−μ1∥2=∥X−μ2∥2⟺2XT(μ2−μ1)=∥μ2∥2−∥μ1∥2 — the perpendicular-bisector hyperplane.
Worked examples
Example 1 — Very Easy · Nearest of two means
Problem:μ1=(0,0), μ2=(4,2); classify X=(1,1).
Asked: Class.
Concept: Nearest mean.
Approach: Squared distances.
Solution:d12=1+1=2; d22=9+1=10.
Final answer:w1.
Key lesson
Compare squared distances; no square root needed.
Example 2 — Easy · Three classes
Problem: Means (0,0),(5,0),(0,5); classify (3,1).
Asked: Class.
Concept:c-class nearest mean.
Approach: Three distances.
Solution:d12=10; d22=4+1=5; d32=9+16=25.
Final answer:w2.
Key lesson
Extends directly to c classes.
Example 3 — Moderate · The boundary line
Problem: Equation of the boundary for μ1=(0,0), μ2=(4,2), and which side is w2?
Asked: Boundary.
Concept: Perpendicular bisector.
Approach: Equate squared distances.
Solution:x12+x22=(x1−4)2+(x2−2)2⇒0=−8x1−4x2+20⇒2x1+x2=5. Test μ2: 2(4)+2=10>5 ⇒ w2 side is 2x1+x2>5.
Final answer:2x1+x2=5.
Key lesson
The boundary passes through the midpoint (2,1) (2⋅2+1=5 ✓) and is perpendicular to μ2−μ1=(4,2).
Example 4 — Hard · With a prior
Problem: 1-D, σ2=1, μ1=0,μ2=4, priors 0.8,0.2. Boundary and the class of x=2.2.
Asked: Threshold.
Concept:gi=lnpi−2σ2(x−μi)2.
Approach: Set g1=g2.
Solution:xth=2+4ln4=2.3466. At x=2.2: g1=ln0.8−2.42=−2.6431; g2=ln0.2−1.62=−3.2294. g1>g2.
Final answer: Threshold 2.347; x=2.2→w1 (although 2.2>2, the midpoint).
Key lesson
Plain minimum distance is only the equal-prior special case.
Example 5 — Very Hard · When Euclid is wrong
Problem: Common covariance Σ=diag(9,1), equal priors, μ1=(0,0), μ2=(3,3), X=(0,2). Classify by the Euclidean minimum-distance rule and by the Bayes (Mahalanobis) rule.
Si = np.diag([1/9, 1]); X = np.array([0, 2]); m1 = np.array([0, 0]); m2 = np.array([3, 3])mah = lambda d: d @ Si @ dprint(mah(X - m1), mah(X - m2)) # 4.0 2.0 -> class 2
Key lesson
Features with large variance (here x1) must be discounted; ignoring Σ gives the wrong answer.
Common mistakes
Using it with unequal priors or non-identity covariance.
Mixing up the minimum-distance rule with kNN (it uses means, kNN uses stored points).
Exam traps
Needs three assumptions: Gaussian, Σi=I, equal priors.
Connections: C14, C18, k-means (C36; the assignment step = minimum distance to centroids).
Mastery checklist
Derive the rule from Bayes.
Write the boundary as a hyperplane.
State when Euclidean distance is wrong.
C18. Linear Discriminant Function (Gaussian, Equal Covariance)
Intuition
With two Gaussian classes sharing the same covariance, the quadratic pieces of the log-posteriors cancel, leaving a straight-line (hyperplane) boundary.
Derivation (lecture, with all steps)
fi=N(μi,Σ), i=1,2. Decide w1 iff p1f1≥p2f2. Taking logs (the constant (2π)m∣Σ∣1/21 cancels):
lnp1−21(X−μ1)TΣ−1(X−μ1)≥lnp2−21(X−μ2)TΣ−1(X−μ2).
Expand: −21[XTΣ−1X−2XTΣ−1μi+μiTΣ−1μi] (using XTΣ−1μi=μiTΣ−1X, both scalars, Σ symmetric). The term −21XTΣ−1X appears on both sides and cancels. Rearranging,
lnp2p1≥XTΣ−1(μ2−μ1)+2μ1TΣ−1μ1−μ2TΣ−1μ2.
Equivalently, define
g(X)=wTX+w0,w=Σ−1(μ1−μ2),w0=−21(μ1TΣ−1μ1−μ2TΣ−1μ2)+lnp2p1;
decide w1 iff g≥0.
Python helper for the checks in this section
def ldf(mu1, mu2, Sigma, p1=.5, p2=.5): Si = np.linalg.inv(Sigma); mu1, mu2 = map(np.asarray, (mu1, mu2)) w = Si @ (mu1 - mu2) w0 = -0.5 * (mu1 @ Si @ mu1 - mu2 @ Si @ mu2) + np.log(p1 / p2) return w, w0 # decide class 1 iff w @ x + w0 >= 0
Key insights
The general Bayes boundary p1f1=p2f2 is quadratic; it becomes linear iff Σ1=Σ2.
The normal w=Σ−1(μ1−μ2) is generally not parallel to μ1−μ2.
Priors only shift the intercept.
Worked examples
Example 1 — Very Easy · Identity covariance
Problem:Σ=I, μ1=(0,0),μ2=(2,2), equal priors. Find g.
Example 4 — Hard · Unequal variances give a parabola
Problem:f1=N(0,1), f2=N(2,4) (variance 4), equal priors. Show the boundary is quadratic and find the decision region of w1.
Asked: Boundary roots.
Concept: Unequal covariance ⇒ quadratic.
Approach: Log-likelihood difference.
Solution:g=lnf1−lnf2=21ln4−2x2+8(x−2)2=1.1931−0.5x−0.375x2. Roots: 0.375x2+0.5x−1.1931=0⇒x=0.75−0.5±1.4282, i.e. x=1.2376 or x=−2.5709. g>0 between the roots (e.g. g(0)=1.19).
Final answer:w1 iff −2.571≤x≤1.238; w2 elsewhere.
Example 5 — Very Hard · Correlated features tilt the line
Problem:Σ=(2112), μ1=(0,0), μ2=(2,0), equal priors. (a) Find the boundary line. (b) Is it the perpendicular bisector of the means? (c) Classify (1.1,1) with both the LDF and Euclidean nearest mean.
Asked: Line, comparison, two decisions.
Concept:w=Σ−1Δμ differs from Δμ.
Approach: Invert Σ.
Solution:Σ−1=31(2−1−12). μ1−μ2=(−2,0) ⇒ w=(−34,32). The midpoint (1,0) lies on the boundary: g(X)=−34(x1−1)+32x2. Boundary: x2=2(x1−1). (b) The perpendicular bisector is the vertical line x1=1; slope 2=∞ ⇒ not the bisector. (c) g(1.1,1)=0.5333>0⇒w1. Euclid: d12=2.21, d22=1.81⇒w2.
Final answer: Boundary x2=2(x1−1); LDF → w1, Euclid → w2.
Estimating p(x1,…,xm∣w) directly needs exponentially many numbers. Naive Bayes assumes features are independent given the class, so the joint becomes a product of simple one-feature distributions — cheap to estimate, surprisingly effective.
flowchart TD
W((class w)) --> X1[x₁]
W --> X2[x₂]
W --> X3[x₃]
W --> Xm[x_m]
Given the class, the features do not talk to each other — only the class points to them.
Formal derivation (lecture)
p(wk∣X)∝p(wk,X)=p(x1∣x2,…,xm,wk)p(x2∣x3,…,xm,wk)⋯p(xm∣wk)p(wk)
(chain rule). Naive assumption: p(xi∣xi+1,…,xm,wk)=p(xi∣wk). Therefore
p(wk∣X)∝p(wk)∏i=1mp(xi∣wk),wmap=argmaxkp(wk)∏i=1mp(xi∣wk).Log version (avoids floating-point underflow):
wmap=argmaxk[lnp(wk)+∑i=1mlnp(xi∣wk)].
Priors: p(wk)=total#samples in wk.
Key insights
Parameters: with m binary features and c classes: cm+(c−1) vs c(2m−1)+(c−1) for the full joint.
The unnormalised scores suffice for the decision; normalise only if you need a probability.
Example 3 — Moderate · 200 tiny probabilities
Problem: A model has m=200 features; every p(xi∣w1)=0.01 and every p(xi∣w2)=0.02; equal priors. Why does the product fail, and how do logs fix it?
Asked: Failure and fix.
Concept: Underflow.
Approach: Magnitudes.
Solution:0.01200=10−400 and 0.02200≈10−340. Double precision underflows below ≈10−308 (denormals to ≈5×10−324), so both products become 0 ⇒ tie ⇒ arbitrary. Logs: ln0.5+200ln0.01=−921.73; ln0.5+200ln0.02=−783.10.
Final answer: Class 2 (score −783.1>−921.7); only the log computation sees it.
Sum logs; never multiply many small probabilities.
Example 4 — Hard · A duplicated feature double-counts
Problem: Equal priors. A feature f has p(f∣w1)=0.6, p(f∣w2)=0.2. The same feature accidentally appears twice (perfectly correlated). Compare the true posterior of w1 with Naive Bayes’s.
Solution: True: P(w1∣f)=0.80.6=0.75. NB with two copies: 0.36+0.040.36=0.90.
Final answer:0.75 vs NB’s 0.90.
Key lesson
NB is over-confident when features are correlated, but the argmax is unchanged (still w1).
Example 5 — Very Hard · Counting parameters
Problem: (a) Count free parameters for c=2 classes with m=10 binary features, full joint vs Naive Bayes. (b) Prove NB’s MAP rule equals the Bayes rule when the independence assumption holds.
Asked: Counts and proof.
Concept: Complexity; relation to Bayes.
Approach: Count; substitute.
Solution: (a) Full: each class has a joint over 210=1024 cells with 1023 free parameters ⇒ 2046, plus 1 prior ⇒ 2047. NB: 2×10=20, plus 1 prior ⇒ 21. (b) The Bayes rule maximises p(wk)p(X∣wk). If features are conditionally independent, p(X∣wk)=∏ip(xi∣wk) exactly; substituting gives the NB rule — identical. When independence is false, NB maximises a different (misspecified) quantity.
Final answer:2047 vs 21 parameters; NB = Bayes under conditional independence.
Key lesson
The “naive” assumption trades bias for a huge reduction in parameters and variance.
Common mistakes
Assuming unconditional independence (it is conditional on the class).
Multiplying many probabilities instead of summing logs.
For numeric features, model each feature within each class as a bell curve, with its own mean and variance estimated from the training data.
Formal definition
p(xi∣wk)=2πσik21exp{−2σik2(xi−μik)2},
with μik,σik2 the sample mean and variance of feature i among class-k samples. Log form:
lnp(xi∣wk)=−21ln(2πσik2)−2σik2(xi−μik)2.
(The maximum-likelihood variance divides by nk; an unbiased estimate divides by nk−1.)
Key insights
If all σik2 are equal across classes, the lnσ terms cancel; the rule becomes a (weighted) nearest-mean rule.
Unequal variances ⇒ quadratic boundary (the wide class wins in the tails).
A zero variance (constant feature in a class) breaks the formula — add a small floor.
Worked examples
Example 1 — Very Easy · Peak height
Problem: Density of N(μ,σ2=4) at x=μ.
Asked:p.
Concept: Gaussian pdf.
Approach: The exponent is 0.
Solution:2π⋅41=5.0131=0.1995.
Final answer:0.1995.
Key lesson
Peak height =1/(σ2π).
Example 2 — Easy · Estimating parameters
Problem: Class A values of a feature: 1,2,3. Estimate μ,σ2 (MLE).
Asked: Parameters.
Concept: Estimation.
Approach: Mean, mean squared deviation.
Solution:μ=2; σ2=31+0+1=0.6667 (unbiased: 1.0).
Final answer:μ=2, σ2=0.667 (MLE).
Key lesson
State which variance estimator you use.
Example 3 — Moderate · One feature, equal variance
Problem: Class A: μ=2,σ2=32; class B: μ=7,σ2=32; equal priors. Classify x=4.
Asked: Class.
Concept: 1-feature Gaussian NB.
Approach: Log-scores.
Solution: Same σ ⇒ compare 2σ2(x−μ)2: A: 1.33334=3.0; B: 1.33339=6.75. Smaller ⇒ A.
Distance measured in standard deviations (3σA vs 2σB) matters, not raw distance.
Common mistakes
Forgetting the lnσ term when variances differ.
Zero variance → division by zero.
Exam traps
Gaussian NB for continuous features; multinomial / Bernoulli for discrete (counts / binary).
Connections: C14, C19, C21–C22.
Mastery checklist
Estimate μik,σik2.
Classify with log-scores.
Explain the unequal-variance effect.
C21. Multinomial Naive Bayes and Laplace (Add-One) Smoothing
Intuition
For text, a feature is a word and its value is how often it occurs. A class is summarised as a “bag” of its words; p(word∣class) is the word’s share of that class’s word-tokens.
A word never seen in a class would zero out the whole product — so we pretend we saw every word once.
Formal definition
Let Fik = total frequency of term i in all class-k documents; m = vocabulary size.
p(xi∣wk)=∑j=1mFjkFik(raw);p(xi∣wk)=∑j=1mFjk+mFik+1(Laplace).
Test document: each occurrence of a term contributes one factor.
Derivation (Laplace form)
Add 1 to every one of the m counts: numerator Fik+1; denominator ∑j(Fjk+1)=∑jFjk+m. The smoothed probabilities sum to 1: ∑i∑jFjk+mFik+1=∑jFjk+m∑iFik+m=1. ∎
Key insights
Smoothing shrinks estimates toward the uniform value 1/m; strongest for small classes.
Repeated words in a test document are counted repeatedly (multinomial) — unlike Bernoulli (C22).
Worked example corpus (used in all five)
Class c (3 docs): “Chinese Beijing Chinese”, “Chinese Chinese Shanghai”, “Chinese Macao”. Class j (1 doc): “Tokyo Japan Chinese”. Vocabulary ={Chinese, Beijing, Shanghai, Macao, Tokyo, Japan}, m=6. Test: “Chinese Chinese Chinese Tokyo Japan”.
Counts. Class c: Chinese 5, Beijing 1, Shanghai 1, Macao 1, Tokyo 0, Japan 0 → total 8. Class j: Chinese 1, Tokyo 1, Japan 1, others 0 → total 3. Priors p(c)=43,p(j)=41.
Python helper for this section and C22
from sklearn.feature_extraction.text import CountVectorizerfrom sklearn.naive_bayes import MultinomialNB, BernoulliNBdocs = ["Chinese Beijing Chinese", "Chinese Chinese Shanghai", "Chinese Macao", "Tokyo Japan Chinese"]labels = ["c", "c", "c", "j"]cv = CountVectorizer(lowercase=False); X = cv.fit_transform(docs)test = cv.transform(["Chinese Chinese Chinese Tokyo Japan"])
Example 1 — Very Easy · The zero-frequency problem
Problem: Raw p(Tokyo∣c); what happens to a test document containing Tokyo?
Asked: Value and consequence.
Concept: Zero-frequency problem.
Approach:F/∑F.
Solution:80=0. Any product containing it is 0.
Final answer:0; class c would be impossible for that document.
Final answer: Smoothed → c; unsmoothed → j (a spurious veto).
Key lesson
Smoothing can change the decision; unsmoothed zeros are not evidence.
Example 5 — Very Hard · Properties of Laplace smoothing
Problem: (a) Prove the smoothed class-k probabilities sum to 1 for m terms. (b) A new class k′ has zero training tokens. What are its probabilities? (c) How would the Example 3 posterior change if a seventh vocabulary word “Osaka” (never seen) is added so m=7?
Asked: Proof and two computations.
Concept: Laplace’s properties.
Approach: Direct.
Solution: (a) shown in the Derivation. (b) 0+m0+1=m1 for every term — uniform. (c) c denominator 8+7=15: Chinese 156, Tokyo 151, Japan 151; j denominator 3+7=10: each 102. Scores: c: 0.75(156)3(151)2=2.133×10−4; j: 0.25(0.2)5=8.0×10−5. P(c∣d)=2.133+0.82.133=0.727.
Final answer: Uniform m1 for an empty class; with m=7, class c still wins, posterior 0.727 (up from 0.690).
Key lesson
Vocabulary size m appears in the denominator — it controls how much probability mass goes to unseen words.
Common mistakes
Adding 1 only to zero counts.
Using the number of documents instead of the vocabulary size m in the denominator.
Forgetting that repeated words count repeatedly.
Exam traps
Denominator: ∑jFjk+m (Lecture eq. 8.9).
The ratio of probabilities, not their absolute values, determines the class.
Connections: C19, C22 (Bernoulli), text classification.
Mastery checklist
Apply Laplace smoothing.
Do the full Chinese / Tokyo example.
Explain why zeros are dangerous.
C22. Bernoulli Naive Bayes
Intuition
Record only whether a word occurs in a document (yes / no), ignoring how often. Each word is a coin flip per document, with a class-specific head probability.
Formal definition
p(xi∣wk) = fraction of class-k documents containing term i. With smoothing (standard form): p(ti∣wk)=Nk+2Nik+1, where Nik = number of class-k docs containing ti, Nk = class-k document count. A test document d is scored by
p(wk)∏i∈presentp(ti∣wk)∏i∈absent(1−p(ti∣wk))
(the full Bernoulli model also penalises absent words). The lecture notes that Bernoulli uses only binary occurrence information and “makes mistakes on long documents”, so it is used for short texts.
Key insights
Multinomial counts repeats; Bernoulli does not.
Absent terms contribute evidence in the Bernoulli model.
The smoothing form (N+1)/(Nk+2) is the two-outcome Laplace analogue.
Worked example corpus (same as C21)
Class c docs: {Chinese, Beijing}, {Chinese, Shanghai}, {Chinese, Macao}; class j doc: {Chinese, Tokyo, Japan}. Test doc (presence): {Chinese, Tokyo, Japan}.
Example 1 — Very Easy · Document frequencies
Problem: Raw p(Chinese∣c) and p(Beijing∣c).
Asked: Two fractions.
Concept: Document-frequency estimate.
Approach: Docs containing the term / class docs.
Solution: Chinese in 3 of 3 ⇒ 1. Beijing in 1 of 3 ⇒ 31.
Final answer:1,0.333.
Key lesson
Probabilities are per-document, not per-token.
Example 2 — Easy · Smoothed table
Problem: Smoothed p(t∣c) and p(t∣j) for all six terms.
b = BernoulliNB(alpha=1, binarize=0).fit(X, labels) # sklearn's BernoulliNB is the full modelprint(b.classes_, b.predict_proba(test)) # P(j|d) = 0.8089
Key lesson
Absent words push toward j because class c “expects” Beijing / Shanghai / Macao, yet they are missing.
Example 5 — Very Hard · Why the two models disagree
Problem: The multinomial model (C21 Ex. 3) said c; the Bernoulli model says j. Explain the discrepancy and say which is appropriate for (a) tweets, (b) 5000-word articles.
Asked: Reasoned comparison.
Concept: Counts vs presence.
Approach: Identify what each model uses.
Solution: The word “Chinese” appears 3 times in the test text. Multinomial multiplies p(Chinese∣c)=146 three times, and since c makes “Chinese” very likely it earns a large reward. Bernoulli sees “Chinese present” once; its decisive evidence is Tokyo / Japan present (favouring j) and the absence of Beijing / Shanghai / Macao. (a) Tweets are short: presence / absence is informative and Bernoulli works well. (b) In long documents most words occur at least once, so presence saturates; the lecture warns Bernoulli errs on long documents ⇒ multinomial.
Final answer: Different modelling assumptions ⇒ different predictions; Bernoulli for short texts, multinomial for long.
Key lesson
Choose the model whose generative story matches your data.
Common mistakes
Ignoring absent terms in the full Bernoulli model.
Using token counts in Bernoulli.
Exam traps
“Bernoulli errs on long documents” (lecture).
Smoothing uses +2 in the denominator for Bernoulli (binary event), +m for multinomial.