Naive Bayes Text Classifier

medium
Checkpoint challenge
Solve this to show you know the material and jump straight to Unit 4. Everything before it counts as cleared.

Multinomial Naive Bayes is a fast, surprisingly strong baseline for text classification such as spam detection or ticket routing.

Implement a class NaiveBayes(alpha=1.0):

  • fit(docs, labels): tokenise each document by lowercasing and splitting on whitespace. Learn:
    • the class prior P(c)P(c) = fraction of documents with label cc;
    • word likelihoods with Laplace smoothing: P(w∣c)=count(w,c)+αtotal words in c+α⋅∣V∣P(w \mid c) = \dfrac{\text{count}(w, c) + \alpha}{\text{total words in } c + \alpha \cdot |V|}, where ∣V∣|V| is the vocabulary size across all training documents.
    • Return self.
  • predict(doc): return the class maximising log⁡P(c)+∑wlog⁡P(w∣c)\log P(c) + \sum_{w} \log P(w \mid c) over the document's words, counting repeats. Ignore words not in the vocabulary. Break ties by the class that sorts first.

Work in log space so long documents don't underflow.

#classification#nlp#probability2 visible + 3 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
Naive Bayes Text Classifier · TechGradify