Level 5 — MasterySVM, Naive Bayes & Probabilistic Models

SVM, Naive Bayes & Probabilistic Models

90 minutes60 marksprintable — key stays hidden on paper

Level: 5 — Mastery (cross-domain: math + probability + coding) Time limit: 90 minutes Total marks: 60

Instructions: Answer all questions. Show full derivations. Use ...... for math. Code may be written in Python (NumPy / scikit-learn style pseudocode acceptable but must be runnable in spirit).


Question 1 — SVM: Derive and Interpret the Margin (24 marks)

Consider a binary classification dataset with linearly separable points {(xi,yi)}\{(\mathbf{x}_i, y_i)\}, yi{1,+1}y_i \in \{-1, +1\}, and a separating hyperplane wx+b=0\mathbf{w}^\top \mathbf{x} + b = 0.

(a) Starting from the geometry of the hyperplane, prove that the perpendicular distance from a point xi\mathbf{x}_i to the hyperplane is wxi+bw\dfrac{|\mathbf{w}^\top\mathbf{x}_i + b|}{\|\mathbf{w}\|}, and hence show that maximizing the margin is equivalent to minimizing 12w2\tfrac{1}{2}\|\mathbf{w}\|^2 subject to yi(wxi+b)1y_i(\mathbf{w}^\top\mathbf{x}_i + b) \ge 1. (6)

(b) Write the primal soft-margin optimization problem with slack variables ξi\xi_i and penalty CC. Explain precisely, using the KKT conditions, what the value of the dual variable αi\alpha_i tells us about whether point ii is: (i) correctly classified beyond the margin, (ii) exactly on the margin, or (iii) inside the margin / misclassified. (8)

(c) Consider the tiny 1-D dataset: positive points at x=2,3x = 2, 3; negative points at x=1,0x = -1, 0. Working by hand, find the maximum-margin separator wx+b=0w x + b = 0, the margin width, and identify the support vectors. (6)

(d) Explain the kernel trick: why we can replace xixj\mathbf{x}_i^\top\mathbf{x}_j with K(xi,xj)K(\mathbf{x}_i,\mathbf{x}_j) without ever computing the feature map ϕ\phi. For the polynomial kernel K(x,z)=(xz+1)2K(\mathbf{x},\mathbf{z})=(\mathbf{x}^\top\mathbf{z}+1)^2 in 2-D, explicitly write the feature map ϕ(x)\phi(\mathbf{x}) it corresponds to. (4)


Question 2 — Naive Bayes: Derivation, Smoothing & Text (24 marks)

(a) State the Naive Bayes conditional-independence assumption formally, and derive the classification rule y^=argmaxcP(c)jP(xjc)\hat{y}=\arg\max_c P(c)\prod_j P(x_j\mid c) from Bayes' theorem. Explain why we can drop the denominator P(x)P(\mathbf{x}). (5)

(b) For a spam classifier trained on the token counts below (Multinomial NB), compute — with Laplace (add-1) smoothing — the class-conditional probabilities and classify the test document "free money".

Class free money meeting total tokens
spam 3 3 0 6
ham 1 1 4 6

Vocabulary size V=3V = 3. Priors: P(spam)=P(ham)=0.5P(\text{spam}) = P(\text{ham}) = 0.5. Show all smoothed probabilities and the final decision. (9)

(c) Explain why Laplace smoothing is necessary here — give the concrete failure that occurs without it, and state how the smoothing parameter interacts with VV as VV \to \infty. (4)

(d) Write a short, correct Python function predict_log_proba(counts, priors, likelihoods) that classifies a document using log-probabilities (to avoid numerical underflow) for a Multinomial NB. Explain in one sentence why working in log-space is essential for long documents. (6)


Question 3 — Cross-Model Reasoning (12 marks)

(a) Gaussian Naive Bayes models each P(xjc)=N(xj;μjc,σjc2)P(x_j\mid c)=\mathcal{N}(x_j;\mu_{jc},\sigma_{jc}^2). Show that if all classes share the same covariance, the resulting decision boundary between two classes is linear, and relate this to how an RBF-kernel SVM differs (i.e., why RBF-SVM can be nonlinear). (6)

(b) Contrast the roles of the SVM hyperparameters CC and γ\gamma (RBF) with the effect of the smoothing parameter α\alpha in Naive Bayes, framing all three in terms of the bias–variance tradeoff. State what happens at extreme values. (6)

Answer keyMark scheme & solutions

Question 1

