Implement a naive Bayes classifier with Gaussian numeric columns and smoothed categorical columns

Quick Overview

Implement a naive Bayes classifier in NumPy that models numeric columns as per-class Gaussians and categorical columns as smoothed frequency tables, combined in one joint log likelihood. It tests variance smoothing, additive smoothing, handling of unseen category codes and stable posterior computation.

Implement a naive Bayes classifier with Gaussian numeric columns and smoothed categorical columns

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement `MixedNB(numeric_cols, categorical_cols, alpha=1.0, var_smoothing=1e-9)`, a naive Bayes classifier over a float matrix `X`. The `numeric_cols` are modeled as per-class Gaussians and the `categorical_cols` (integer codes ≥ 0) as smoothed frequency tables. The joint log likelihood is the log prior plus the sum of all per-column log likelihoods. The class must meet these requirements: - `fit(X, y)` returns `self` and sets `classes_` (sorted), `class_log_prior_` (log of the empirical class frequencies), and `theta_` and `var_`, both of shape `(n_classes, n_numeric)`. - `var_` is the per-class population variance plus `epsilon_`, where `epsilon_ = var_smoothing * max` of the overall per-column variance of the numeric columns. - `category_log_prob_` is a list with one `(n_classes, K)` array per categorical column, where `K = max training code + 1` and the entries are `log((count + alpha) / (class_count + alpha * K))`. - `joint_log_likelihood(X)` returns an array of shape `(n, n_classes)`. A test code outside `[0, K)` contributes nothing for that column. - `predict_log_proba` normalizes with a stable log-sum-exp, so it stays finite for extreme inputs. `predict_proba` exponentiates it, and `predict` takes the argmax, with ties going to the smallest label. Example: ```python X = [[1, 0], [3, 1], [2, 0], [6, 1], [4, 1]]; y = [0, 0, 1, 1, 1] m = MixedNB([0], [1], alpha=1.0, var_smoothing=0.1).fit(X, y) np.exp(m.class_log_prior_) # [0.4, 0.6] m.theta_ # [[2.0], [4.0]] m.var_ # [[1.296], [2.9627]] (epsilon_ = 0.1 * 2.96) np.exp(m.category_log_prob_[0]) # [[0.5, 0.5], [0.4, 0.6]] ``` ```hint Tables, then lookups Each categorical column can be a class-by-code table of counts. Think about how to fill it without a Python loop over rows, and how scoring a column then becomes an index into its log table. ``` ```hint Watch the index range Check which test codes fall inside the range seen in training before you index a table. A negative code is a valid NumPy index and silently reads the wrong cell. ``` ### Constraints & Assumptions - NumPy only. - `X` is a float matrix. Categorical columns hold non-negative integer codes in training; test rows may hold codes outside the training range. - `numeric_cols` and `categorical_cols` are column indices into `X`, and either list may be empty. - `alpha` is the additive smoothing count (1.0 is Laplace smoothing) and `K` is fixed per column from the training codes. ### What a Strong Answer Covers - The Gaussian part: sorted classes, log priors, per-class means and population variances, and one shared `epsilon_` computed from the numeric columns only. - The smoothed categorical tables, with the right `K` and denominator for each column. - One `(n, n_classes)` joint log likelihood that combines both parts and applies the rule for codes outside `[0, K)`. - Stable normalization and the tie rule in `predict`. - Complexity and edge cases such as empty column lists, codes a class never saw, `alpha = 0` and zero variance. ### Follow-up Questions - Why ignore unseen category codes instead of raising or assigning a smoothed probability? - How would you add a `partial_fit` for streaming data? - What if a numeric column is clearly non-Gaussian (skewed or multimodal)?

Overview: Implement a naive Bayes classifier in NumPy that models numeric columns as per-class Gaussians and categorical columns as smoothed frequency tables, combined in one joint log likelihood. It tests variance smoothing, additive smoothing, handling of unseen category codes and stable posterior computation.

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

Implement MixedNB(numeric_cols, categorical_cols, alpha=1.0, var_smoothing=1e-9), a naive Bayes classifier over a float matrix X. The numeric_cols are modeled as per-class Gaussians and the categorical_cols (integer codes ≥ 0) as smoothed frequency tables. The joint log likelihood is the log prior plus the sum of all per-column log likelihoods.

The class must meet these requirements:

  • fit(X, y) returns self and sets classes_ (sorted), class_log_prior_ (log of the empirical class frequencies), and theta_ and var_ , both of shape (n_classes, n_numeric) .
  • var_ is the per-class population variance plus epsilon_ , where epsilon_ = var_smoothing * max of the overall per-column variance of the numeric columns.
  • category_log_prob_ is a list with one (n_classes, K) array per categorical column, where K = max training code + 1 and the entries are log((count + alpha) / (class_count + alpha * K)) .
  • joint_log_likelihood(X) returns an array of shape (n, n_classes) . A test code outside [0, K) contributes nothing for that column.
  • predict_log_proba normalizes with a stable log-sum-exp, so it stays finite for extreme inputs. predict_proba exponentiates it, and predict takes the argmax, with ties going to the smallest label.

Example:

X = [[1, 0], [3, 1], [2, 0], [6, 1], [4, 1]]; y = [0, 0, 1, 1, 1]
m = MixedNB([0], [1], alpha=1.0, var_smoothing=0.1).fit(X, y)
np.exp(m.class_log_prior_)        # [0.4, 0.6]
m.theta_                          # [[2.0], [4.0]]
m.var_                            # [[1.296], [2.9627]]   (epsilon_ = 0.1 * 2.96)
np.exp(m.category_log_prob_[0])   # [[0.5, 0.5], [0.4, 0.6]]

Constraints & Assumptions

  • NumPy only.
  • X is a float matrix. Categorical columns hold non-negative integer codes in training; test rows may hold codes outside the training range.
  • numeric_cols and categorical_cols are column indices into X , and either list may be empty.
  • alpha is the additive smoothing count (1.0 is Laplace smoothing) and K is fixed per column from the training codes.

What a Strong Answer Covers Guidance

  • The Gaussian part: sorted classes, log priors, per-class means and population variances, and one shared epsilon_ computed from the numeric columns only.
  • The smoothed categorical tables, with the right K and denominator for each column.
  • One (n, n_classes) joint log likelihood that combines both parts and applies the rule for codes outside [0, K) .
  • Stable normalization and the tie rule in predict .
  • Complexity and edge cases such as empty column lists, codes a class never saw, alpha = 0 and zero variance.

Follow-up Questions Guidance

  • Why ignore unseen category codes instead of raising or assigning a smoothed probability?
  • How would you add a partial_fit for streaming data?
  • What if a numeric column is clearly non-Gaussian (skewed or multimodal)?