Categorical Naive Bayes with Unseen-Value Fallback
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `CategoricalNaiveBayes` for integer-coded categorical features. `fit(X, y)` learns class priors and Lidstone-smoothed per-feature tables and returns `self`. The prediction methods score rows in log space and skip any feature whose value falls outside the range seen in training.
The class must meet these requirements:
- After fitting, the model exposes `classes_` (sorted unique labels), `class_count_`, `class_log_prior_`, `n_categories_` with `n_categories_[j] = max(X[:, j]) + 1`, and the per-feature lists `category_count_` and `feature_log_prob_`, where entry `j` has shape `(n_classes, n_categories_[j])`.
- Each table cell is `P(x_j = c | k) = (count + alpha) / (N_k + alpha * n_categories_[j])`, where `count` is the number of class `k` training rows with `x_j = c` and `N_k` is the number of class `k` rows.
- The prior is `class_prior` when it is given (a wrong length raises `ValueError`), else the empirical class frequencies when `fit_prior` is true, else uniform.
- `joint_log_likelihood(X)` returns an `(n, n_classes)` array: the log prior plus the log-probabilities of every feature whose value is in `[0, n_categories_[j])`. Out-of-range values contribute nothing.
- `predict_log_proba` normalizes with a stable log-sum-exp and `predict_proba` exponentiates it. `predict` returns `classes_[argmax]`, and ties go to the smallest label.
Example:
```python
X = [[0, 1], [1, 1], [0, 0], [2, 1]]
y = [0, 0, 1, 1]
m = CategoricalNaiveBayes(alpha=1.0).fit(X, y)
m.n_categories_ # [3, 2]
m.predict_proba([[0, 1]]) # [[0.6, 0.4]]
m.predict_proba([[5, 0]]) # [[1/3, 2/3]] (feature 0 is out of range, skipped)
m.predict([[5, 0]]) # [1]
```
```hint Shape of the tables
Each feature can have a different number of categories, so one 3-D array does not fit. Count (class, value) pairs per feature, and check how NumPy handles repeated index pairs when you increment with fancy indexing.
```
```hint Scoring a row safely
Decide per column which rows have a usable value, and add table entries only for those rows. Then think about what happens to `exp` when a row's joint score is a sum of hundreds of negative logs.
```
### Constraints & Assumptions
- At fit time `X` is 2-D and holds non-negative integers. Anything else raises `ValueError`.
- At prediction time any integer can appear, including negative values and values above the training maximum.
- There can be hundreds of features, and posteriors must stay finite.
- On rows whose values are all in range, probabilities should match `sklearn.naive_bayes.CategoricalNB` to about `1e-6`.
### What a Strong Answer Covers
- The prior precedence rule, the `class_prior` length check, and labels mapped through sorted `classes_`.
- Lidstone-smoothed tables per feature whose denominators use `n_categories_[j]` exactly as in the stated formula.
- Masked lookups so that out-of-range values, negatives included, leave every class score unchanged, and a row with no usable values returns the prior.
- Log-space scoring with a max-shifted log-sum-exp, plus the tie rule in `predict`.
- Fit-time input validation and the time and space cost of fitting and scoring.
### Follow-up Questions
- Why ignore unseen values instead of assigning them a smoothed probability?
- How would you support `partial_fit` on streaming batches?
Overview: Implement a categorical naive Bayes classifier for integer-coded features with Lidstone smoothing, configurable class priors, and a rule that skips feature values outside the training range. It tests log-space scoring, stable log-sum-exp normalization, and careful NumPy indexing.