(a) (6 marks)

  • The hyperplane is wx+b=0\mathbf{w}^\top\mathbf{x}+b=0; w\mathbf{w} is normal to it. For any point xi\mathbf{x}_i, decompose xi=xp+rww\mathbf{x}_i = \mathbf{x}_p + r\frac{\mathbf{w}}{\|\mathbf{w}\|} where xp\mathbf{x}_p lies on the hyperplane. (2)
  • Substituting: wxi+b=wxp+b+rw=0+rw\mathbf{w}^\top\mathbf{x}_i + b = \mathbf{w}^\top\mathbf{x}_p + b + r\|\mathbf{w}\| = 0 + r\|\mathbf{w}\|, so r=wxi+bwr = \frac{\mathbf{w}^\top\mathbf{x}_i+b}{\|\mathbf{w}\|}, distance =wxi+bw=\frac{|\mathbf{w}^\top\mathbf{x}_i+b|}{\|\mathbf{w}\|}. (2)
  • With canonical scaling so margin points satisfy wx+b=1|\mathbf{w}^\top\mathbf{x}+b|=1, margin half-width =1w=\frac{1}{\|\mathbf{w}\|}; maximizing 2w\frac{2}{\|\mathbf{w}\|} \equiv minimizing 12w2\frac12\|\mathbf{w}\|^2 s.t. yi(wxi+b)1y_i(\mathbf{w}^\top\mathbf{x}_i+b)\ge1. (2)

(b) (8 marks) Primal: minw,b,ξ 12w2+Ciξi\min_{\mathbf{w},b,\xi}\ \frac12\|\mathbf{w}\|^2 + C\sum_i\xi_i s.t. yi(wxi+b)1ξi, ξi0y_i(\mathbf{w}^\top\mathbf{x}_i+b)\ge 1-\xi_i,\ \xi_i\ge0. (3) KKT interpretation (complementary slackness αi[yi(wxi+b)1+ξi]=0\alpha_i[y_i(\mathbf{w}^\top\mathbf{x}_i+b)-1+\xi_i]=0, and (Cαi)ξi=0(C-\alpha_i)\xi_i=0): (5, ~1.6 each)

  • (i) αi=0\alpha_i = 0: point beyond margin, yif(xi)>1y_i f(\mathbf{x}_i) > 1, ξi=0\xi_i=0not a support vector.
  • (ii) 0<αi<C0 < \alpha_i < C: point exactly on the margin, ξi=0\xi_i=0, yif=1y_i f=1 — free support vector.
  • (iii) αi=C\alpha_i = C: point inside margin or misclassified, ξi>0\xi_i>0 — bounded support vector.

(c) (6 marks)

  • Nearest opposite points: positive x=2x=2, negative x=0x=0. Boundary midway at x=1x=1. (2)
  • With canonical constraints w2+b=+1w\cdot2 + b = +1 and w0+b=1w\cdot0 + b = -1: subtract → 2w=2w=12w=2 \Rightarrow w=1, b=1b=-1. Boundary x=1x=1. ✓ (2)
  • Margin width =2w=2=\frac{2}{\|w\|}=2 (half-width 1). Support vectors: x=2x=2 (+) and x=0x=0 (−); x=3,1x=3,-1 are not. (2)

(d) (4 marks)

  • The dual objective and decision function depend on data only through inner products xixj\mathbf{x}_i^\top\mathbf{x}_j; replacing with K=ϕ(xi)ϕ(xj)K=\phi(\mathbf{x}_i)^\top\phi(\mathbf{x}_j) gives the high-dim solution without materializing ϕ\phi (Mercer kernel). (2)
  • For x=(x1,x2)\mathbf{x}=(x_1,x_2): (xz+1)2=1+2x1z1+2x2z2+x12z12+x22z22+2x1x2z1z2(\mathbf{x}^\top\mathbf{z}+1)^2 = 1 + 2x_1z_1 + 2x_2z_2 + x_1^2z_1^2 + x_2^2z_2^2 + 2x_1x_2z_1z_2, so ϕ(x)=(1, 2x1, 2x2, x12, x22, 2x1x2).\phi(\mathbf{x}) = (1,\ \sqrt2 x_1,\ \sqrt2 x_2,\ x_1^2,\ x_2^2,\ \sqrt2 x_1x_2). (2)

Question 2

(a) (5 marks)

  • Assumption: features conditionally independent given class: P(x1,,xnc)=jP(xjc)P(x_1,\dots,x_n\mid c)=\prod_j P(x_j\mid c). (2)
  • Bayes: P(cx)=P(c)P(xc)P(x)P(c\mid\mathbf{x}) = \frac{P(c)P(\mathbf{x}\mid c)}{P(\mathbf{x})}; apply independence → P(c)jP(xjc)\propto P(c)\prod_j P(x_j\mid c). (2)
  • P(x)P(\mathbf{x}) is constant across classes, so it doesn't affect the argmax\arg\max. (1)

