Foundations to Frontier
Tests
D. Classical Machine Learning › D3 Probabilistic and Bayesian Classifiers

Complement Naive Bayes

Complement naive Bayes is a fix for multinomial naive Bayes on imbalanced text data. Instead of estimating each class's word distribution from that class's own (possibly few) documents, it estimates the distribution of all other classes, the complement, which uses far more data. It then assigns a document to the class whose complement fits it worst. This page covers the complement estimate, the decision rule, why it reduces the bias toward large classes, weight normalisation and the other transforms of Rennie et al., and when to use it. In the exercises you implement complement NB, verify a hand example and show its advantage on a rare class; then you route anomaly reports to teams with very different report volumes and compare multinomial NB (with learned or uniform priors) and complement NB (with and without weight normalisation) on balanced accuracy and the rarest team's recall.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Learn a small class from everybody else

The propulsion team gets 85% of anomaly reports, and the thermal team only 1%. To recognise a thermal report, multinomial naive Bayes needs a good picture of “thermal words”, but it has only a handful of thermal reports to learn from. Complement naive Bayes flips the question. For each team it learns what reports from all the other teams look like, which uses almost all the data. A new report goes to the team whose “everyone else” picture fits it worst.

Complement naive Bayes: learn each team from everyone else
multinomial NB · balanced accuracy 0.452
team 1 (80%)0.96
team 2 (15%)0.23
team 3 (5%)0.16
complement NB · balanced accuracy 0.582
team 1 (80%)0.76
team 2 (15%)0.56
team 3 (5%)0.43
words used to model the smallest team: multinomial (its own reports) 80 · complement (all other reports) 1120
As the largest team dominates the training data, multinomial NB's estimate for the small teams comes from a handful of reports, and its prior also pushes predictions toward the big team, so small-team recall collapses. Complement NB estimates "everything except team 3" from almost all the data, which is stable, so its decisions stay balanced.
Why engineers care

Operational text is always imbalanced: a few subsystems generate most tickets, and rare ones (often the critical ones) generate few. Complement NB keeps naive Bayes’ speed and simplicity while treating rare categories much more fairly. It is a one-line change in scikit-learn.

📝 Quick check (Level 0)
0/3 answered
  1. 1. Complement NB estimates, for each class…
  2. 2. A document is assigned to the class whose complement fits it…
  3. 3. Complement NB mainly helps when classes are…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

A small example

The vocabulary is valve, leak, battery, antenna. The training reports are:

  • class 0 (propulsion): (3, 1, 0, 0) and (2, 2, 0, 0);
  • class 1 (power): (0, 0, 4, 0) and (0, 1, 3, 0);
  • class 2 (comms): (0, 0, 0, 5), a single report.

Complement counts (all other classes) with +1 smoothing:

Class Complement counts + 1 Total
0 (1, 2, 8, 6) 17
1 (6, 4, 1, 6) 17
2 (6, 5, 8, 1) 20

For the report “valve leak”, x = (1, 1, 0, 0), the score is −Σ x log θ̃ (higher means a worse fit for the complement):

  • class 0: −(log 1/17 + log 2/17) = 4.97;
  • class 1: −(log 6/17 + log 4/17) = 2.49;
  • class 2: −(log 6/20 + log 5/20) = 2.59.

The report goes to class 0: “everyone except propulsion” almost never says “valve”.

Data used. The comms model in multinomial NB would come from one report with 5 words. Its complement uses 16 words from 4 reports.

The steps in plain English:

  1. For each class k, add up the word counts of every training document not in class k.
  2. Smooth and normalise to get the complement word probabilities θ̃ₖ.
  3. Score a new document: −Σⱼ xⱼ log θ̃ₖⱼ, high when the complement explains it poorly.
  4. Predict the class with the highest score. No class prior is used.
  5. Optionally normalise each class’s weights, which can help on balanced text corpora; check this on validation data.
📝 Quick check (Level 1)
0/3 answered
  1. 1. Complement counts for class 1 come from…
  2. 2. A higher complement-NB score means the complement fits the document…
  3. 3. In the example, 'valve leak' goes to…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

The algorithm

Complement estimate: θ̃ₖⱼ = (Σ over i with yᵢ ≠ k of xᵢⱼ + α)/(Σ over i with yᵢ ≠ k of Σⱼ xᵢⱼ + αV).

Weights: wₖⱼ = log θ̃ₖⱼ. With weight normalisation, ŵₖⱼ = wₖⱼ/Σⱼ|wₖⱼ|.

Decision: ŷ = argminₖ Σⱼ xⱼ wₖⱼ. Like multinomial NB, this is a linear classifier.

Why it helps. Multinomial NB’s estimates for small classes have high variance, and their weight vectors also systematically differ in scale from those of large classes. Rennie et al. (2003) showed that this “skewed data bias” pushes predictions toward large classes. Complement estimates are built from similar amounts of data for every class, so they are more stable and more comparable.

The full Rennie recipe for text:

  1. TF transform: log(1 + count);
  2. IDF weighting;
  3. length normalisation;
  4. complement estimates;
  5. weight normalisation.

Together these make NB competitive with linear SVMs on classic text benchmarks.

from sklearn.naive_bayes import ComplementNB
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.pipeline import make_pipeline
clf = make_pipeline(TfidfVectorizer(sublinear_tf=True), ComplementNB(alpha=0.3, norm=False)).fit(texts, labels)

