Incremental Naive Bayes Text Classifier

Quick Overview

Implement a multinomial Naive Bayes text classifier whose partial_fit updates class and word counts batch by batch without revisiting earlier data. It tests sufficient statistics, additive smoothing over a growing vocabulary, log-sum-exp normalization and matching scikit-learn's MultinomialNB.

Incremental Naive Bayes Text Classifier

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement `IncrementalTextNB`, a multinomial Naive Bayes over raw strings. `partial_fit(docs, labels)` accumulates running document counts per class and word counts per class, without storing or reprocessing earlier batches. All derived properties are recomputed from these counts over the current vocabulary. Requirements: - Tokenize with `text.lower().split()`. `classes_` is a sorted `np.array` and `vocabulary_` is a sorted `list`. Classes and words first seen in later batches are merged in. - `class_count_` has shape `(C,)` and `feature_count_` has shape `(C, V)` (float). `feature_log_prob_` = `log((count + alpha) / (class_total + alpha*V))`, with `V` the current vocabulary size. - `class_log_prior_` holds the log of the empirical document frequencies, or a uniform prior when `fit_prior=False`. - Prediction ignores out-of-vocabulary tokens. `predict_log_proba` normalizes with log-sum-exp and stays finite for long documents. `predict` breaks ties toward the smallest label. - `fit` resets state, then calls `partial_fit`. Both return `self`. A length mismatch raises `ValueError`. Accessing `classes_` or predicting before any fit raises `RuntimeError`. Example: ```python m = IncrementalTextNB(alpha=1.0) m.partial_fit(["a b", "a"], ["x", "y"]) m.vocabulary_ # ['a', 'b'] m.feature_log_prob_ # log([[1/2, 1/2], [2/3, 1/3]]) m.partial_fit(["c"], ["x"]) m.vocabulary_ # ['a', 'b', 'c'] m.feature_log_prob_ # log([[1/3, 1/3, 1/3], [1/2, 1/4, 1/4]]) m.class_log_prior_ # log([2/3, 1/3]) ``` Results must match `sklearn.naive_bayes.MultinomialNB` trained on the equivalent count matrix. ```hint What to keep between batches Ask which quantities add up across batches. Keep only those, and compute every matrix from them at the moment it is read. ``` ```hint Watch class y in the example Class `y` gets no new documents in the second batch, yet its row of `feature_log_prob_` changes. Work out which term in the formula moved. ``` ```hint Long documents A joint log-likelihood for a long document can be in the thousands below zero. Think about what subtracting the same constant from every class's score does before you exponentiate. ``` ### What a Strong Answer Covers - Which statistics are stored between batches, and why they are enough to reproduce a single fit on all the data seen so far. - How a growing vocabulary changes the smoothing denominator for every class, including classes absent from the latest batch. - Handling of out-of-vocabulary tokens, label ties, and the `ValueError` and `RuntimeError` cases. - A numerically stable normalization of the posteriors for long documents. - The cost of an update compared with the cost of building the parameters and predicting. ### Follow-up Questions - How would you keep memory bounded as the vocabulary grows without limit? - How would you adapt the model to concept drift in a stream? - Why can caching `feature_log_prob_` between batches be wrong?

Overview: Implement a multinomial Naive Bayes text classifier whose partial_fit updates class and word counts batch by batch without revisiting earlier data. It tests sufficient statistics, additive smoothing over a growing vocabulary, log-sum-exp normalization and matching scikit-learn's MultinomialNB.

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

Implement IncrementalTextNB, a multinomial Naive Bayes over raw strings. partial_fit(docs, labels) accumulates running document counts per class and word counts per class, without storing or reprocessing earlier batches. All derived properties are recomputed from these counts over the current vocabulary.

Requirements:

  • Tokenize with text.lower().split() . classes_ is a sorted np.array and vocabulary_ is a sorted list . Classes and words first seen in later batches are merged in.
  • class_count_ has shape (C,) and feature_count_ has shape (C, V) (float). feature_log_prob_ = log((count + alpha) / (class_total + alpha*V)) , with V the current vocabulary size.
  • class_log_prior_ holds the log of the empirical document frequencies, or a uniform prior when fit_prior=False .
  • Prediction ignores out-of-vocabulary tokens. predict_log_proba normalizes with log-sum-exp and stays finite for long documents. predict breaks ties toward the smallest label.
  • fit resets state, then calls partial_fit . Both return self . A length mismatch raises ValueError . Accessing classes_ or predicting before any fit raises RuntimeError .

Example:

m = IncrementalTextNB(alpha=1.0)
m.partial_fit(["a b", "a"], ["x", "y"])
m.vocabulary_          # ['a', 'b']
m.feature_log_prob_    # log([[1/2, 1/2], [2/3, 1/3]])
m.partial_fit(["c"], ["x"])
m.vocabulary_          # ['a', 'b', 'c']
m.feature_log_prob_    # log([[1/3, 1/3, 1/3], [1/2, 1/4, 1/4]])
m.class_log_prior_     # log([2/3, 1/3])

Results must match sklearn.naive_bayes.MultinomialNB trained on the equivalent count matrix.

What a Strong Answer Covers Guidance

  • Which statistics are stored between batches, and why they are enough to reproduce a single fit on all the data seen so far.
  • How a growing vocabulary changes the smoothing denominator for every class, including classes absent from the latest batch.
  • Handling of out-of-vocabulary tokens, label ties, and the ValueError and RuntimeError cases.
  • A numerically stable normalization of the posteriors for long documents.
  • The cost of an update compared with the cost of building the parameters and predicting.

Follow-up Questions Guidance

  • How would you keep memory bounded as the vocabulary grows without limit?
  • How would you adapt the model to concept drift in a stream?
  • Why can caching feature_log_prob_ between batches be wrong?