Sparse Batch Prediction for Multinomial Naive Bayes

Quick Overview

Implement multinomial Naive Bayes that fits and scores dense or scipy.sparse count matrices without densifying them, matching scikit-learn's MultinomialNB. It tests the linear form of the log-likelihood, sparse-dense matrix products, stable log-sum-exp normalization and tie-breaking on sorted labels.

Sparse Batch Prediction for Multinomial Naive Bayes

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement a class `SparseMultinomialNB` with the methods `fit`, `joint_log_likelihood`, `predict_log_proba`, `predict_proba` and `predict`. Every method accepts either a dense array or a `scipy.sparse` matrix. Sparse inputs must be scored with a sparse-dense matrix product and never densified. Requirements: - `fit` sets `classes_` (sorted unique labels), `class_count_`, `feature_count_`, `class_log_prior_` (empirical) and `feature_log_prob_` (shape `(k, d)`, additive `alpha` smoothing). It returns `self`. - `joint_log_likelihood` returns a dense `(n, k)` float64 `ndarray`. - Sparse inputs must not call `toarray`, `todense` or `__array__`. - `predict_log_proba` must stay finite and normalized for very large counts, so use a numerically stable log-sum-exp. - `predict` returns labels from `classes_`. Ties go to the smallest label. Example: ```python from scipy.sparse import csr_matrix X = [[2, 1, 0], [0, 1, 3], [1, 0, 0]] y = [0, 1, 0] nb = SparseMultinomialNB(alpha=1.0).fit(X, y) # nb.class_log_prior_ -> log([2/3, 1/3]) # nb.feature_log_prob_ -> log([[4/7, 2/7, 1/7], # [1/7, 2/7, 4/7]]) nb.predict_proba(csr_matrix((1, 3))) # -> [[0.6667, 0.3333]] (an empty document gets the prior) ``` ```hint Shape of the score Write out the log of the multinomial likelihood for one document and look at what kind of function of the count vector it is. That tells you what scoring a whole batch turns into. ``` ```hint Counting per class The per-class feature counts can also be a single matrix product if you encode the labels as a matrix first. ``` ```hint Long documents For a document with millions of tokens every class score is a huge negative number. Think about what exponentiating those directly does, and what you can subtract from every score in a row without changing the normalized result. ``` ### Constraints & Assumptions - Features are non-negative counts, and `alpha > 0`. - Labels may be any sortable type (ints, strings). - Results must match `sklearn.naive_bayes.MultinomialNB` with `force_alpha=True`. - Inputs are 2-D: a dense array or a `scipy.sparse` matrix in any format. ### What a Strong Answer Covers - Why the batch joint log-likelihood is one matrix product plus the class log-prior, and why zero counts need no work. - Sparse-safe fitting of the per-class counts and smoothed log-probabilities, using the same formulas as scikit-learn. - Stable normalization with log-sum-exp, and why the naive version fails for long documents. - Tie-breaking through sorted classes, and the dense float64 return type of `joint_log_likelihood`. - Time and space complexity in terms of the number of stored non-zeros, classes and features. ### Follow-up Questions - How would you support `partial_fit` for streaming batches? - Why is `X @ feature_log_prob_.T` efficient for CSR input, and what changes for CSC input? - What breaks if `alpha = 0`?

Overview: Implement multinomial Naive Bayes that fits and scores dense or scipy.sparse count matrices without densifying them, matching scikit-learn's MultinomialNB. It tests the linear form of the log-likelihood, sparse-dense matrix products, stable log-sum-exp normalization and tie-breaking on sorted labels.

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

Implement a class SparseMultinomialNB with the methods fit, joint_log_likelihood, predict_log_proba, predict_proba and predict. Every method accepts either a dense array or a scipy.sparse matrix. Sparse inputs must be scored with a sparse-dense matrix product and never densified.

Requirements:

  • fit sets classes_ (sorted unique labels), class_count_ , feature_count_ , class_log_prior_ (empirical) and feature_log_prob_ (shape (k, d) , additive alpha smoothing). It returns self .
  • joint_log_likelihood returns a dense (n, k) float64 ndarray .
  • Sparse inputs must not call toarray , todense or __array__ .
  • predict_log_proba must stay finite and normalized for very large counts, so use a numerically stable log-sum-exp.
  • predict returns labels from classes_ . Ties go to the smallest label.

Example:

from scipy.sparse import csr_matrix

X = [[2, 1, 0], [0, 1, 3], [1, 0, 0]]
y = [0, 1, 0]
nb = SparseMultinomialNB(alpha=1.0).fit(X, y)
# nb.class_log_prior_  -> log([2/3, 1/3])
# nb.feature_log_prob_ -> log([[4/7, 2/7, 1/7],
#                              [1/7, 2/7, 4/7]])
nb.predict_proba(csr_matrix((1, 3)))
# -> [[0.6667, 0.3333]]   (an empty document gets the prior)

Constraints & Assumptions

  • Features are non-negative counts, and alpha > 0 .
  • Labels may be any sortable type (ints, strings).
  • Results must match sklearn.naive_bayes.MultinomialNB with force_alpha=True .
  • Inputs are 2-D: a dense array or a scipy.sparse matrix in any format.

What a Strong Answer Covers Guidance

  • Why the batch joint log-likelihood is one matrix product plus the class log-prior, and why zero counts need no work.
  • Sparse-safe fitting of the per-class counts and smoothed log-probabilities, using the same formulas as scikit-learn.
  • Stable normalization with log-sum-exp, and why the naive version fails for long documents.
  • Tie-breaking through sorted classes, and the dense float64 return type of joint_log_likelihood .
  • Time and space complexity in terms of the number of stored non-zeros, classes and features.

Follow-up Questions Guidance

  • How would you support partial_fit for streaming batches?
  • Why is X @ feature_log_prob_.T efficient for CSR input, and what changes for CSC input?
  • What breaks if alpha = 0 ?