Bernoulli Naive Bayes as a Linear Classifier

Quick Overview

Fit a binary Bernoulli naive Bayes model in NumPy and convert its log-parameters into a weight vector and bias that reproduce its log-odds exactly. Tests the derivation of the linear form, scikit-learn compatible smoothing, and a numerically stable way to compute log(1 - p).

Bernoulli Naive Bayes as a Linear Classifier

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement three NumPy functions that fit a binary Bernoulli naive Bayes model and turn it into an equivalent linear classifier. - `fit_bernoulli_nb(X, y, alpha=1.0, binarize=0.0)` fits the model and returns `(classes, class_log_prior, feature_log_prob)`. - `bernoulli_linear_boundary(class_log_prior, feature_log_prob)` converts the log-parameters into `(weights, bias)` so that `x @ weights + bias` equals the log-odds `log P(classes[1] | x) - log P(classes[0] | x)`. - `predict_linear(X, weights, bias, classes, binarize=0.0)` predicts labels with that linear score. The functions must follow these rules: - Binarize features as `X > binarize` (strict). `binarize=None` leaves `X` unchanged. - `classes = np.unique(y)` (sorted). `class_log_prior` is the log of the empirical class frequencies. `feature_log_prob[c] = log((count_c + alpha) / (n_c + 2*alpha))` with shape `(2, n_features)`, where `n_c` is the number of samples in class `c` and `count_c` is how many of them have the feature present. Both must match sklearn's `BernoulliNB`. - Return `weights` as a 1-D array and `bias` as a Python `float`. - `predict_linear` returns `classes[1]` when the score is `> 0` and `classes[0]` otherwise, including a score of exactly 0. - Raise `ValueError` when `y` does not have exactly 2 classes, or when the parameters passed to `bernoulli_linear_boundary` are not binary (the prior must have shape `(2,)` and the log-probabilities must be 2-D with 2 rows). Example: ```python X = [[1, 0], [1, 1], [0, 1], [0, 0]] y = [0, 0, 1, 1] classes, class_log_prior, feature_log_prob = fit_bernoulli_nb(X, y, alpha=1.0) # classes -> [0, 1] # class_log_prior -> log([0.5, 0.5]) # feature_log_prob -> log([[0.75, 0.5], [0.25, 0.5]]) weights, bias = bernoulli_linear_boundary(class_log_prior, feature_log_prob) # weights -> [-2*log(3), 0.0] # bias -> log(3) predict_linear([[1, 0]], weights, bias, classes) # -> [0], because the score is -2*log(3) + log(3) = -log(3) ``` ```hint One feature at a time Write the class-conditional log-likelihood of a single binary feature as an expression in $x_j$, then separate the part that multiplies $x_j$ from the part that does not. ``` ```hint The all-zeros input Score the vector with no features present. Its log-odds is usually not the prior ratio, and that tells you what has to go into the bias. ``` ```hint Only log p is given The boundary function receives log-probabilities, so you need $\log(1 - p)$ from $\log p$. Check what a naive formula does when p is very close to 1 and when it is very close to 0. ``` ### What a Strong Answer Covers - A derivation showing that the log-odds is linear in the binarized features, including what happens to the evidence term - How the absent-feature terms enter the weights and the bias - Fitting that matches `BernoulliNB` smoothing, priors and binarization exactly - A numerically safe way to get $\log(1 - p)$ from $\log p$ - The tie rule at a zero score, the input validation, and the cost of each function ### Follow-up Questions - Why does the bias depend on every feature, unlike in multinomial naive Bayes? - How do you keep the conversion numerically stable when probabilities approach 1? - How would this generalize to K classes?

Overview: Fit a binary Bernoulli naive Bayes model in NumPy and convert its log-parameters into a weight vector and bias that reproduce its log-odds exactly. Tests the derivation of the linear form, scikit-learn compatible smoothing, and a numerically stable way to compute log(1 - p).

PracHub logo
General
Nov 25, 2026
mediumMachine Learning EngineerOtherMachine Learning
0
0

Implement three NumPy functions that fit a binary Bernoulli naive Bayes model and turn it into an equivalent linear classifier.

  • fit_bernoulli_nb(X, y, alpha=1.0, binarize=0.0) fits the model and returns (classes, class_log_prior, feature_log_prob) .
  • bernoulli_linear_boundary(class_log_prior, feature_log_prob) converts the log-parameters into (weights, bias) so that x @ weights + bias equals the log-odds log P(classes[1] | x) - log P(classes[0] | x) .
  • predict_linear(X, weights, bias, classes, binarize=0.0) predicts labels with that linear score.

The functions must follow these rules:

  • Binarize features as X > binarize (strict). binarize=None leaves X unchanged.
  • classes = np.unique(y) (sorted). class_log_prior is the log of the empirical class frequencies. feature_log_prob[c] = log((count_c + alpha) / (n_c + 2*alpha)) with shape (2, n_features) , where n_c is the number of samples in class c and count_c is how many of them have the feature present. Both must match sklearn's BernoulliNB .
  • Return weights as a 1-D array and bias as a Python float .
  • predict_linear returns classes[1] when the score is > 0 and classes[0] otherwise, including a score of exactly 0.
  • Raise ValueError when y does not have exactly 2 classes, or when the parameters passed to bernoulli_linear_boundary are not binary (the prior must have shape (2,) and the log-probabilities must be 2-D with 2 rows).

Example:

X = [[1, 0], [1, 1], [0, 1], [0, 0]]
y = [0, 0, 1, 1]
classes, class_log_prior, feature_log_prob = fit_bernoulli_nb(X, y, alpha=1.0)
# classes          -> [0, 1]
# class_log_prior  -> log([0.5, 0.5])
# feature_log_prob -> log([[0.75, 0.5], [0.25, 0.5]])

weights, bias = bernoulli_linear_boundary(class_log_prior, feature_log_prob)
# weights -> [-2*log(3), 0.0]
# bias    -> log(3)

predict_linear([[1, 0]], weights, bias, classes)
# -> [0], because the score is -2*log(3) + log(3) = -log(3)

What a Strong Answer Covers Guidance

  • A derivation showing that the log-odds is linear in the binarized features, including what happens to the evidence term
  • How the absent-feature terms enter the weights and the bias
  • Fitting that matches BernoulliNB smoothing, priors and binarization exactly
  • A numerically safe way to get log⁡(1−p)\log(1 - p) from log⁡p\log p
  • The tie rule at a zero score, the input validation, and the cost of each function

Follow-up Questions Guidance

  • Why does the bias depend on every feature, unlike in multinomial naive Bayes?
  • How do you keep the conversion numerically stable when probabilities approach 1?
  • How would this generalize to K classes?