Study Vault Search notes, aliases and full text
Graph
TopicDBISAI-written · not yet proofread

Naive Bayes Classification

Classifying documents with Bayes' theorem and the assumption that words are independent given the class: training by counting, smoothing, prediction by an argmax over class scores.

Concepts#

  1. Naive Bayes Classifiermodel, training by relative frequencies, prediction (also in log space), linearity start here
  2. Laplace Smoothingavoids zero probabilities for unseen words
  3. Maximum Likelihood Estimationwhy the relative frequencies are the best parameters for the observed data

Prerequisites from the foundations: Bayes’ Theorem, Conditional Probability, Statistical Independence.

How it fits together#

  • Chain: Bayes’ Theorem turns Pr⁡(c∣d)\Pr(c \mid d) into Pr⁡(d∣c)Pr⁡(c)/Pr⁡(d)\Pr(d \mid c)\Pr(c)/\Pr(d); Pr⁡(d)\Pr(d) is constant over classes and dropped; conditional independence of the words factorizes Pr⁡(d∣c)\Pr(d \mid c) into the pwcp_{wc}.
  • Where things go wrong: a word never seen in class cc zeroes its score. Laplace Smoothing repairs this; the log-space implementation needs it, and avoids underflow of long products.
  • Implementation patterns in the exams:
VariantIdeaExam
for-loops over word_idsmultiply pcp_c and pwcp_{wc}, argmax, tie by larger idWS 17/18
matrix-vector productrow cc of MM is log⁡pwc\log p_{wc} plus log⁡pc\log p_c, vector is counts plus a 11WS 19/20
word to id map, return class and probabilityproduct per class, track bestWS 22/23
  • Naive Bayes is linear. With two classes the prediction is w⋅x>bw \cdot x > b for word counts xx (Linear Classifier); this links the topic to Linear Classifiers and Logistic Regression, where the same decision rule is learned directly instead of via counting.
  • Prior vs. evidence: repeating a document multiplies the word evidence but not the prior, so only with equal priors is the prediction unchanged.

Key Formulas#

  • Prediction: c^(d)=arg⁡max⁡c pc∏w∈dpwc\hat c(d) = \arg\max_c\, p_c \prod_{w \in d} p_{wc} (Naive Bayes Classifier)
  • Training: pc=#docsc/#docsp_c = \#\text{docs}_c / \#\text{docs}, pwc=nwc/ncp_{wc} = n_{wc}/n_c
  • Smoothing: pwc=(nwc+α)/(nc+α∣V∣)p_{wc} = (n_{wc} + \alpha)/(n_c + \alpha|V|) (Laplace Smoothing)

Exercises & Exam Questions#

SuccessSolution (not in the exam note; written by Claude)
def naive_bayes_predict(pc, pwc, word_ids):
    best, best_p = 0, -1
    for c in range(len(pc)):
        p = pc[c]
        for w in word_ids:
            p *= pwc[c][w]
        if p >= best_p:          # >= : ties go to the larger id
            best, best_p = c, p
    return best
SuccessSolution (written by Claude)

Let sc(d1)=p⋅Qcs_c(d_1) = p \cdot Q_c with the common prior pp and Qc=∏w∈d1pwcQ_c = \prod_{w \in d_1} p_{wc}. Then sc(d2)=p⋅Qc2s_c(d_2) = p \cdot Q_c^2. For Qc≥0Q_c \ge 0, Qc↦Qc2Q_c \mapsto Q_c^2 is strictly increasing, so Qc≤Qc′  ⟺  Qc2≤Qc′2Q_c \le Q_{c'} \iff Q_c^2 \le Q_{c'}^2, and the ordering of the classes (also the tie-breaking) is the same.

SuccessSolution (written by Claude)

No. Two classes, pA=0.9p_A = 0.9, pB=0.1p_B = 0.1, one word ww with pwA=0.2p_{wA} = 0.2, pwB=0.5p_{wB} = 0.5. For d1=(w)d_1 = (w): 0.9⋅0.2=0.18>0.1⋅0.5=0.050.9 \cdot 0.2 = 0.18 > 0.1 \cdot 0.5 = 0.05, predicts AA. For d2=(w,w)d_2 = (w, w): 0.9⋅0.04=0.036<0.1⋅0.25=0.0250.9 \cdot 0.04 = 0.036 < 0.1 \cdot 0.25 = 0.025? No, 0.036>0.0250.036 > 0.025, so adjust: take pwA=0.1p_{wA} = 0.1, pwB=0.5p_{wB} = 0.5 and pA=0.6p_A = 0.6, pB=0.4p_B = 0.4. d1d_1: 0.06<0.20.06 < 0.2 predicts BB … use instead pwA=0.5p_{wA} = 0.5, pwB=0.4p_{wB} = 0.4, pA=0.4p_A = 0.4, pB=0.6p_B = 0.6: d1d_1: 0.20.2 vs 0.240.24 gives BB; d2d_2: 0.10.1 vs 0.0960.096 gives AA. The prediction changes, because the prior is not squared.

SuccessSolution (written by Claude)

