Complement Naive Bayes From Scratch
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: hard
Interview Round: Other
Implement `build_count_matrix(docs, vocabulary)` and the `ComplementNaiveBayes` class (`alpha=1.0`, `norm=False`) for non-negative count features. Parameters are estimated from each class's complement, and a document is assigned to the class whose complement fits it worst (argmin).
The code must meet these requirements:
- `build_count_matrix` lowercases each document, splits it on whitespace, ignores tokens that are not in the vocabulary, and returns a dense float array of shape `(n_docs, n_vocab)`.
- After fitting, the model exposes `classes_` (sorted unique labels), `feature_count_`, `feature_all_`, `weights_` and `feature_log_prob_` as defined below.
- `predict` returns `classes_[argmin(scores)]`, and ties go to the smallest label. `predict_log_proba` and `predict_proba` return a numerically stable log-softmax of `-scores` and its exponent. There is no class prior.
- `partial_fit` requires `classes` on the first call (otherwise it raises `ValueError`), and a sequence of `partial_fit` calls must give the same model as a single `fit` on all the data.
- Both dense and `scipy.sparse` input are accepted. Raise `ValueError` when `alpha <= 0` or any count is negative.
Definitions:
```text
feature_count_[c] = sum of X rows with label c # (n_classes, n_features)
feature_all_ = feature_count_.sum(axis=0)
comp = feature_all_ + alpha - feature_count_
weights_ = log(comp / comp.sum(axis=1, keepdims=True))
if norm: weights_ = weights_ / abs(weights_).sum(axis=1, keepdims=True)
feature_log_prob_ = -weights_
complement_scores(X) = X @ weights_.T # (n_samples, n_classes)
```
Example:
```python
X = [[2, 1, 0], [1, 0, 0], [0, 1, 3]]
y = [0, 0, 1]
m = ComplementNaiveBayes(alpha=1.0).fit(X, y)
m.feature_count_ # [[3, 1, 0], [0, 1, 3]]
m.weights_ # log([[1, 2, 4], [4, 2, 1]] / 7)
m.complement_scores([[1, 0, 0]]) # [[log(1/7), log(4/7)]]
m.predict([[1, 0, 0]]) # [0]
```
```hint Counting by class
Summing the rows of `X` per class is a matrix product with a one-hot label matrix. Think about which representation of that matrix keeps the cost proportional to the nonzeros of a sparse `X`.
```
```hint Making partial_fit match fit
Ask which fitted quantities simply add up across batches. Store only those, and derive everything else from them after each update.
```
```hint Long documents
Scores for a long document can be very large in magnitude. Normalize so that the largest term you exponentiate is exactly 1.
```
### Constraints & Assumptions
- Long documents, with counts up to about 10,000 per feature, must give finite, non-NaN log-probabilities.
- An all-zero row yields uniform probabilities.
### What a Strong Answer Covers
- A count-matrix builder that lowercases, splits on whitespace and drops unknown tokens.
- Complement counts and weights exactly as defined, `norm` applied per class, and the argmin decision rule with the stated tie-break.
- Per-class count accumulation that works for dense and sparse input and makes `partial_fit` reproduce `fit`.
- A stable log-softmax of `-scores` that stays finite on long documents and is uniform on an all-zero row.
- Validation of `alpha`, negative counts, unknown labels and the first `partial_fit` call, plus the cost of fitting and scoring.
### Follow-up Questions
- Why does CNB help on imbalanced data compared to Multinomial NB?
- What problem does `norm=True` address?
- How would you add TF-IDF and document-length normalization?
Overview: Implement complement naive Bayes for text counts, including a bag-of-words builder, complement-based weights with optional L1 normalization, and an argmin decision rule. It tests sparse-friendly counting, a partial_fit that matches fit, and numerically stable probabilities on long documents.