Use it when classifying imbalanced text (tickets, reports, logs) with naive Bayes. Test norm=True on validation data rather than assuming it helps (exercise 2).

🐍 Exercise 1: complement naive Bayes
Implement complement naive Bayes (complement counts, smoothing, optional weight normalisation, argmin decision) alongside multinomial NB; verify the hand example and that complement NB recovers more of a rare 5% class than multinomial NB.
📝 Quick check (Level 2)
0/3 answered
  1. 1. Complement NB's decision rule is…
  2. 2. Rennie et al. called the multinomial NB problem with small classes…
  3. 3. ComplementNB's norm=True applies…

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Why and when

Variance argument. With nₖ words in class k, the error of a word probability estimate scales like √(θ(1 − θ)/nₖ). For a 1% class among 400 short reports, that is only about 4 reports’ worth of words. Its complement has 99 times as many (complement data ratio = (n − nₖ)/nₖ). The complement estimates are far less noisy.

What it gives up. The complement of class k mixes all the other classes, so it is not a model of class k at all. Complement NB is a discriminative heuristic in naive-Bayes form: it no longer yields calibrated class probabilities, and its scores are only for ranking.

Priors. Multinomial NB with the learned prior favours big classes. On a balanced test set or under a “treat every team equally” objective, a uniform prior helps (exercise 2: +6 to +9 points of balanced accuracy), but less than complement estimates do.

Weight normalisation equalises the L1 norm of each class’s weight vector, correcting a remaining length bias. Its effect depends on the data. In exercise 2 it was harmless with balanced classes but catastrophic under heavy imbalance (balanced accuracy 0.38 against 0.70). Large-class complements are built from few documents, so after normalisation their weights become comparatively extreme. Validate it; don’t assume it.

Interview questions.

  • Why not just reweight classes in multinomial NB? Reweighting fixes the prior but not the noisy small-class word estimates. Complement NB fixes the estimates.
  • Does complement NB give probabilities? Not meaningful ones. Calibrate its scores if you need them.
📝 Quick check (Level 3)
0/3 answered
  1. 1. Complement data ratio for a class with 4 of 400 documents?
  2. 2. Complement NB's scores are best treated as…
  3. 3. In exercise 2, weight normalisation under heavy skew…

Level 4: Expert

★★★★★ Expert⏱ 25 minResearchers: original papers and open problems.

Routing reports to unequal teams

History.

  • Rennie, Shih, Teevan and Karger (2003), “Tackling the poor assumptions of naive Bayes text classifiers”, identified the skewed-data bias and weight-magnitude errors, and proposed complement NB and the TF, IDF and length transforms.
  • Their transformed weight-normalised complement NB (TWCNB) rivalled SVMs on 20 Newsgroups and Reuters.
  • ComplementNB was added to scikit-learn in 2017 (v0.20).

Exercise 1. The hand example gives the scores 4.97 / 2.49 / 2.59, so “valve leak” goes to class 0. On synthetic reports with an 80/15/5% split, complement NB recalls the 5% class 86.3% of the time, against 76.1% for multinomial NB.

Exercise 2: imbalanced report routing. Setup: four teams, 400 training reports, a balanced test set, 15 repetitions. Each cell shows balanced accuracy / recall of the rarest team.

Team shares Multinomial NB MNB, uniform prior Complement NB Complement NB, normalised
25/25/25/25 0.870 / 0.865 0.870 / 0.868 0.892 / 0.896 0.888 / 0.886
60/25/10/5 0.722 / 0.425 0.789 / 0.579 0.840 / 0.703 0.680 / 0.424
85/10/4/1 0.524 / 0.030 0.613 / 0.096 0.704 / 0.270 0.378 / 0.024
  • Complement NB is best in every setting, even with balanced classes (+2 points).
  • Under imbalance its advantage grows: +12 points of balanced accuracy at 60/25/10/5 and +18 at 85/10/4/1 over multinomial NB. It recalls the 1% team 9 times as often.
  • Removing the prior helps multinomial NB but recovers only part of the gap. The small-class word estimates are still noisy.
  • Weight normalisation backfires under imbalance, falling below plain multinomial NB.
  • With 4 thermal reports in training, no method recalls that team well. Collect or synthesise more examples of rare classes.
🐍 Exercise 2 (research): imbalanced report routing
Simulate anomaly reports for four teams with balanced to highly skewed volumes; compare multinomial NB with learned and uniform priors and complement NB with and without weight normalisation by balanced accuracy and recall of the rarest team on a balanced test set.

Complement naive Bayes in AI, robotics and aerospace

  • Imbalanced ticket and anomaly routing: rare subsystems still get their reports.
  • Log severity classification: critical events are rare and must not be swamped.
  • Fast text baselines before training larger models.
  • Active-learning loops: a quick model to find candidate examples of rare classes for labelling.

References

  1. J. D. M. Rennie, L. Shih, J. Teevan, D. R. Karger (2003). “Tackling the poor assumptions of naive Bayes text classifiers.” ICML.
  2. A. McCallum, K. Nigam (1998). “A comparison of event models for naive Bayes text classification.” AAAI Workshop.
  3. H. He, E. A. Garcia (2009). “Learning from imbalanced data.” IEEE Transactions on Knowledge and Data Engineering 21(9).
  4. F. Pedregosa et al. (2011). “Scikit-learn: machine learning in Python.” JMLR 12.
  5. C. D. Manning, P. Raghavan, H. Schütze (2008). Introduction to Information Retrieval, chapter 13. Cambridge University Press.