Sub topic 14
Evaluating the classifier
This chapter assumes you can train a scikit-learn naive Bayes text pipeline and know what a train/test split is. Here you will measure how well that classifier works and avoid the usual mistakes.
Why accuracy is not enough
Accuracy is the fraction of predictions that are correct. It misleads when classes are imbalanced. If 95% of messages are ham, a model that always predicts "ham" scores 95% and catches no spam.
Start from the confusion matrix, which counts predictions per true class. For spam as the positive class:
- True positives (TP): spam predicted as spam.
- False positives (FP): ham predicted as spam.
- False negatives (FN): spam predicted as ham.
- True negatives (TN): ham predicted as ham.
From these counts:
- Precision = TP / (TP + FP). Of the messages flagged as spam, how many really are spam.
- Recall = TP / (TP + FN). Of the real spam, how much was caught.
- F1 is the harmonic mean of precision and recall.
Which metric matters depends on the cost of errors. A spam filter usually favors precision, since losing a real email is worse than seeing one spam message.
A worked example
The code below trains on a public newsgroup dataset and reports per-class metrics. It downloads data on first run.
from sklearn.datasets import fetch_20newsgroups
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics import classification_report, confusion_matrix
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import make_pipeline
cats = ["rec.autos", "sci.space", "talk.politics.misc"]
remove = ("headers", "footers", "quotes")
train = fetch_20newsgroups(subset="train", categories=cats, remove=remove)
test = fetch_20newsgroups(subset="test", categories=cats, remove=remove)
clf = make_pipeline(CountVectorizer(), MultinomialNB(alpha=1.0))
clf.fit(train.data, train.target)
pred = clf.predict(test.data)
print(confusion_matrix(test.target, pred))
print(classification_report(test.target, pred, target_names=train.target_names))Each row of the confusion matrix is a true class and each column is a predicted class. Large off-diagonal values show which classes the model confuses.
Common errors
- Removing headers, footers, and quotes matters. Without it, the model can learn email addresses and signatures that leak the label, and the score looks better than real performance.
- Fitting the vectorizer on all data before splitting leaks test vocabulary into training. Putting it inside the pipeline avoids this.
- Reading
predict_probaas true confidence. Naive Bayes probabilities are usually pushed toward 0 or 1, so use them for ranking, not as literal probabilities. - Judging from one split. Use cross-validation for a steadier estimate.
from sklearn.model_selection import cross_val_score
scores = cross_val_score(clf, train.data, train.target, cv=5, scoring="f1_macro")
print(scores.mean(), scores.std())Macro F1 averages F1 across classes equally, so small classes count as much as large ones. Use alpha as the one hyperparameter to tune, selecting it by cross-validation and not by test score.
The evaluation loop
Exercise
A fraud detector flags 1% of transactions, and 1% of all transactions are truly fraud. It catches 40 of 100 frauds and wrongly flags 60 legitimate ones. Compute precision and recall for the fraud class.
Show answer
TP = 40, FN = 60, FP = 60. Precision = 40 / (40 + 60) = 0.40. Recall = 40 / (40 + 60) = 0.40. Accuracy would be high because most transactions are legitimate, which is why precision and recall are the better measures here.