Cost-Sensitive Multinomial Naive Bayes Prediction

Quick Overview

Implement a multinomial naive Bayes classifier that also computes expected risk from a cost matrix and predicts the class with the lowest risk. It tests log-space normalization for large counts, reading a cost matrix the right way, and how asymmetric costs move the decision threshold.

Cost-Sensitive Multinomial Naive Bayes Prediction

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement `CostSensitiveMultinomialNB`, a multinomial naive Bayes classifier with Laplace/Lidstone smoothing `alpha`. In addition to argmax prediction, it must compute the expected risk from a cost matrix and predict the class that minimizes that risk. The class must meet these requirements: - `fit` returns `self` and sets the sorted `classes_`, the empirical `class_log_prior_`, and `feature_log_prob_` $= \log \frac{N_{kj} + \alpha}{\sum_{j'} (N_{kj'} + \alpha)}$, matching sklearn's `MultinomialNB`. Here $N_{kj}$ is the total count of feature $j$ over the training rows of class $k$. - `predict_log_proba` normalizes in log space and stays finite for large counts such as 5000. `predict` returns the class with the largest posterior. - `expected_risk(X, cost)` returns `predict_proba(X) @ cost` with shape `(n_samples, n_classes)`, where `cost[i, j]` is the cost of predicting class `j` when the true class is `i`. - `predict_min_risk(X, cost)` returns the label in `classes_` with the smallest risk. Ties go to the earliest class in `classes_`. - A `cost` whose shape is not `(n_classes, n_classes)` raises `ValueError`. Example: ```python X = [[2, 0], [1, 1], [0, 3]] y = [0, 0, 1] m = CostSensitiveMultinomialNB(alpha=1.0).fit(X, y) q = [[1, 1]] cost = [[0, 1], [5, 0]] m.predict_proba(q) # [[25/34, 9/34]] m.expected_risk(q, cost) # [[45/34, 25/34]] m.predict(q) # [0] m.predict_min_risk(q, cost) # [1] ``` ```hint Staying finite With counts in the thousands, the joint log-likelihoods are large negative numbers. Normalize them without ever exponentiating a raw score. ``` ```hint Reading the cost matrix Rows are the true class and columns are the prediction. Write the expected cost of one prediction as a sum over the possible true classes, then check it against the example. ``` ### Constraints & Assumptions - `X` holds non-negative counts. Labels may be ints or strings. - Cost entries are finite and may be very large (for example `1e300`), and the risks must stay finite. ### What a Strong Answer Covers - Smoothed multinomial parameters and empirical priors that match sklearn's `MultinomialNB`, with sorted `classes_`. - Log-space scoring with a max-shifted log-sum-exp so that large counts stay finite. - The expected-risk formula with rows as true classes and columns as predictions, plus the shape check. - The minimum-risk decision with ties going to the earliest class, and why it can disagree with the argmax prediction. - Why the risks stay finite for very large cost entries, and the cost of fitting and scoring. ### Follow-up Questions - How would you add a reject (abstain) option to the cost-sensitive decision? - Naive Bayes posteriors are often overconfident. Why does that matter here? - For two classes, how does the cost matrix reduce to a threshold?

Overview: Implement a multinomial naive Bayes classifier that also computes expected risk from a cost matrix and predicts the class with the lowest risk. It tests log-space normalization for large counts, reading a cost matrix the right way, and how asymmetric costs move the decision threshold.

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

Implement CostSensitiveMultinomialNB, a multinomial naive Bayes classifier with Laplace/Lidstone smoothing alpha. In addition to argmax prediction, it must compute the expected risk from a cost matrix and predict the class that minimizes that risk.

The class must meet these requirements:

  • fit returns self and sets the sorted classes_ , the empirical class_log_prior_ , and feature_log_prob_ =log⁡Nkj+α∑j′(Nkj′+α)= \log \frac{N_{kj} + \alpha}{\sum_{j'} (N_{kj'} + \alpha)} , matching sklearn's MultinomialNB . Here NkjN_{kj} is the total count of feature jj over the training rows of class kk .
  • predict_log_proba normalizes in log space and stays finite for large counts such as 5000. predict returns the class with the largest posterior.
  • expected_risk(X, cost) returns predict_proba(X) @ cost with shape (n_samples, n_classes) , where cost[i, j] is the cost of predicting class j when the true class is i .
  • predict_min_risk(X, cost) returns the label in classes_ with the smallest risk. Ties go to the earliest class in classes_ .
  • A cost whose shape is not (n_classes, n_classes) raises ValueError .

Example:

X = [[2, 0], [1, 1], [0, 3]]
y = [0, 0, 1]
m = CostSensitiveMultinomialNB(alpha=1.0).fit(X, y)
q = [[1, 1]]
cost = [[0, 1], [5, 0]]
m.predict_proba(q)               # [[25/34, 9/34]]
m.expected_risk(q, cost)         # [[45/34, 25/34]]
m.predict(q)                     # [0]
m.predict_min_risk(q, cost)      # [1]

Constraints & Assumptions

  • X holds non-negative counts. Labels may be ints or strings.
  • Cost entries are finite and may be very large (for example 1e300 ), and the risks must stay finite.

What a Strong Answer Covers Guidance

  • Smoothed multinomial parameters and empirical priors that match sklearn's MultinomialNB , with sorted classes_ .
  • Log-space scoring with a max-shifted log-sum-exp so that large counts stay finite.
  • The expected-risk formula with rows as true classes and columns as predictions, plus the shape check.
  • The minimum-risk decision with ties going to the earliest class, and why it can disagree with the argmax prediction.
  • Why the risks stay finite for very large cost entries, and the cost of fitting and scoring.

Follow-up Questions Guidance

  • How would you add a reject (abstain) option to the cost-sensitive decision?
  • Naive Bayes posteriors are often overconfident. Why does that matter here?
  • For two classes, how does the cost matrix reduce to a threshold?