Sub topic 7
Measuring performance: precision, recall, F1, and the confusion matrix
This chapter assumes you can train a scikit-learn classifier, such as the TF-IDF and logistic regression baseline from earlier chapters. It also assumes you know what a train/test split is. Here you learn to judge a sentiment classifier honestly. A single accuracy number hides most of what matters, so we break the results down by class and by error type.
Why accuracy is not enough
Accuracy is the share of predictions that are correct. It is easy to compute and easy to misread.
Suppose 90% of your reviews are positive. A model that predicts "positive" for every input scores 90% accuracy and finds no negative review. If your goal is to catch unhappy customers, that model is useless.
Sentiment data is often skewed like this. Star-rating corpora usually lean positive, and social media streams often hold mostly neutral text. So you need metrics that look at each class separately.
The confusion matrix
A confusion matrix is a table that counts predictions by true label and predicted label. In scikit-learn's convention, rows are true labels and columns are predicted labels. Other libraries sometimes flip the axes, so check the documentation before comparing tables.
The diagonal holds correct predictions. Every off-diagonal cell is a specific kind of mistake, such as "true negative predicted as neutral".
For one class, treated as the "positive" outcome in a one-versus-rest view, four counts matter:
| Term | Meaning for the class "neg" |
|---|---|
| True positive (TP) | Truly negative, predicted negative |
| False positive (FP) | Not negative, predicted negative |
| False negative (FN) | Truly negative, predicted something else |
| True negative (TN) | Not negative, predicted something else |
In sentiment work, "positive" in the TP/FP terms means "the class we are scoring". It does not mean positive sentiment. This naming collision confuses many learners, so say "the class under evaluation" in your own notes.
Precision, recall, and F1
For a given class:
- Precision = TP / (TP + FP). Of everything the model labeled with this class, how much was right?
- Recall = TP / (TP + FN). Of everything that truly has this class, how much did the model find?
- F1 = 2 · precision · recall / (precision + recall). This is the harmonic mean of the two. It is also equal to 2TP / (2TP + FP + FN).
The harmonic mean punishes imbalance between the two numbers. A model with precision 1.0 and recall 0.1 has F1 of about 0.18, not 0.55.
The two numbers answer different business questions:
- High precision matters when a false alarm is costly. An example is auto-escalating a support ticket to a human.
- High recall matters when missing a case is costly. An example is a brand team that must see every angry post.
A diagram of how the counts flow into the metrics:
A worked three-class example
Here is a confusion matrix for 200 test posts with labels negative, neutral, and positive. Rows are true labels and columns are predictions.
| True \ Predicted | neg | neu | pos |
|---|---|---|---|
| neg (50) | 35 | 10 | 5 |
| neu (30) | 4 | 20 | 6 |
| pos (120) | 6 | 14 | 100 |
The code below rebuilds label lists from this matrix. It then computes the metrics by hand and with scikit-learn, so you can check that they agree.
import numpy as np
from sklearn.metrics import classification_report, confusion_matrix
labels = ["neg", "neu", "pos"]
cm = np.array([
[35, 10, 5],
[4, 20, 6],
[6, 14, 100],
])
# Rebuild label lists that produce exactly this matrix.
y_true, y_pred = [], []
for i, true_label in enumerate(labels):
for j, pred_label in enumerate(labels):
count = int(cm[i, j])
y_true += [true_label] * count
y_pred += [pred_label] * count
# By hand: the diagonal is TP; column sums are predictions; row sums are truths.
tp = np.diag(cm)
precision = tp / cm.sum(axis=0)
recall = tp / cm.sum(axis=1)
f1 = 2 * precision * recall / (precision + recall)
for name, p, r, f in zip(labels, precision, recall, f1):
print(f"{name}: precision={p:.3f} recall={r:.3f} f1={f:.3f}")
print("accuracy:", tp.sum() / cm.sum())
print("macro F1:", f1.mean())
# Same numbers from scikit-learn.
print(confusion_matrix(y_true, y_pred, labels=labels))
print(classification_report(y_true, y_pred, labels=labels, digits=3))Reading the output:
- Accuracy is 155/200 = 0.775. That looks respectable.
- Positive does well: precision about 0.90, recall about 0.83, F1 about 0.87.
- Negative is middling: precision about 0.78, recall 0.70, F1 about 0.74.
- Neutral is the weak class: precision about 0.45, recall about 0.67, F1 about 0.54. The model over-predicts neutral, mostly by pulling in positives (14 cases) and negatives (10 cases).
The matrix shows where to look next. The 14 positive posts called neutral are a concrete list to read.
Averaging across classes
A report with one row per class needs a single summary number for comparisons. There are three common choices.
| Average | How it works | Use it when |
|---|---|---|
| Macro | Unweighted mean of per-class scores | Every class matters equally, including rare ones |
| Weighted | Mean weighted by class size | You care about overall performance on the real class mix |
| Micro | Pools all TP, FP, FN before computing | You want one global figure; for single-label tasks it equals accuracy |
For the example above, macro F1 is about 0.714 and weighted F1 is about 0.785. The gap exists because the weak neutral class is small, so it pulls the macro average down more than the weighted one.
Pick one average before you start comparing models, and report it by name. Writing "F1 = 0.71" with no qualifier is ambiguous.
Evaluating honestly
Good metrics computed the wrong way still mislead. These are the common errors.
Leakage between train and test
Duplicates and near-duplicates are common in reviews and social posts. Retweets, copy-pasted reviews, and templated spam can land in both splits. The model then looks better than it is. Deduplicate before splitting, and when posts come from the same author or product, split by that group.
Tuning on the test set
If you pick the model, the n-gram range, or the decision threshold by looking at test scores, the test set is no longer an independent measurement. Use three parts: train, validation for choices, and a test set you touch once at the end. Cross-validation on the training portion is an alternative to a fixed validation set.
Stratified splits
Use train_test_split(..., stratify=labels) so rare classes appear in every split in the same proportion. Without it, a small negative class can end up with very few test examples, and its recall becomes noisy.
Small test sets
A class with 30 test examples gives a recall that moves by several points if you change two or three predictions. Report the support (number of true examples per class), which classification_report prints. For important comparisons, compute a bootstrap confidence interval by resampling the test set, or compare models on the same cross-validation folds.
Label noise sets a ceiling
Human annotators often disagree on sentiment, especially on neutral and mixed text. If two people agree only 80% of the time, a model scoring 80% on that data is not necessarily bad. Measuring inter-annotator agreement, for example with Cohen's kappa, tells you a realistic ceiling.
Choosing a metric for your goal
Match the metric to the decision the model supports.
- Monitoring overall mood on a dashboard: weighted F1 and the confusion matrix, since the class mix is what you want to reflect.
- Detecting unhappy customers: recall and precision on the negative class specifically. Treat the other classes as supporting detail.
- Comparing models for a general-purpose release: macro F1, so a model cannot win by ignoring the neutral class.
- Ordinal ratings, such as 1 to 5 stars: a plain confusion matrix treats predicting 4 for a true 5 as equal to predicting 1. Consider mean absolute error alongside F1, or look at how far off-diagonal the errors fall.
Many classifiers output probabilities, not just labels. The default cutoff for choosing a label is the highest-probability class, and moving it trades precision against recall. In the binary case, lowering the threshold for "negative" finds more negatives (higher recall) and also flags more false alarms (lower precision). Plot a precision-recall curve on the validation set and choose a threshold from it. Do not choose it from the test set.
Common mistakes
- Reporting only accuracy on imbalanced data.
- Passing arguments to
classification_reportorconfusion_matrixin the wrong order. The signature is(y_true, y_pred). Swapping them transposes the matrix and swaps precision with recall. - Letting scikit-learn infer label order. Pass
labels=[...]so rows and columns match your own ordering across runs. - Ignoring the
zero_divisionwarning. A class the model never predicts has undefined precision. Setting it to 0 reports that honestly, but you should also ask why the class is never predicted. - Treating the neutral class as filler. It is often the largest source of confusion, because the boundary between mild opinion and no opinion is vague. The next chapter covers handling it.
Exercise
A model is evaluated on 100 test posts for the negative class. It predicts "negative" for 20 posts, and 15 of those are truly negative. There are 30 truly negative posts in total. Compute precision, recall, and F1 for the negative class.
Show answer
TP = 15, FP = 20 - 15 = 5, FN = 30 - 15 = 15. Precision = 15/20 = 0.75. Recall = 15/30 = 0.50. F1 = 2 · 0.75 · 0.50 / (0.75 + 0.50) = 0.75 / 1.25 = 0.60. Check with the other formula: 2·15 / (2·15 + 5 + 15) = 30/50 = 0.60.
Exercise
A team reports 92% accuracy for a three-class sentiment model and says it is ready to ship. What two pieces of information would you ask for before agreeing, and why?
Show answer
First, the class distribution (support per class). If one class makes up around 90% of the data, a majority-class guess already scores close to 92%. Second, the per-class precision and recall, or the confusion matrix. These show whether the rare classes, such as negative, are being found. You could also ask how the test set was built (deduplicated, stratified, untouched during tuning), because leakage or tuning on the test set inflates the score.