Sub topic 14
Evaluating the classifier
This chapter assumes you can train a naive Bayes model in scikit-learn, as in the previous chapters, and that you know the train/test split and the terms precision and recall. Here you will learn how to measure whether a model is good, which numbers to trust, and which mistakes make results look better than they are.
Start with a baseline
A score means little without something to compare it to. If 90% of your messages are ham, a model that always answers "ham" gets 90% accuracy and catches no spam. Before you judge naive Bayes, run a baseline that ignores the text. scikit-learn provides DummyClassifier, and strategy="most_frequent" predicts the majority class.
If naive Bayes does not clearly beat this baseline on the metric you care about, the features, the labels, or the evaluation setup need attention.
Read the confusion matrix first
A confusion matrix counts predictions by true class and predicted class. For a binary problem with "spam" as the positive class, it has four cells:
- True positives (TP): spam predicted as spam.
- False positives (FP): ham predicted as spam. A real email lands in the junk folder.
- False negatives (FN): spam predicted as ham. Junk reaches the inbox.
- True negatives (TN): ham predicted as ham.
Every common metric is built from these four counts.
| Metric | Formula | Use it when |
|---|---|---|
| Accuracy | (TP + TN) / all | Classes are balanced and errors cost the same |
| Precision | TP / (TP + FP) | A false alarm is expensive |
| Recall | TP / (TP + FN) | A missed positive is expensive |
| F1 | 2PR / (P + R) | You need one number that balances precision and recall |
| Macro F1 | Mean of per-class F1 | Classes are imbalanced and each one matters equally |
For more than two classes, classification_report gives precision, recall, and F1 per class. Macro averaging gives each class equal weight. Weighted averaging weights each class by its size, so it hides poor results on rare classes. Prefer macro F1 when a rare class matters.
Evaluate without leaking information
Naive Bayes learns from counts, and so does the vectorizer that creates them. CountVectorizer learns a vocabulary, and that vocabulary is part of the model. If you fit it on all your data before splitting, words that appear only in the test set leak into training. The score then looks better than real-world performance.
The fix is to put the vectorizer and the classifier in one Pipeline. Cross-validation then refits both on the training part of each fold. The same rule applies to any preprocessing that learns from data, such as TF-IDF weighting or feature selection.
Use stratified splits. StratifiedKFold keeps the class proportions the same in every fold, so a rare class is not missing from a test fold. With small datasets, a single train/test split gives a noisy score. Cross-validation averages over several splits and shows how much the score varies.
A complete evaluation
The code below compares the baseline with multinomial naive Bayes. It uses cross_val_predict, which returns one out-of-fold prediction per document. Then it tunes alpha and the binary-count option with a grid search scored by macro F1. The dataset is tiny so the script runs instantly. Real evaluations need far more data.
from sklearn.dummy import DummyClassifier
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics import classification_report, confusion_matrix
from sklearn.model_selection import GridSearchCV, StratifiedKFold, cross_val_predict
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import make_pipeline
spam = [
"free prize now", "win free cash now", "free offer click now",
"claim your prize today", "cheap offer free gift", "win a free prize",
"limited offer click now", "free cash prize",
]
ham = [
"meeting at noon", "project meeting notes", "lunch at noon today",
"send the project notes", "notes from the meeting", "see you at lunch",
"project deadline today", "review the meeting notes",
]
texts = spam + ham
labels = ["spam"] * len(spam) + ["ham"] * len(ham)
classes = ["spam", "ham"]
cv = StratifiedKFold(n_splits=4, shuffle=True, random_state=0)
models = {
"baseline": DummyClassifier(strategy="most_frequent"),
"naive bayes": MultinomialNB(alpha=1.0),
}
for name, model in models.items():
pipe = make_pipeline(CountVectorizer(), model)
pred = cross_val_predict(pipe, texts, labels, cv=cv)
print(name)
print(confusion_matrix(labels, pred, labels=classes))
print(classification_report(labels, pred, labels=classes, zero_division=0))
pipe = make_pipeline(CountVectorizer(), MultinomialNB())
grid = GridSearchCV(
pipe,
{
"multinomialnb__alpha": [0.01, 0.1, 1.0],
"countvectorizer__binary": [False, True],
},
scoring="f1_macro",
cv=cv,
)
grid.fit(texts, labels)
print("best params:", grid.best_params_)
print("best cross-validated macro F1:", grid.best_score_)In the confusion matrix, labels=classes fixes the row and column order as spam, then ham. Without it, scikit-learn sorts the labels alphabetically, which puts ham first. Pass zero_division=0 to classification_report so the baseline, which never predicts spam, reports precision 0 for spam without a warning.
Tuning without fooling yourself
GridSearchCV reports best_score_, which is the best of several tries on the same folds. That score is slightly optimistic, because you picked the winner after seeing the results. For an honest final number, hold out a test set before tuning, tune only on the rest, and score the chosen model on the held-out set once.
For naive Bayes, the parameters worth searching are few:
alpha: values below 1 often work better on large vocabularies, because Laplace smoothing withalpha=1can overweight rare words.- Binary versus raw counts: binary counts reduce the influence of a word repeated many times.
- Vocabulary limits such as
min_dfandstop_words, which change which words get likelihoods at all.
Judge probabilities separately
Accuracy and F1 only check the predicted label. If you use predict_proba to rank messages, set a threshold, or combine scores with other signals, you also need to check the probabilities. sklearn.metrics.log_loss and brier_score_loss penalize confident wrong answers.
Naive Bayes often has a good F1 and a poor log loss. Repeated, correlated words multiply together, which pushes probabilities toward 0 and 1. A later chapter covers calibration. For now, treat a naive Bayes probability as a score for ranking, not as a literal chance.
If you need a different balance of errors, move the decision threshold instead of retraining. Predict spam when predict_proba for spam exceeds 0.8 rather than 0.5, and precision rises while recall falls. Choose the threshold on validation data, not on the test set.
Common errors
- Fitting the vectorizer on all text before splitting, which leaks vocabulary.
- Reporting only accuracy on imbalanced data.
- Choosing alpha with the same test set you report.
- Trusting a score from a few dozen test examples. Check the spread across folds.
- Reading
predict_probaoutputs as calibrated probabilities. - Comparing models on different splits. Use the same
cvobject for every model.
Exercise
A fraud dataset is 99% legitimate. A model scores 99% accuracy. What two checks tell you whether it is useful, and which metric would you report?
Show answer
Compare it with a most-frequent-class baseline, which also scores 99%, and look at the confusion matrix to see how many fraud cases are caught. Report recall and precision for the fraud class, or macro F1, instead of accuracy.
Exercise
You call CountVectorizer().fit_transform(texts) on all documents, then run cross_val_score(MultinomialNB(), X, labels). What is wrong, and how do you fix it?
Show answer
The vocabulary was learned from every document, including those later used as test folds, so test information leaks into training. Put the vectorizer and classifier in one pipeline, for example make_pipeline(CountVectorizer(), MultinomialNB()), and pass the raw texts to cross_val_score.
Exercise
A spam filter must never send a real email to the junk folder, even if some spam gets through. Which error type matters most, which metric should you favor, and how can you change behavior without retraining?
Show answer
False positives (ham predicted as spam) matter most, so favor precision for the spam class. Raise the spam probability threshold above 0.5, chosen on validation data, so the model flags only messages it is very sure about.