Incremental Gaussian Naive Bayes with partial_fit
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Complete `IncrementalGaussianNB`. `partial_fit(X, y, classes=None)` merges each batch's per-class count, mean and population variance into running statistics using the parallel (Chan) update, so the fitted state matches a single `fit` on all data seen so far. Both methods return `self`.
```python
class IncrementalGaussianNB:
def __init__(self, var_smoothing=1e-9, priors=None): ...
def partial_fit(self, X, y, classes=None): ... # returns self
def fit(self, X, y): ... # returns self
def predict_log_proba(self, X): ...
def predict(self, X): ...
```
Requirements:
- Expose `classes_` (sorted), `class_count_`, `theta_`, `var_`, `epsilon_` and `class_prior_`. Classes come from `classes` on the first call, or from `np.unique(y)`.
- `epsilon_ = var_smoothing * max(per-feature population variance over all data seen)`, and `var_` is the per-class population variance plus `epsilon_`.
- `class_prior_` is `priors` normalized if given, else `class_count_ / total`.
- An unknown label in a later batch, or a changed feature count, raises `ValueError`. `fit` resets the state, then fits.
- `predict_log_proba` stays finite on extreme inputs (log-sum-exp). `predict` returns the `argmax` class of the joint log-likelihood.
Example:
```python
m = IncrementalGaussianNB(var_smoothing=0.1)
m.partial_fit([[1.0], [3.0], [10.0]], [0, 0, 1])
m.partial_fit([[5.0], [14.0]], [0, 1])
# class_count_ = [3, 2], class_prior_ = [0.6, 0.4]
# theta_ = [[3.0], [12.0]]
# epsilon_ = 0.1 * 22.64 = 2.264
# var_ = [[8/3 + 2.264], [4.0 + 2.264]]
```
After both batches, class 0 has seen 1, 3 and 5 (mean 3, population variance 8/3) and class 1 has seen 10 and 14 (mean 12, variance 4). The five values together have variance 22.64, which sets `epsilon_`.
```hint What to keep
You cannot store the rows. Decide which per-class quantities let two batches combine exactly, whatever their sizes.
```
```hint Merging spreads
When two groups have different means, the pooled spread is larger than the two within-group spreads combined. Account for the gap between the means.
```
```hint Epsilon without the data
The overall feature variance can be rebuilt from per-class counts, means and spreads.
```
### Constraints & Assumptions
- Outputs are checked against `sklearn.naive_bayes.GaussianNB` fit on the union of batches.
- A declared class may have zero samples in early batches.
- Keep only running statistics, so memory does not grow with the number of rows seen.
### What a Strong Answer Covers
- Per-class sufficient statistics (count, mean, sum of squared deviations) and an exact merge that includes the between-batch term and handles classes absent from a batch.
- An `epsilon_` based on the variance of all data seen, recovered from the running statistics.
- Priors, validation of labels and feature counts, and `fit` resetting the state.
- Stable log posteriors, and a `predict` that takes the argmax of the joint log-likelihood.
- An argument, or a test, that any batch split gives the same state as one `fit`.
### Follow-up Questions
- Why not just average each batch's variance into the running variance?
- How would `partial_fit` differ for Multinomial Naive Bayes?
- How would you adapt this to drifting data streams?
Overview: Build a Gaussian naive Bayes classifier whose partial_fit merges each batch into running per-class counts, means and variances, so the state matches a single fit on all data. Tests Chan's parallel variance update, variance smoothing rebuilt from running statistics, input validation and stable log-probabilities.