Classify binary feature vectors with Bernoulli Naive Bayes

Why it matters Bernoulli NB suits short texts and yes/no feature sets such as app permissions or symptom checklists, where absence is informative.

Bernoulli Naive Bayes models whether each feature is present or absent, so a missing word is evidence too.

Write bernoulli_nb(X_train, y_train, X_test, alpha=1.0). Binarise inputs with x > 0. For each class c (sorted): log prior = log(n_c / n) and p_cv = (number of class c rows with feature v present + alpha) / (n_c + 2 * alpha). The score of test row x is log prior_c + sum_v [x_v log p_cv + (1 - x_v) log(1 - p_cv)]. Return (pred, scores) like multinomial NB: a list of labels (smaller label on ties) and an (m, C) float array.

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

Example

X_train [[1, 1, 0], [1, 0, 0], [0, 1, 1], [0, 0, 1]], y_train [0, 0, 1, 1], X_test [[1, 1, 0], [0, 1, 1]] gives pred [0, 1] and scores [[-1.961659, -4.158883], [-4.158883, -1.961659]] (rounded).

Understand the idea

Bernoulli Naive Bayes looks at every feature as a yes/no question: does this message contain the word 'offer'? Unlike the multinomial version, a word that does not appear also counts as evidence. If spam emails almost always say 'offer', an email without it is a little less likely to be spam.

Worked example: class 0 has 2 rows and feature 'offer' appears in both. With alpha = 1, p = (2 + 1) / (2 + 2) = 0.75. A test email without 'offer' gets log(1 - 0.75) = log(0.25) added to its class 0 score, a penalty. With the word present it would get log(0.75).

Rule: p_cv = (present count + alpha) / (n_c + 2 alpha); score_c = log prior_c + sum_v [x_v log p_cv + (1 - x_v) log(1 - p_cv)].

Bernoulli NB works well for short texts and checklists. For long documents with repeated words, the multinomial version that uses counts is usually better.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

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

  • Sample 1: examplebernoulli_nb([[1, 1, 0], [1, 0, 0], [0, 1, 1], [0, 0, 1]], [0, 0, 1, 1], [[1, 1, 0], [0, 1, 1]])
  • Sample 2: absence decidesbernoulli_nb([[1, 1, 1], [1, 1, 1], [1, 0, 0], [1, 0, 0]], [0, 0, 1, 1], [[1, 0, 0], [1, 1, 0]])
  • Test 3: counts binarisedbernoulli_nb([[3, 0], [5, 2], [0, 4]], [1, 1, 2], [[7, 0], [0, 9]], 0.5)
  • Test 4: randombernoulli_nb(_X, _y, _Xt)