Sub topic 17
Complement naive Bayes for imbalanced text
This chapter assumes you know multinomial naive Bayes, Laplace smoothing, and log-space scoring from earlier chapters. You should also be comfortable with CountVectorizer, precision and recall, and a stratified train/test split.
Why multinomial naive Bayes struggles on skewed data
Multinomial naive Bayes (MNB) estimates word likelihoods for each class from only that class's documents. A rare class has few documents and few word tokens. Two problems follow.
- The prior favors the big class. The log prior
log P(c)is small for a rare class, so every score starts with a handicap. - The likelihoods are noisy for the small class. A class with 60 short documents gives rough counts for most words. Smoothing fills the gaps with a uniform guess, which pulls the estimates toward noise.
The result is a classifier that scores well on accuracy by predicting the majority class too often. Recall on the minority class is low, and that is usually the class you care about.
Complement naive Bayes (CNB), introduced by Rennie et al. in 2003, changes what each class's parameters are estimated from. It uses the documents that are not in the class.
The complement estimate
For class c, CNB counts how often each word i appears in all the other classes. Let N_c'i be that count, and let α be the smoothing constant. The complement likelihood is:
theta_ci = (N_c'i + alpha) / (sum_j N_c'j + alpha * |V|)Here |V| is the vocabulary size. The rare class gets its parameters from the large pool of every other class's text. That pool is large and stable, so the estimates are far less noisy than the rare class's own counts.
Prediction then asks which class's complement describes the document worst. A document d with word counts f_i receives this score for each class:
score(c) = sum_i f_i * log(theta_ci)CNB picks the class with the lowest score, because a low complement score means the document does not look like "everything else". scikit-learn flips the sign of the weights so that it can keep using argmax, the same as the other naive Bayes estimators.
Two details that matter in practice
Normalization. Long documents and frequent words can dominate the sum. Rennie et al. proposed dividing each class's weights by their total absolute value, so that no class has weights with a larger overall scale than the others. In scikit-learn this is the norm=True option. It defaults to False. Try both values and compare them on validation data.
Priors are ignored. In scikit-learn, ComplementNB does not add the class prior when there are two or more classes. The score is only the weighted word evidence. This removes the majority-class handicap described above. It also means the model has no built-in way to express that one class is more common than another.
The diagram shows where each estimator takes its counts from.
Comparing the two on skewed text
The script below builds a synthetic corpus with 900 "major" documents and 60 "minor" documents. Both classes mix shared words with a few topic words, and the minor class has a weaker topic signal. It then fits both models on the same features. The data is random, so you should look at the pattern in the report and not at fixed numbers.
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics import classification_report
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import ComplementNB, MultinomialNB
rng = np.random.default_rng(0)
shared = [f"common{i}" for i in range(30)]
major_words = [f"major{i}" for i in range(20)]
minor_words = [f"minor{i}" for i in range(8)]
def make_doc(topic_words, topic_share, length=20):
words = []
for _ in range(length):
pool = topic_words if rng.random() < topic_share else shared
words.append(str(rng.choice(pool)))
return " ".join(words)
texts, labels = [], []
for _ in range(900):
texts.append(make_doc(major_words, 0.5))
labels.append("major")
for _ in range(60):
texts.append(make_doc(minor_words, 0.3))
labels.append("minor")
X_train, X_test, y_train, y_test = train_test_split(
texts, labels, test_size=0.3, random_state=0, stratify=labels
)
vec = CountVectorizer()
Xtr = vec.fit_transform(X_train)
Xte = vec.transform(X_test)
for model in (MultinomialNB(alpha=1.0), ComplementNB(alpha=1.0, norm=True)):
model.fit(Xtr, y_train)
print(type(model).__name__)
print(classification_report(y_test, model.predict(Xte), zero_division=0))When you run it, read the minor row first. Check its recall, and check its precision as well. Recall on the minority class should rise with CNB. Precision can fall, because CNB flags more documents as minor. That is a trade-off and not a free improvement.
When to use which
| Situation | Better starting point |
|---|---|
| Balanced classes, short documents | `MultinomialNB` |
| Strong skew, rare class matters | `ComplementNB` |
| You need calibrated-looking class frequencies | `MultinomialNB` |
| Binary word presence only | `BernoulliNB` |
| Continuous features | `GaussianNB` |
CNB often does well on text with many classes of uneven size, which is the case it was designed for. It is not a replacement for good evaluation. Always compare against MNB on your own validation data.
Failure modes and gotchas
- Features must be non-negative. CNB, like MNB, expects counts or TF-IDF values. Negative values raise an error.
- Probabilities are still poor.
predict_probaon CNB is computed from a softmax of the joint log likelihoods. It has the same overconfidence problem as other naive Bayes models, and the lack of a prior makes the numbers harder to interpret. Calibrate them if you need them (see the calibration chapter). - Heavy skew with a tiny class can still fail. If the rare class has only a handful of documents, no estimator can learn a reliable decision boundary. Collect more data or consider resampling.
- Tune
alphaandnormtogether. They interact. A largeralphaflattens the complement estimates, and normalization rescales them again. Use a grid search with a metric that suits the minority class, such as F1 for that class or macro-averaged F1, and not accuracy.
Tuning with a pipeline
The following example puts CNB behind a TF-IDF step and searches over the two parameters using macro F1. The scorer rewards good performance on every class equally.
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import GridSearchCV
from sklearn.naive_bayes import ComplementNB
from sklearn.pipeline import Pipeline
pipe = Pipeline([
("tfidf", TfidfVectorizer()),
("clf", ComplementNB()),
])
grid = GridSearchCV(
pipe,
param_grid={
"clf__alpha": [0.1, 0.3, 1.0],
"clf__norm": [False, True],
},
scoring="f1_macro",
cv=3,
)
grid.fit(X_train, y_train)
print(grid.best_params_)
print(grid.score(X_test, y_test))This reuses X_train, y_train, X_test, and y_test from the previous script, so run both in the same session. With three folds and 60 minority documents in total, each fold has few rare examples, so expect the best parameters to change if you change the seed.
Exercise
A corpus has three classes with 5,000, 400, and 40 documents. You fit MultinomialNB and see near-zero recall on the 40-document class. Name two reasons CNB can help, and say which of its parameters has no effect on predictions when there are three classes.
Show answer
First, the 40-document class gets its word likelihoods from the other 5,400 documents instead of its own few, so the estimates are far less noisy. Second, CNB leaves out the log prior, so the rare class no longer starts with a large penalty. The fit_prior and class_prior parameters have no effect on predictions with three classes, because the joint log likelihood does not include the prior.
Exercise
After switching to CNB, minority-class recall rose from 0.10 to 0.70, but precision fell from 0.80 to 0.35. Is the change an improvement?
Show answer
It depends on the cost of each error. If missing a minority document is expensive (for example, a rare abuse report), the higher recall may be worth the extra false alarms. If reviewers must read every flagged document, the low precision may be unacceptable. Compare F1 for the minority class and judge it against the real cost of each error type, and consider tuning alpha and norm to move along the precision-recall trade-off.