v9.1.1
Menu

Naive Bayes Classifier

mediumPROText ClassificationNLP 2: Applications

Implement a Naive Bayes text classifier.

Training: Given labeled documents, compute:

  • Prior: P(c)=count of docs in class ctotal docsP(c) = \frac{\text{count of docs in class c}}{\text{total docs}}
  • Likelihood: P(w∣c)=count of w in class c+1total words in class c+∣V∣P(w|c) = \frac{\text{count of w in class c} + 1}{\text{total words in class c} + |V|} (Laplace smoothing)

Where |V| is the vocabulary size (unique words across all documents).

Prediction: For a test document, compute: arg⁡max⁡c[log⁡P(c)+∑w∈doclog⁡P(w∣c)]\arg\max_c \left[ \log P(c) + \sum_{w \in doc} \log P(w|c) \right]

Input:

  • train_docs: a list of training documents, each a list of words
  • train_labels: a list of class labels (strings), one per training document
  • test_doc: the document to classify, as a list of words

Output: The predicted class label (a string).

Example

Input
4
pos I love this movie
pos great film wonderful
neg terrible movie awful
neg bad film horrible
I love this film
Output
pos
Reasoning
  • Inputs: four training documents (two pos, two neg), each a list of words, and the test document I, love, this, film. Labels are plain strings.
  • Counts: the pos documents hold 7 words in total, the neg documents hold 6, and there are ∣V∣=11|V| = 11 distinct words across all four documents. Both priors are P(c)=2/4=0.5P(c) = 2/4 = 0.5.
  • Smoothed likelihoods: for pos the denominator is 7+11=187 + 11 = 18. Each of I, love, this, film appears once, so each gets 1+118=19\frac{1+1}{18} = \frac{1}{9}. For neg the denominator is 6+11=176 + 11 = 17: I, love, this never appear, giving 117\frac{1}{17} each, while film appears once, giving 217\frac{2}{17}.
  • Log scores: log⁡0.5+4log⁡19≈−0.6931−8.7889=−9.4820\log 0.5 + 4\log\frac{1}{9} \approx -0.6931 - 8.7889 = -9.4820 for pos, and log⁡0.5+3log⁡117+log⁡217≈−11.3329\log 0.5 + 3\log\frac{1}{17} + \log\frac{2}{17} \approx -11.3329 for neg.
  • Output: pos has the larger (less negative) score, so the answer is pos. Notice that add-1 smoothing keeps the unseen words in neg from making its probability zero; they only pull the score down.

Constraints

  • Use Laplace smoothing (add-1) for likelihoods
  • Use log probabilities to avoid underflow
  • Words are already lowercase
  • If a test word is not in training vocab, skip it
  • Labels are strings

Learn this in

More from NLP 2: Applications

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.