Feature Duplication Effect on Gaussian Naive Bayes

Quick Overview

Implement Gaussian naive Bayes and a tie-aware ROC AUC in NumPy, then measure how appending copies of one feature changes the mean max posterior and the AUC. Tests numerically stable posteriors, matching scikit-learn's conventions, and how the independence assumption affects calibration and ranking.

Feature Duplication Effect on Gaussian Naive Bayes

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement Gaussian naive Bayes from scratch in NumPy, a tie-aware ROC AUC, and a function that measures what happens to the model when one feature is copied several times. Write these four functions: - `fit_gaussian_nb(X, y, var_smoothing=1e-9)` returns a dict with keys `classes` (sorted), `class_prior`, `theta`, `var` and `epsilon`. `theta` holds the per-class feature means. `var` is the per-class population variance plus `epsilon = var_smoothing * max(np.var(X, axis=0))`. - `predict_proba(model, X)` returns an array of shape `(n, n_classes)` with columns in sorted class order. Every row must be finite and sum to 1, even when the log-likelihoods are extreme. - `roc_auc(y_true, scores)` takes 0/1 labels with 1 as the positive class and counts each tied positive/negative pair as 0.5. It raises `ValueError` if either class is absent. - `duplication_effect(X, y, feature, k)` fits the model on `X` and on `X` with `k` copies of column `feature` appended, then scores both on the training data. It returns floats under `base_mean_max_proba`, `base_auc`, `dup_mean_max_proba` and `dup_auc`. AUC uses `proba[:, 1]`, so the second sorted label is the positive class. `duplication_effect` raises `ValueError` when `X` is not 2-D, `feature` is out of range, `k < 0`, or the labels are not exactly binary. Example: ```python X = [[1, 0], [3, 0], [4, 0], [6, 0], [8, 10]] y = [0, 0, 1, 1, 1] model = fit_gaussian_nb(X, y) # np.var(X, axis=0) = [5.84, 16], so eps = 1e-9 * 16 # class_prior = [0.4, 0.6] # theta = [[2, 0], [6, 10/3]] # var = [[1 + eps, eps], [8/3 + eps, 200/9 + eps]] roc_auc([0, 0, 1, 1], [0.5, 0.2, 0.5, 0.9]) # 0.875 ``` The AUC example has four positive/negative pairs. The positive scored 0.9 beats both negatives, and the positive scored 0.5 beats the negative at 0.2 and ties the one at 0.5, so the AUC is (3 + 0.5) / 4 = 0.875. ```hint Stable posteriors Stay in log space until the last step, and think about what to subtract from each row before you exponentiate. ``` ```hint Reading the result Write the duplicated model's log-odds as a sum of per-feature terms and look at the coefficient on the copied feature's term. ``` ### Constraints & Assumptions - Use NumPy only. - Results must match scikit-learn's `GaussianNB` and `roc_auc_score` to about 1e-6. - Labels may be ints or strings. Classes are ordered by sorting the unique labels. - `k = 0` must leave every metric unchanged. ### What a Strong Answer Covers - Parameter estimates that match scikit-learn: population variance and one epsilon computed from the whole training matrix. - A joint log-likelihood normalized with log-sum-exp so posteriors stay finite and rows sum to 1. - An AUC that gives ties half credit and raises when a class is missing. - Input validation, string labels, the positive-class convention and the `k = 0` case. - A correct account of how the copies change the log-odds, and what that does to calibration and to ranking. ### Follow-up Questions - Why does AUC stay nearly constant while the mean max posterior rises, and when can AUC change? - How would you repair the overconfident posteriors after the fact? - How could you detect or mitigate correlated features before fitting? - How would you compute the AUC for millions of samples without the pairwise comparison matrix?

Overview: Implement Gaussian naive Bayes and a tie-aware ROC AUC in NumPy, then measure how appending copies of one feature changes the mean max posterior and the AUC. Tests numerically stable posteriors, matching scikit-learn's conventions, and how the independence assumption affects calibration and ranking.

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

Implement Gaussian naive Bayes from scratch in NumPy, a tie-aware ROC AUC, and a function that measures what happens to the model when one feature is copied several times. Write these four functions:

  • fit_gaussian_nb(X, y, var_smoothing=1e-9) returns a dict with keys classes (sorted), class_prior , theta , var and epsilon . theta holds the per-class feature means. var is the per-class population variance plus epsilon = var_smoothing * max(np.var(X, axis=0)) .
  • predict_proba(model, X) returns an array of shape (n, n_classes) with columns in sorted class order. Every row must be finite and sum to 1, even when the log-likelihoods are extreme.
  • roc_auc(y_true, scores) takes 0/1 labels with 1 as the positive class and counts each tied positive/negative pair as 0.5. It raises ValueError if either class is absent.
  • duplication_effect(X, y, feature, k) fits the model on X and on X with k copies of column feature appended, then scores both on the training data. It returns floats under base_mean_max_proba , base_auc , dup_mean_max_proba and dup_auc . AUC uses proba[:, 1] , so the second sorted label is the positive class.

duplication_effect raises ValueError when X is not 2-D, feature is out of range, k < 0, or the labels are not exactly binary.

Example:

X = [[1, 0], [3, 0], [4, 0], [6, 0], [8, 10]]
y = [0, 0, 1, 1, 1]
model = fit_gaussian_nb(X, y)
# np.var(X, axis=0) = [5.84, 16], so eps = 1e-9 * 16
# class_prior = [0.4, 0.6]
# theta       = [[2, 0], [6, 10/3]]
# var         = [[1 + eps, eps], [8/3 + eps, 200/9 + eps]]

roc_auc([0, 0, 1, 1], [0.5, 0.2, 0.5, 0.9])  # 0.875

The AUC example has four positive/negative pairs. The positive scored 0.9 beats both negatives, and the positive scored 0.5 beats the negative at 0.2 and ties the one at 0.5, so the AUC is (3 + 0.5) / 4 = 0.875.

Constraints & Assumptions

  • Use NumPy only.
  • Results must match scikit-learn's GaussianNB and roc_auc_score to about 1e-6.
  • Labels may be ints or strings. Classes are ordered by sorting the unique labels.
  • k = 0 must leave every metric unchanged.

What a Strong Answer Covers Guidance

  • Parameter estimates that match scikit-learn: population variance and one epsilon computed from the whole training matrix.
  • A joint log-likelihood normalized with log-sum-exp so posteriors stay finite and rows sum to 1.
  • An AUC that gives ties half credit and raises when a class is missing.
  • Input validation, string labels, the positive-class convention and the k = 0 case.
  • A correct account of how the copies change the log-odds, and what that does to calibration and to ranking.

Follow-up Questions Guidance

  • Why does AUC stay nearly constant while the mean max posterior rises, and when can AUC change?
  • How would you repair the overconfident posteriors after the fact?
  • How could you detect or mitigate correlated features before fitting?
  • How would you compute the AUC for millions of samples without the pairwise comparison matrix?