(b) (9 marks) Smoothed likelihood: P(wc)=count(w,c)+1totalc+VP(w\mid c) = \frac{\text{count}(w,c)+1}{\text{total}_c + V}, denom =6+3=9=6+3=9. (2)

  • Spam: P(free)=49P(\text{free})=\frac{4}{9}, P(money)=49P(\text{money})=\frac{4}{9}. (2)
  • Ham: P(free)=29P(\text{free})=\frac{2}{9}, P(money)=29P(\text{money})=\frac{2}{9}. (2)
  • Score spam =0.54949=0.51681=8810.0988= 0.5\cdot\frac{4}{9}\cdot\frac{4}{9} = 0.5\cdot\frac{16}{81}=\frac{8}{81}\approx0.0988.
  • Score ham =0.52929=0.5481=2810.0247= 0.5\cdot\frac{2}{9}\cdot\frac{2}{9} = 0.5\cdot\frac{4}{81}=\frac{2}{81}\approx0.0247. (2)
  • Spam score > ham score → classify as SPAM. (1)

(c) (4 marks)

  • Without smoothing, "meeting" absent in spam would give P(meetingspam)=0P(\text{meeting}\mid\text{spam})=0, zeroing the entire product regardless of other evidence — a single unseen word vetoes the class. (2)
  • Add-α\alpha: count+αtotal+αV\frac{count+\alpha}{total+\alpha V}; as VV\to\infty with fixed counts, each probability \to uniform-ish/tiny, smoothing dominates and washes out evidence — must keep α\alpha small relative to counts. (2)

(d) (6 marks)

import numpy as np
def predict_log_proba(counts, priors, likelihoods):
    # counts: dict token->freq in doc
    # priors: {class: P(class)}, likelihoods: {class: {token: P(token|class)}}
    scores = {}
    for c in priors:
        s = np.log(priors[c])
        for tok, n in counts.items():
            s += n * np.log(likelihoods[c][tok])  # log of product = sum of logs
        scores[c] = s
    return max(scores, key=scores.get)

(5) for correct log-space summation and argmax. One sentence (1): multiplying many probabilities <1<1 underflows to 0 in floating point; summing logs stays representable.


Question 3

(a) (6 marks)

  • logP(cx)=logP(c)12(xμc)Σ1(xμc)+const\log P(c\mid x) = \log P(c) - \frac12(x-\mu_c)^\top\Sigma^{-1}(x-\mu_c)+\text{const}. (2)
  • With shared Σ\Sigma, the quadratic term xΣ1xx^\top\Sigma^{-1}x cancels in the log-ratio between two classes, leaving a term linear in xx → linear boundary (this is LDA). (2)
  • RBF-SVM maps to an infinite-dimensional feature space where linear separation corresponds to nonlinear boundaries in input space; γ\gamma controls the locality of that mapping, allowing curved decision regions. (2)

(b) (6 marks)

  • CC: penalty on margin violations. Large CC → low bias, high variance (hard margin, overfits noise); small CC → high bias, wider soft margin. (2)
  • γ\gamma (RBF): inverse kernel width. Large γ\gamma → very local, high variance/overfit; small γ\gamma → smooth, high bias. (2)
  • α\alpha (NB smoothing): large α\alpha → pulls estimates toward uniform, high bias, low variance; α0\alpha\to0 → trusts sparse counts, low bias, high variance (zero-probability instability). (2)
[
  {"claim":"1D SVM: w=1,b=-1 gives correct canonical constraints and margin width 2",
   "code":"w,b=1,-1; c1=(w*2+b==1); c2=(w*0+b==-1); margin=Rational(2,abs(w)); result=bool(c1 and c2 and margin==2)"},
  {"claim":"Multinomial NB spam score exceeds ham score for 'free money'",
   "code":"ps=Rational(1,2)*Rational(4,9)*Rational(4,9); ph=Rational(1,2)*Rational(2,9)*Rational(2,9); result=bool(ps>ph and ps==Rational(8,81) and ph==Rational(2,81))"},
  {"claim":"Laplace smoothed P(free|spam)=4/9 with add-1, V=3, total=6",
   "code":"p=Rational(3+1,6+3); result=bool(p==Rational(4,9))"},
  {"claim":"Poly kernel expansion (x.z+1)^2 has 6 monomial terms matching phi",
   "code":"x1,x2,z1,z2=symbols('x1 x2 z1 z2'); K=expand((x1*z1+x2*z2+1)**2); phi=[1,sqrt(2)*x1,sqrt(2)*x2,x1**2,x2**2,sqrt(2)*x1*x2]; psi=[1,sqrt(2)*z1,sqrt(2)*z2,z1**2,z2**2,sqrt(2)*z1*z2]; dot=expand(sum(a*b for a,b in zip(phi,psi))); result=bool(simplify(dot-K)==0)"}
]