Naive Bayes Classifier
Implement a Naive Bayes text classifier.
Training: Given labeled documents, compute:
- Prior:
- Likelihood: (Laplace smoothing)
Where |V| is the vocabulary size (unique words across all documents).
Prediction: For a test document, compute:
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
4 pos I love this movie pos great film wonderful neg terrible movie awful neg bad film horrible I love this film
pos
- Inputs: four training documents (two
pos, twoneg), each a list of words, and the test document I, love, this, film. Labels are plain strings. - Counts: the
posdocuments hold 7 words in total, thenegdocuments hold 6, and there are distinct words across all four documents. Both priors are . - Smoothed likelihoods: for
posthe denominator is . Each of I, love, this, film appears once, so each gets . Fornegthe denominator is : I, love, this never appear, giving each, while film appears once, giving . - Log scores: for
pos, and forneg. - Output:
poshas the larger (less negative) score, so the answer ispos. Notice that add-1 smoothing keeps the unseen words innegfrom 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