Implement Naive Bayes with Configurable Priors and Prior-Shift Adjustment

Quick Overview

Implement a multinomial naive Bayes classifier over count features with configurable class priors and a method that re-weights posteriors for known test-set priors. Tests log-space numerics, input validation, and the label-shift reasoning behind swapping priors at prediction time.

Implement Naive Bayes with Configurable Priors and Prior-Shift Adjustment

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement `PriorShiftNB`, a multinomial naive Bayes classifier over count features. Feature likelihoods use additive smoothing with parameter `alpha`: $$P(i \mid c) = \frac{N_{ci} + \alpha}{N_c + \alpha \cdot d}$$ Here $N_{ci}$ is the total count of feature $i$ over the training rows of class $c$, $N_c = \sum_i N_{ci}$, and $d$ is `n_features`. Class priors are configurable, and `adjust_proba` re-weights posteriors when the class priors of the test set are known. The class must meet these requirements: - `fit(X, y)` sets `classes_` (sorted unique labels), `class_log_prior_`, `feature_log_prob_` (shape `(k, n_features)`) and returns `self`. - The constructor argument `priors` is `"fitted"` (class frequencies), `"uniform"`, or an array of length k whose entries are finite, greater than 0 and sum to 1 within `1e-8`. Anything else raises `ValueError`. - `predict_log_proba` and `predict_proba` stay finite and normalised for very long documents. - `adjust_proba(X, test_priors)` returns the posterior multiplied by `test_priors` and divided by the training prior, renormalised. `test_priors` gets the same validation as an array passed as `priors`. - `predict` and `predict_shifted` return labels from `classes_` via argmax. Example: ```python X = [[2, 1], [1, 1], [0, 3]] y = [0, 0, 1] m = PriorShiftNB(alpha=1.0, priors="uniform").fit(X, y) m.predict([[1, 1]]) # [0] m.adjust_proba([[1, 1]], [0.1, 0.9]) # [[0.1453, 0.8547]] m.predict_shifted([[1, 1]], [0.1, 0.9]) # [1] ``` ```hint Where the prior enters Write the log posterior as a sum of terms. Which single term depends on the class prior, and what happens to the likelihood terms when only the class proportions change? ``` ```hint Very long documents A row with thousands of counts pushes every class score far below what `exp` can represent. Normalise the scores without leaving log space. ``` ### Constraints & Assumptions - `X` is array-like with shape `(n_samples, n_features)` and holds non-negative counts; `y` holds one label per row. - Labels only need to be sortable, and `k` is the number of distinct labels in `y`. - A priors array lists one value per class in the order of the sorted `classes_`. - Assume `alpha > 0`. ### What a Strong Answer Covers - Smoothed per-class feature log-probabilities with the stated denominator, and `classes_` in sorted order. - All three `priors` options, with `ValueError` for an unknown string, a wrong length, non-finite or non-positive entries, or a sum more than `1e-8` away from 1. - Normalisation in log space with a max shift, so long documents give finite probabilities that sum to 1. - A prior-shift adjustment that removes the prior the model actually used, adds the test prior and renormalises, with an argument for why the likelihoods stay valid. - Time and space complexity of fitting and prediction, plus edge cases such as tied scores and priors given in the wrong class order. ### Follow-up Questions - The test priors are unknown and you only have unlabeled test data. How would you estimate them? - Naive Bayes probabilities are often overconfident. How does that affect the prior-shift correction, and what would you do about it? - For a binary problem, which evaluation metrics change after the adjustment and which stay the same?

Overview: Implement a multinomial naive Bayes classifier over count features with configurable class priors and a method that re-weights posteriors for known test-set priors. Tests log-space numerics, input validation, and the label-shift reasoning behind swapping priors at prediction time.

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

Implement PriorShiftNB, a multinomial naive Bayes classifier over count features. Feature likelihoods use additive smoothing with parameter alpha:

P(i∣c)=Nci+αNc+α⋅dP(i \mid c) = \frac{N_{ci} + \alpha}{N_c + \alpha \cdot d}

Here NciN_{ci} is the total count of feature ii over the training rows of class cc, Nc=∑iNciN_c = \sum_i N_{ci}, and dd is n_features. Class priors are configurable, and adjust_proba re-weights posteriors when the class priors of the test set are known.

The class must meet these requirements:

  • fit(X, y) sets classes_ (sorted unique labels), class_log_prior_ , feature_log_prob_ (shape (k, n_features) ) and returns self .
  • The constructor argument priors is "fitted" (class frequencies), "uniform" , or an array of length k whose entries are finite, greater than 0 and sum to 1 within 1e-8 . Anything else raises ValueError .
  • predict_log_proba and predict_proba stay finite and normalised for very long documents.
  • adjust_proba(X, test_priors) returns the posterior multiplied by test_priors and divided by the training prior, renormalised. test_priors gets the same validation as an array passed as priors .
  • predict and predict_shifted return labels from classes_ via argmax.

Example:

X = [[2, 1], [1, 1], [0, 3]]
y = [0, 0, 1]
m = PriorShiftNB(alpha=1.0, priors="uniform").fit(X, y)
m.predict([[1, 1]])                        # [0]
m.adjust_proba([[1, 1]], [0.1, 0.9])       # [[0.1453, 0.8547]]
m.predict_shifted([[1, 1]], [0.1, 0.9])    # [1]

Constraints & Assumptions

  • X is array-like with shape (n_samples, n_features) and holds non-negative counts; y holds one label per row.
  • Labels only need to be sortable, and k is the number of distinct labels in y .
  • A priors array lists one value per class in the order of the sorted classes_ .
  • Assume alpha > 0 .

What a Strong Answer Covers Guidance

  • Smoothed per-class feature log-probabilities with the stated denominator, and classes_ in sorted order.
  • All three priors options, with ValueError for an unknown string, a wrong length, non-finite or non-positive entries, or a sum more than 1e-8 away from 1.
  • Normalisation in log space with a max shift, so long documents give finite probabilities that sum to 1.
  • A prior-shift adjustment that removes the prior the model actually used, adds the test prior and renormalises, with an argument for why the likelihoods stay valid.
  • Time and space complexity of fitting and prediction, plus edge cases such as tied scores and priors given in the wrong class order.

Follow-up Questions Guidance

  • The test priors are unknown and you only have unlabeled test data. How would you estimate them?
  • Naive Bayes probabilities are often overconfident. How does that affect the prior-shift correction, and what would you do about it?
  • For a binary problem, which evaluation metrics change after the adjustment and which stay the same?