Implement Gaussian naive Bayes from scratch in NumPy to match scikit-learn's GaussianNB
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement a Gaussian naive Bayes classifier, `GaussianNaiveBayes(var_smoothing=1e-9, priors=None)`, using NumPy only. `fit(X, y)` estimates per-class priors, means and variances. The scoring methods return log joint likelihoods, posteriors and MAP labels. Results must match `sklearn.naive_bayes.GaussianNB`.
The class must meet these requirements:
- `fit` returns `self` and sets these attributes: `classes_` (sorted unique labels), `class_count_`, `class_prior_` (class frequencies, or `priors` verbatim if given), `theta_` and `var_` (both of shape `(n_classes, n_features)`).
- `epsilon_ = var_smoothing * max(np.var(X, axis=0))`, and `var_` is the per-class population variance (`ddof=0`) plus `epsilon_`.
- `joint_log_likelihood(X)` returns an array of shape `(n_samples, n_classes)`: the log prior plus the summed log Gaussian densities.
- `predict_log_proba` and `predict_proba` normalize each row with a stable log-sum-exp. The results must stay finite and each row must sum to 1, even for extreme inputs such as `x = ±1000`.
- `predict` returns `classes_[argmax]` over the joint log likelihood. Ties resolve to the smallest label.
Inputs may be lists or arrays. Labels can be any sortable values, for example `[3, 1, 8]`.
Example:
```python
X = [[1, 2], [3, 2], [5, 8], [7, 10], [9, 12]]; y = [0, 0, 1, 1, 1]
m = GaussianNaiveBayes(var_smoothing=0.0).fit(X, y)
m.class_prior_ # [0.4, 0.6]
m.theta_ # [[2, 2], [7, 10]]
m.var_ # [[1, 0], [8/3, 8/3]]
# with var_smoothing=0.01: epsilon_ = 0.01 * 16.96 = 0.1696
```
With `var_smoothing=0.0`, class 0 has zero variance on the second feature, so that setting is only for checking the fitted attributes. Scoring with it would divide by zero, which the default smoothing prevents.
```hint Stay in log space
Products of many small densities underflow to zero. Work with sums of log densities, and look at what subtracting the same constant from every score in a row does to the normalized result.
```
```hint Where mismatches come from
Most differences from `GaussianNB` come from which variance you compute (`ddof`) and from which rows `epsilon_` is computed on. Compare your fitted attributes on the example before you write the scoring methods.
```
### Constraints & Assumptions
- NumPy only inside the class. scikit-learn is used only to compare results.
- `X` has shape `(n_samples, n_features)` and may be a list of lists or an array. `y` has length `n_samples`.
- Labels can be any sortable values (integers, strings), not necessarily `0..k-1`.
- When `priors` is given, it has one entry per class, in the order of the sorted labels.
### What a Strong Answer Covers
- Per-class counts, means and population variances, with `epsilon_` computed from the variance of the full training data and added to every class variance.
- The Gaussian log density summed over features plus the log prior, producing an `(n_samples, n_classes)` array.
- A numerically stable normalization for `predict_log_proba` and `predict_proba`, and why the direct version fails at `x = ±1000`.
- Label handling: sorted `classes_`, arbitrary sortable labels, and the tie rule in `predict`.
- Time and space complexity, plus edge cases such as zero-variance features, supplied priors and a class with one sample.
### Follow-up Questions
- Why is variance smoothing needed at all, and why scale `epsilon_` by the largest feature variance?
- How would you add `partial_fit` so the model can learn from batches without storing the training data?
- What happens to the posteriors when features are strongly correlated, and how well calibrated are naive Bayes probabilities?
- What should happen when a supplied prior is zero for some class?
Overview: Implement a Gaussian naive Bayes classifier in NumPy whose fitted attributes, log likelihoods, posteriors and predictions match scikit-learn's GaussianNB. It tests per-class variance estimation with smoothing, scoring in log space, numerically stable normalization and correct label handling.