PIXELBANKv9.1.0
Menu

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 format:

  • Line 1: Number of training documents N
  • Lines 2 to N+1: label followed by the document text (space-separated words)
  • Line N+2: Test document (space-separated words)

Output: The predicted class label.

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:

Training counts:

  • pos: 2 docs, words: [I, love, this, movie, great, film, wonderful] = 7 words
  • neg: 2 docs, words: [terrible, movie, awful, bad, film, horrible] = 6 words
  • Vocabulary size |V| = 11 unique words

Priors: P(pos) = 2/4 = 0.5, P(neg) = 2/4 = 0.5

Test doc: "I love this film" For class "pos": log(0.5) + log(P("I"|pos)) + log(P("love"|pos)) + log(P("this"|pos)) + log(P("film"|pos)) Each P(w|pos) uses (count+1)/(7+11) = (count+1)/18

For class "neg": similar but lower scores for "I", "love", "this"

Result: pos has higher score.

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
🔒

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

0/0
Run code to see test results.
Naive Bayes Classifier - Medium | PixelBank