Weighted Multinomial Naive Bayes Fit

Quick Overview

Implement multinomial Naive Bayes with per-sample weights so its fitted counts, smoothed log probabilities and class priors match scikit-learn. It tests weighted counting, Laplace smoothing, the three prior options and numerically stable probability normalization for very long documents.

Weighted Multinomial Naive Bayes Fit

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement `WeightedMultinomialNB` so that `fit(X, y, sample_weight=None)` weights each document's contribution to its class count and word counts. Results must match scikit-learn's `MultinomialNB` fitted with the same `sample_weight`. The constructor takes `alpha=1.0`, `fit_prior=True` and `class_prior=None`, as in scikit-learn. Requirements: - `fit` sets `classes_` (sorted unique labels), `class_count_`, `feature_count_` (shape `(n_classes, n_features)`), `feature_log_prob_`, `class_log_prior_` and returns `self`. - `sample_weight=None` means unit weights. A length mismatch raises `ValueError`. - Smoothing: `log((count + alpha) / row_sum(count + alpha))`. Prior: `class_prior` if given, else weighted class frequencies if `fit_prior`, else uniform. - `predict_log_proba` must stay finite and normalized for very long documents. - `predict` returns labels from `classes_` (string labels supported). `predict_proba` rows sum to 1. For example: ```python X = [[2, 1, 0], [0, 1, 3], [1, 0, 1]] y = [0, 1, 0]; w = [2.0, 1.0, 0.5] m = WeightedMultinomialNB(alpha=1.0).fit(X, y, w) m.class_count_ # [2.5, 1.0] m.feature_count_ # [[4.5, 2.0, 0.5], [0.0, 1.0, 3.0]] m.feature_log_prob_ # log([[0.55, 0.3, 0.15], [1/7, 2/7, 4/7]]) m.class_log_prior_ # log([2.5/3.5, 1/3.5]) ``` ```hint Treat a weight as a row count An integer weight of 3 should act exactly like three copies of the row. Work out what that means for each class total and each word count, then look for one matrix product that produces all of the word counts at once. ``` ```hint Long documents A document with thousands of tokens has a joint log-likelihood far below anything `exp` can represent. Normalize the class scores without leaving log space. ``` ### Constraints & Assumptions - `X` holds non-negative counts. Weights are non-negative (zero weight means the sample is ignored). - Integer weights must be equivalent to duplicating rows. - Match scikit-learn to `rtol=1e-6`. ### What a Strong Answer Covers - Applying the weights before counting, so the class counts, word counts and fitted prior all use weighted totals. - Smoothing and the three prior cases (given `class_prior`, fitted from weighted frequencies, uniform) written to match scikit-learn's formulas. - A numerically stable `predict_log_proba` for very long documents, with `predict_proba` rows that sum to 1. - Input checks and label handling: weight length, sorted `classes_`, and string labels returned by `predict`. - Why integer weights reproduce row duplication, and the cost of fitting and predicting. ### Follow-up Questions - What happens if a class has total weight zero? - If every weight is multiplied by 10, which fitted attributes change and which stay the same? - How would you add `partial_fit` so weighted batches can arrive over time? - How would you adapt the fit for a sparse document-term matrix with a million columns?

Overview: Implement multinomial Naive Bayes with per-sample weights so its fitted counts, smoothed log probabilities and class priors match scikit-learn. It tests weighted counting, Laplace smoothing, the three prior options and numerically stable probability normalization for very long documents.

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

Implement WeightedMultinomialNB so that fit(X, y, sample_weight=None) weights each document's contribution to its class count and word counts. Results must match scikit-learn's MultinomialNB fitted with the same sample_weight. The constructor takes alpha=1.0, fit_prior=True and class_prior=None, as in scikit-learn.

Requirements:

  • fit sets classes_ (sorted unique labels), class_count_ , feature_count_ (shape (n_classes, n_features) ), feature_log_prob_ , class_log_prior_ and returns self .
  • sample_weight=None means unit weights. A length mismatch raises ValueError .
  • Smoothing: log((count + alpha) / row_sum(count + alpha)) . Prior: class_prior if given, else weighted class frequencies if fit_prior , else uniform.
  • predict_log_proba must stay finite and normalized for very long documents.
  • predict returns labels from classes_ (string labels supported). predict_proba rows sum to 1.

For example:

X = [[2, 1, 0], [0, 1, 3], [1, 0, 1]]
y = [0, 1, 0]; w = [2.0, 1.0, 0.5]
m = WeightedMultinomialNB(alpha=1.0).fit(X, y, w)
m.class_count_      # [2.5, 1.0]
m.feature_count_    # [[4.5, 2.0, 0.5], [0.0, 1.0, 3.0]]
m.feature_log_prob_ # log([[0.55, 0.3, 0.15], [1/7, 2/7, 4/7]])
m.class_log_prior_  # log([2.5/3.5, 1/3.5])

Constraints & Assumptions

  • X holds non-negative counts. Weights are non-negative (zero weight means the sample is ignored).
  • Integer weights must be equivalent to duplicating rows.
  • Match scikit-learn to rtol=1e-6 .

What a Strong Answer Covers Guidance

  • Applying the weights before counting, so the class counts, word counts and fitted prior all use weighted totals.
  • Smoothing and the three prior cases (given class_prior , fitted from weighted frequencies, uniform) written to match scikit-learn's formulas.
  • A numerically stable predict_log_proba for very long documents, with predict_proba rows that sum to 1.
  • Input checks and label handling: weight length, sorted classes_ , and string labels returned by predict .
  • Why integer weights reproduce row duplication, and the cost of fitting and predicting.

Follow-up Questions Guidance

  • What happens if a class has total weight zero?
  • If every weight is multiplied by 10, which fitted attributes change and which stay the same?
  • How would you add partial_fit so weighted batches can arrive over time?
  • How would you adapt the fit for a sparse document-term matrix with a million columns?