A probabilistic text classifier that predicts the class c maximizing p_c times the product of the word probabilities p_wc over the words of the document, assuming that the words are independent given the class.
Derivation. By Bayes’ Theorem, Pr(c∣d)=Pr(d∣c)Pr(c)/Pr(d). The denominator Pr(d) is the same for all classes and drops out of the argmax. The naive assumption is that the words of d are independent given the class, so Pr(d∣c)=∏w∈dPr(w∣c) (conditional independence). Together:
Pr(c∣d)∝pc⋅w∈d∏pwc.
Training (learning step) on labelled documents, by relative frequencies:
pc=#training documents#training documents of class c,pwc=ncnwc,
where nwc is the number of occurrences of w in all training documents of class c and nc=∑w∈Vnwc is the total number of word occurrences in class c.
Prediction in log space.log is strictly increasing, so
c^(d)=argcmax(logpc+w∈V∑nw(d)⋅logpwc).
With the matrix M∈R∣C∣×(∣V∣+1) whose row c is (logpw1c,…,logpw∣V∣c,logpc) and the document vector x=(nw1(d),…,nw∣V∣(d),1), all class scores are one matrix-vector product M⋅x, and c^(d)=argmax(M⋅x) (exam WS 19/20, Task 4.3).
Zero probabilities. If a word w of d never occurs in the training documents of class c, then pwc=0 and the score of c is 0, whatever the other words say. If every class has such a word, all scores are 0. Smoothing fixes this, and it is also needed for the log-space version (log0 is undefined).
Naive Bayes is a Linear Classifier. For two classes X,Y it predicts X iff
w∈V∑nw(d)(logpwX−logpwY)>logpY−logpX,
i.e. iff w⋅x>b with x=(nw(d))w∈V, weights wi=log(pwiX/pwiY) and threshold b=log(pY/pX). The decision boundary is a hyperplane in the space of word-count vectors.
Document length and the prior. Repeating a document k times raises the word part of the score to the k-th power but leaves pc unchanged: sc(dk)=pc⋅(∏w∈dpwc)k. With equal priors the prediction is invariant under repetition; with unequal priors the word evidence outweighs the prior for long enough documents, so the prediction can change (exam WS 17/18, Task 4.2–4.3).
Rounding. A product of many probabilities <1 underflows to 0 in floating point. The log-space sum avoids this.
Ties must be broken by a fixed rule (e.g. by the larger class id, exam WS 17/18, Task 4).