Multinomial Naive Bayes Text Classifier

Quick Overview

Implement a multinomial Naive Bayes text classifier in NumPy that builds a vocabulary from raw strings, applies additive smoothing and an optional class prior, and returns stable posterior probabilities. It tests log-space scoring, handling of unseen tokens and alpha=0, and matching scikit-learn's MultinomialNB.

Multinomial Naive Bayes Text Classifier

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement a class `MultinomialNaiveBayes(alpha=1.0, class_prior=None)` that fits on a list of strings and labels, then scores new documents. It has the methods `fit`, `transform`, `joint_log_likelihood`, `predict_log_proba`, `predict_proba` and `predict`. Use smoothing `alpha` and an optional `class_prior`. All outputs are NumPy arrays. Requirements: - Tokenise with `doc.lower().split()`. `vocabulary_` maps sorted training tokens to `0..V-1`, `classes_` holds the sorted unique labels, and `fit` returns `self`. - `class_log_prior_` is the log of empirical class frequencies, or the log of `class_prior` renormalised to sum 1 when given. - `feature_log_prob_` has shape `(n_classes, V)` and equals `log((N_cw + alpha) / (N_c + alpha*V))`, where `N_cw` is the count of word w in class c and `N_c` is the total word count of class c. With `alpha=0`, entries may be `-inf`. - `transform` returns a float count matrix `(n_docs, V)` and ignores unseen tokens. `joint_log_likelihood` is counts · `feature_log_prob_ᵀ` + prior, and a zero count contributes 0 even against `-inf`. - `predict_log_proba` normalises with a stable log-sum-exp, and `predict_proba` is its `exp`. `predict` returns the argmax label, with ties going to the earliest entry in `classes_`. Example: ```python m = MultinomialNaiveBayes(alpha=1.0).fit( ["good good movie", "bad movie", "good fun"], ["pos", "neg", "pos"]) m.classes_ # ['neg', 'pos'] m.vocabulary_ # {'bad': 0, 'fun': 1, 'good': 2, 'movie': 3} m.feature_log_prob_ # log([[2,1,1,2]/6, [1,2,4,2]/9]) m.predict_proba(["xyz unknown", ""]) # [[1/3, 2/3], [1/3, 2/3]] ``` Only `numpy` is available. Results are checked against `sklearn.naive_bayes.MultinomialNB`. ```hint Zero counts at alpha=0 With `alpha=0`, some log-probabilities are `-inf`. Check what a plain matrix product returns when a document has a zero count for one of those words. ``` ```hint Long documents A long document pushes every class score far below zero. Look for a constant you can subtract from each row before exponentiating. ``` ### What a Strong Answer Covers - How the vocabulary and class order are built, and how `transform` maps a document onto them while skipping unseen tokens. - The prior, including how a supplied `class_prior` is renormalised and aligned with `classes_`. - The smoothed likelihood formula and its behavior at `alpha=0`, including how a zero count is kept from producing NaN. - Stable log-sum-exp normalization and the tie rule in `predict`. - The time and memory cost of scoring, and how to reduce the memory. ### Follow-up Questions - How would you scale this to a 1M-word vocabulary? - Why can Complement Naive Bayes beat this on imbalanced classes? - How would you choose `alpha`?

Overview: Implement a multinomial Naive Bayes text classifier in NumPy that builds a vocabulary from raw strings, applies additive smoothing and an optional class prior, and returns stable posterior probabilities. It tests log-space scoring, handling of unseen tokens and alpha=0, and matching scikit-learn's MultinomialNB.

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

Implement a class MultinomialNaiveBayes(alpha=1.0, class_prior=None) that fits on a list of strings and labels, then scores new documents. It has the methods fit, transform, joint_log_likelihood, predict_log_proba, predict_proba and predict. Use smoothing alpha and an optional class_prior. All outputs are NumPy arrays.

Requirements:

  • Tokenise with doc.lower().split() . vocabulary_ maps sorted training tokens to 0..V-1 , classes_ holds the sorted unique labels, and fit returns self .
  • class_log_prior_ is the log of empirical class frequencies, or the log of class_prior renormalised to sum 1 when given.
  • feature_log_prob_ has shape (n_classes, V) and equals log((N_cw + alpha) / (N_c + alpha*V)) , where N_cw is the count of word w in class c and N_c is the total word count of class c. With alpha=0 , entries may be -inf .
  • transform returns a float count matrix (n_docs, V) and ignores unseen tokens. joint_log_likelihood is counts · feature_log_prob_ᵀ + prior, and a zero count contributes 0 even against -inf .
  • predict_log_proba normalises with a stable log-sum-exp, and predict_proba is its exp . predict returns the argmax label, with ties going to the earliest entry in classes_ .

Example:

m = MultinomialNaiveBayes(alpha=1.0).fit(
    ["good good movie", "bad movie", "good fun"], ["pos", "neg", "pos"])
m.classes_          # ['neg', 'pos']
m.vocabulary_       # {'bad': 0, 'fun': 1, 'good': 2, 'movie': 3}
m.feature_log_prob_ # log([[2,1,1,2]/6, [1,2,4,2]/9])
m.predict_proba(["xyz unknown", ""])  # [[1/3, 2/3], [1/3, 2/3]]

Only numpy is available. Results are checked against sklearn.naive_bayes.MultinomialNB.

What a Strong Answer Covers Guidance

  • How the vocabulary and class order are built, and how transform maps a document onto them while skipping unseen tokens.
  • The prior, including how a supplied class_prior is renormalised and aligned with classes_ .
  • The smoothed likelihood formula and its behavior at alpha=0 , including how a zero count is kept from producing NaN.
  • Stable log-sum-exp normalization and the tie rule in predict .
  • The time and memory cost of scoring, and how to reduce the memory.

Follow-up Questions Guidance

  • How would you scale this to a 1M-word vocabulary?
  • Why can Complement Naive Bayes beat this on imbalanced classes?
  • How would you choose alpha ?