Classify word-count vectors with multinomial Naive Bayes

Why it matters Naive Bayes on word counts is still a strong, explainable baseline for spam, intent and support-ticket routing, and it trains in one pass.

Multinomial Naive Bayes is the classic fast baseline for spam filters and text classifiers built on word counts.

Write multinomial_nb(X_train, y_train, X_test, alpha=1.0). X_train is (n, V) word counts, y_train integer labels, X_test (m, V). For each class c (sorted): log prior = log(n_c / n), and word probabilities theta_cv = (count_cv + alpha) / (total_c + alpha * V), where count_cv is the total count of word v in class c and total_c the total count of all words in class c. The score of a test row x for class c is log prior_c + sum_v x_v log theta_cv. Return (pred, scores): pred is a list of predicted labels (highest score, smaller label on ties) and scores is the (m, C) float array.

Signaturedef multinomial_nb(X_train, y_train, X_test, alpha=1.0)

Example

X_train [[2, 1, 0], [1, 0, 0], [0, 1, 3], [0, 0, 2]], y_train [0, 0, 1, 1], X_test [[1, 0, 1]] gives pred [0] and scores [[-3.198673, -3.295837]] (rounded).

Understand the idea

Naive Bayes asks: if this email were spam, how likely are its words? It pretends every word is chosen independently, which is wrong but works surprisingly well. Multiplying many small probabilities underflows, so we add logs instead.

Laplace smoothing adds alpha fake counts to every word in every class, so a word never seen in a class does not make its probability exactly zero.

Worked example: class 0 has word counts [3, 1, 0] (4 words total), V = 3, alpha = 1. Then theta = (3 + 1) / (4 + 3), (1 + 1) / 7, (0 + 1) / 7 = 4/7, 2/7, 1/7. For a test row with one word 0 and one word 2, the class 0 score is log(0.5) + log(4/7) + log(1/7), with prior 0.5.

Rule: theta_cv = (count_cv + alpha) / (total_c + alpha * V), score_c = log prior_c + sum_v x_v log theta_cv.

This model still powers many spam filters and quick text baselines because it is fast and easy to explain.

Shapes and data flow

X (n, V) -> theta (C, V) -> scores (m, C)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: examplemultinomial_nb([[2, 1, 0], [1, 0, 0], [0, 1, 3], [0, 0, 2]], [0, 0, 1, 1], [[1, 0, 1]])
  • Sample 2: unseen wordmultinomial_nb([[3, 0, 0, 0], [0, 2, 0, 0], [0, 1, 1, 0]], [5, 7, 7], [[0, 0, 0, 2], [1, 1, 0, 0]], 0.5)
  • Test 3: randommultinomial_nb(_X, _y, _Xt)