Bernoulli Naive Bayes From Scratch

Quick Overview

Implement a Bernoulli naive Bayes classifier from scratch in NumPy whose priors, feature log-probabilities and posteriors match scikit-learn's BernoulliNB. Tests smoothing, scoring of absent features, vectorized log-likelihoods and stable log-sum-exp normalization.

Bernoulli Naive Bayes From Scratch

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement a `BernoulliNaiveBayes` class with the constructor `BernoulliNaiveBayes(alpha=1.0, binarize=0.0, fit_prior=True, class_prior=None)` and the methods `fit`, `joint_log_likelihood`, `predict_log_proba`, `predict_proba` and `predict`. Both present and absent features must contribute to each class score, and the outputs must match `sklearn.naive_bayes.BernoulliNB`. The class must follow these rules: - Binarize as `x > binarize` (strict, so a value equal to the threshold maps to 0). `binarize=None` uses the input as is. - `fit(X, y)` returns `self` and sets `classes_` (sorted), `class_count_`, `feature_count_`, `feature_log_prob_ = log((count + alpha) / (N_c + 2*alpha))` and `class_log_prior_`. - The prior is `class_prior` if given, else the empirical class frequencies if `fit_prior` is true, else uniform. - The score methods return arrays of shape `(n_samples, n_classes)` and stay finite when joint log-likelihoods fall below -700. - `predict` breaks posterior ties toward the smallest class label. Example: ```python X = [[1, 0, 1], [1, 1, 0], [0, 0, 1]]; y = [1, 1, 0] m = BernoulliNaiveBayes(alpha=1.0).fit(X, y) m.class_log_prior_ # log([1/3, 2/3]) m.feature_log_prob_ # log([[1/3, 1/3, 2/3], [3/4, 1/2, 1/2]]) ``` ```hint Absent features Expand the per-feature term for $x_j \in \{0, 1\}$ and look for a way to score every sample with one matrix product plus a constant per class. ``` ```hint Very negative scores In float64, `exp` of a number far below -700 underflows to zero. Normalize in log space, and think about what to subtract from each row before exponentiating. ``` ### Constraints & Assumptions - Only `numpy` may be used. - Labels can be any sortable type, such as ints or strings. ### What a Strong Answer Covers - Counts, smoothing and the three prior options, matching `BernoulliNB` attribute by attribute - How each class score accounts for absent features, and how to compute it for all samples at once - Posterior normalization that stays finite for very negative joint log-likelihoods - The tie rule in `predict` and support for string labels - Time and space complexity ### Follow-up Questions - Why can't you just drop the absent-feature terms as in multinomial naive Bayes? - How would you support sparse input with thousands of features efficiently?

Overview: Implement a Bernoulli naive Bayes classifier from scratch in NumPy whose priors, feature log-probabilities and posteriors match scikit-learn's BernoulliNB. Tests smoothing, scoring of absent features, vectorized log-likelihoods and stable log-sum-exp normalization.

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

Implement a BernoulliNaiveBayes class with the constructor BernoulliNaiveBayes(alpha=1.0, binarize=0.0, fit_prior=True, class_prior=None) and the methods fit, joint_log_likelihood, predict_log_proba, predict_proba and predict. Both present and absent features must contribute to each class score, and the outputs must match sklearn.naive_bayes.BernoulliNB.

The class must follow these rules:

  • Binarize as x > binarize (strict, so a value equal to the threshold maps to 0). binarize=None uses the input as is.
  • fit(X, y) returns self and sets classes_ (sorted), class_count_ , feature_count_ , feature_log_prob_ = log((count + alpha) / (N_c + 2*alpha)) and class_log_prior_ .
  • The prior is class_prior if given, else the empirical class frequencies if fit_prior is true, else uniform.
  • The score methods return arrays of shape (n_samples, n_classes) and stay finite when joint log-likelihoods fall below -700.
  • predict breaks posterior ties toward the smallest class label.

Example:

X = [[1, 0, 1], [1, 1, 0], [0, 0, 1]]; y = [1, 1, 0]
m = BernoulliNaiveBayes(alpha=1.0).fit(X, y)
m.class_log_prior_   # log([1/3, 2/3])
m.feature_log_prob_  # log([[1/3, 1/3, 2/3], [3/4, 1/2, 1/2]])

Constraints & Assumptions

  • Only numpy may be used.
  • Labels can be any sortable type, such as ints or strings.

What a Strong Answer Covers Guidance

  • Counts, smoothing and the three prior options, matching BernoulliNB attribute by attribute
  • How each class score accounts for absent features, and how to compute it for all samples at once
  • Posterior normalization that stays finite for very negative joint log-likelihoods
  • The tie rule in predict and support for string labels
  • Time and space complexity

Follow-up Questions Guidance

  • Why can't you just drop the absent-feature terms as in multinomial naive Bayes?
  • How would you support sparse input with thousands of features efficiently?