4.3: see the second example in Naive Bayes Classifier > Example: pX=1/3p_X = 1/3, pY=2/3p_Y = 2/3, p1X=3/4p_{1X} = 3/4, p2X=1/4p_{2X} = 1/4, p1Y=1/4p_{1Y} = 1/4, p2Y=3/4p_{2Y} = 3/4, so w=(ln⁡3,−ln⁡3)w = (\ln 3, -\ln 3), b=ln⁡2b = \ln 2. 4.4: need b=0b = 0 and w1=−w2>0w_1 = -w_2 > 0. Take equal class sizes (pX=pYp_X = p_Y) and a point (1,0)(1, 0) labeled XX and a point (0,1)(0, 1) labeled YY: p1X=1p_{1X} = 1, p2X=0p_{2X} = 0, p1Y=0p_{1Y} = 0, p2Y=1p_{2Y} = 1 (smooth with the same ε\varepsilon if zero probabilities are a concern, giving w=(ln⁡r,−ln⁡r)w = (\ln r, -\ln r) with r>1r > 1 and b=0b = 0).

SuccessSolution
def smoothing(pwc, eps):
    for pw in pwc:
        for i in range(len(pw)):
            pw[i] += eps
        sum_pw = sum(pw)
        for i in range(len(pw)):
            pw[i] /= sum_pw
  1. Non-zero: adding eps > 0 makes every entry strictly positive; dividing by a positive sum keeps it so.
  2. Order: pa<pb⇒pa+ε<pb+εp_a < p_b \Rightarrow p_a + \varepsilon < p_b + \varepsilon, and dividing by the same positive constant preserves the strict inequality.
  3. Distribution: after dividing by sum_pw=∑i(pi+ε)\text{sum\_pw} = \sum_i (p_i + \varepsilon) the entries of each class sum to 1.
SuccessSolution
def predict(doc, pwc, pc):
    doc.append(1)
    for i in range(len(pwc)):
        pwc[i].append(pc[i])
        for j in range(len(pwc[i])):
            pwc[i][j] = math.log(pwc[i][j])
    predictions = pwc * doc
    return argmax(predictions)

Appending 11 to the document and pc[i]p_c[i] to row ii puts the prior into the dot product. The logarithm turns ∏jp(wj∣c)nj⋅p(c)\prod_j p(w_j \mid c)^{n_j} \cdot p(c) into ∑jnjlog⁡p(wj∣c)+log⁡p(c)\sum_j n_j \log p(w_j \mid c) + \log p(c), which is the dot product of the log row with the document vector. argmax returns the class with the highest log-probability.

SuccessSolution
  1. 8 numbers are even, 8 odd: pA=pB=1/2p_A = p_B = 1/2.
  2. All documents have 4 words, so nA=nB=8⋅4=32n_A = n_B = 8 \cdot 4 = 32.
  3. Class AA (even): the last bit is always 00; each of the other three positions has four 00s and four 11s. Count of word 00: 8+4+4+4=208 + 4 + 4 + 4 = 20; of word 11: 0+4+4+4=120 + 4 + 4 + 4 = 12.
  4. Class BB (odd): the last bit is always 11. Count of word 00: 1212; of word 11: 2020.
  5. p0∣A=20/32=5/8p_{0|A} = 20/32 = 5/8, p1∣A=3/8p_{1|A} = 3/8, p0∣B=3/8p_{0|B} = 3/8, p1∣B=5/8p_{1|B} = 5/8.
  6. For “0 0 0 1”: Pr⁡(A∣0001)Pr⁡(B∣0001)=pA p0∣A3 p1∣ApB p0∣B3 p1∣B=(5/8)3(3/8)(3/8)3(5/8)=5232=259>1\dfrac{\Pr(A \mid 0001)}{\Pr(B \mid 0001)} = \dfrac{p_A\, p_{0|A}^3\, p_{1|A}}{p_B\, p_{0|B}^3\, p_{1|B}} = \dfrac{(5/8)^3 (3/8)}{(3/8)^3 (5/8)} = \dfrac{5^2}{3^2} = \dfrac{25}{9} > 1, so class AA is predicted. ■\blacksquare
SuccessSolution
def predict(doc, wordIds, pwc, pc):
    c_best, p_best = -1, -1
    for c in range(0, len(pc)):
        p = pc[c]
        for w in doc:
            wid = wordIds[w]
            p = p * pwc[c][wid]
        if p > p_best:
            c_best, p_best = c, p
    return c_best, p_best

For each class, P(c)⋅∏w∈docP(w∣c)P(c) \cdot \prod_{w \in \text{doc}} P(w \mid c) is computed using the conditional-independence assumption; the best class is tracked and returned with its score. (Tasks 4.2 and 4.3 of this exam are about a web page that calls this function, see Web Applications.)

Occurrence table#

SemesterTaskPointsSubtopics
WS 16/17 (not published)Task 4.3–4.410 of 20learning step, ww and bb of the linear classifier, constructing an input
WS 17/18 (not published)Task 420predict with for-loops, document repetition proofs
WS 19/20 (not published)Task 4.2–4.320 of 25smoothing function, prediction as matrix-vector product
WS 21/22 (not published)Task 4.310 of 25training on binary numbers, ratio of posteriors
WS 22/23 (not published)Task 4.110 of 20predict with word-id map, returns class and probability

Lectures#

No WS 25/26 lecture covers this topic. It appears only in older Information Retrieval exams (last in WS 22/23).

Search

Type In
↑ ↓ move ↵ open ⇥ next section Ctrl↵ results page Prefix # to search text only