Naive Bayes Smoothing Selection by Validation Log-Loss
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement multinomial and Gaussian naive Bayes from scratch, a validation log-loss, and two grid searches, `select_alpha` and `select_var_smoothing`. Each search fits one model per grid value on the training set, scores it on the validation set and returns `(best_value, losses)`.
The functions to write:
```python
fit_multinomial(X, y, alpha) -> dict
multinomial_predict_proba(model, X) -> np.ndarray
fit_gaussian(X, y, var_smoothing) -> dict
gaussian_predict_proba(model, X) -> np.ndarray
validation_log_loss(y_true, proba, classes) -> float
select_alpha(X_train, y_train, X_val, y_val, alphas) -> (float, np.ndarray)
select_var_smoothing(X_train, y_train, X_val, y_val, var_smoothings) -> (float, np.ndarray)
```
Requirements:
- Classes are `np.unique(y)` and may be strings. Priors are the empirical class frequencies. Model dicts hold `classes` and `class_log_prior`, plus `feature_log_prob` (multinomial) or `theta` and `var` (Gaussian).
- Multinomial: `feature_log_prob = log((counts + alpha) / row_sum)`, where `counts` is the per-class feature count matrix and `row_sum` is the sum of each row of `counts + alpha`.
- Gaussian: `var` is the per-class population variance plus `var_smoothing * max(np.var(X, axis=0))`.
- `predict_proba` rows sum to 1 and stay finite for extreme inputs.
- Log-loss is the mean of `-log(p_true)` with `p_true` clipped to `[1e-15, 1]`. `losses` is an array in grid order. Ties pick the smallest grid value, returned as a `float`.
Examples:
```python
X = [[2, 1, 0], [1, 0, 0], [0, 1, 3]]
y = [0, 0, 1]
fit_multinomial(X, y, 1.0)
# class_log_prior = log([2/3, 1/3])
# feature_log_prob = log([[4/7, 2/7, 1/7], [1/7, 2/7, 4/7]])
select_alpha(X, y, [[1, 0, 0]], [0], [1.0, 0.5, 2.0])
# (0.5, array([0.1178, 0.0690, 0.1823]))
select_alpha(X, y, [[0, 0, 0]], [0], [2.0, 1.0, 0.5])
# (0.5, array([0.4055, 0.4055, 0.4055]))
```
In the last call the validation row has no counts, so every alpha gives the same posterior and the tie goes to the smallest value, even though it comes last in the grid.
```hint Extreme inputs
A validation row far from every class mean, or with very large counts, makes every class likelihood underflow. Normalise the joint log-likelihoods per row before you exponentiate anything.
```
```hint Finding the true-class column
Labels can be strings. Map each validation label to its column using the sorted class array the model was fit with.
```
### Constraints & Assumptions
- Multinomial features are non-negative counts. Every class appears in training.
- Validation labels are a subset of the training classes. Grid values are positive.
- Results must match scikit-learn's `MultinomialNB(force_alpha=True)` and `GaussianNB` to about `1e-6`.
### What a Strong Answer Covers
- A multinomial fit that adds `alpha` to every count and normalises each class row by its own smoothed total, with empirical log-priors over sorted classes.
- A Gaussian fit with per-class means, population variances and one shared epsilon of `var_smoothing * max(np.var(X, axis=0))`.
- Posteriors computed in log space with a max-shifted log-sum-exp, so rows are finite and sum to 1.
- A log-loss that finds the true-class column for string or numeric labels and clips at `1e-15`.
- A grid search that refits per value, returns losses in grid order and breaks exact ties toward the smallest value, with the time and space cost.
### Follow-up Questions
- Why select the smoothing value by log-loss, and what would go wrong if you used accuracy?
- How would you make the selection more reliable on a small dataset?
- Why is `var_smoothing` scaled by the largest feature variance?
Overview: Implement multinomial and Gaussian naive Bayes from scratch, a clipped validation log-loss, and grid searches that choose each model's smoothing parameter. Tests numerically stable posteriors, matching scikit-learn's conventions, and a deterministic tie-breaking rule.