Sub topic 7
Why accuracy misleads on imbalanced data
This chapter assumes you can read the four cells of a binary confusion matrix (TP, FP, FN, TN). It also assumes you know the basic formulas for accuracy, precision and recall, and can read short Python snippets. The goal is to show when accuracy stops telling you anything useful, and which numbers to read instead.
What imbalance means
A dataset is imbalanced when one class is much rarer than the other. Common examples are fraud, equipment failure, disease screening and spam in a well-filtered inbox. The rare class is usually the positive class, and it is usually the class you care about.
Accuracy counts correct predictions from both classes in one number:
accuracy = (TP + TN) / (TP + TN + FP + FN)
When negatives dominate, TN is huge. It swamps the other three cells, so accuracy mostly measures how well the model handles the common class.
The always-negative model
The simplest demonstration is a model that never predicts the positive class.
from sklearn.metrics import confusion_matrix, accuracy_score, recall_score
y_true = [0] * 95 + [1] * 5
y_pred = [0] * 100 # a model that always predicts the negative class
print(confusion_matrix(y_true, y_pred, labels=[0, 1]))
# [[95 0]
# [ 5 0]]
print(accuracy_score(y_true, y_pred)) # 0.95
print(recall_score(y_true, y_pred)) # 0.0The model scores 95% accuracy and finds none of the five positives. The matrix shows why. All the correct predictions sit in TN, and the whole bottom row is wrong.
The baseline is the number to compare against. The majority-class rate (here 0.95) is what you get without learning anything. A reported accuracy of 96% on this data is barely better than doing nothing.
A model that does something
A model that finds some positives will often score lower accuracy than the do-nothing model. Suppose it catches 3 of the 5 positives and raises 10 false alarms among the 95 negatives. The code below also computes balanced accuracy. This is the average of recall and specificity, so each class counts equally whatever its size.
from sklearn.metrics import (
confusion_matrix, accuracy_score, precision_score,
recall_score, f1_score, balanced_accuracy_score,
)
y_true = [0] * 95 + [1] * 5
# First 95 are negatives: 10 wrongly flagged. Last 5 are positives: 3 found.
y_pred = [1] * 10 + [0] * 85 + [1] * 3 + [0] * 2
print(confusion_matrix(y_true, y_pred, labels=[0, 1]))
# [[85 10]
# [ 2 3]]
print("accuracy ", accuracy_score(y_true, y_pred)) # 0.88
print("precision ", round(precision_score(y_true, y_pred), 3)) # 0.231
print("recall ", recall_score(y_true, y_pred)) # 0.6
print("f1 ", round(f1_score(y_true, y_pred), 3)) # 0.333
print("balanced accuracy ", round(balanced_accuracy_score(y_true, y_pred), 3)) # 0.747Accuracy ranks this model (0.88) below the one that never finds a positive (0.95). If positives matter, the ranking is backwards. Recall rises from 0 to 0.6, and balanced accuracy rises from 0.5 to about 0.747. Precision is only 0.231, because most positive predictions are false alarms. That is a real weakness, and accuracy hides it too.
| Model | Accuracy | Recall | Precision | Balanced accuracy |
|---|---|---|---|---|
| Always negative | 0.95 | 0.0 | undefined (no positive predictions) | 0.5 |
| Finds 3 of 5, 10 false alarms | 0.88 | 0.6 | 0.231 | 0.747 |
The always-negative model has undefined precision because its denominator, TP + FP, is zero. scikit-learn returns 0.0 and warns unless you set zero_division. Treat that as a signal. A metric that cannot be computed tells you the model never made a positive prediction.
Prevalence also sinks precision
Imbalance affects precision as well, even for a good model. Take a screening test with 99% sensitivity (recall) and 95% specificity, applied to 10,000 people where 1% have the condition.
| Row | Actual positive | Actual negative |
|---|---|---|
| Predicted positive | TP = 99 | FP = 495 |
| Predicted negative | FN = 1 | TN = 9,405 |
Accuracy is (99 + 9,405) / 10,000 = 0.9504. Recall is 0.99. Precision is 99 / 594, about 0.167. Only one in six positive results is a real case, even though the test is strong on both error rates.
Recall and specificity are properties of the model. Precision also depends on how common the positive class is. The same model deployed on data with 10% positives would have much higher precision. When you compare precision across datasets, check the class ratios first.
How the distortion arises
flowchart TDThe block above is only a placeholder, so do not use it. Here is the diagram for this chapter.
Recall and precision both exclude TN from their formulas. That is why they stay informative when TN is large. They ignore the cell that accuracy is drowned by.
What to report instead
No single number is right for every task. These are the common choices.
- Recall and precision together. Report both, because each can be inflated alone. A model that flags everything has recall 1.0. A model that flags one sure case has high precision.
- F1. The harmonic mean of precision and recall, which equals 2TP / (2TP + FP + FN). It contains no TN term, so it is not inflated by negatives. It also weights the two errors equally, which may not match your costs.
- Balanced accuracy. The mean of recall and specificity. It is accuracy computed as if both classes were the same size. A coin flip scores 0.5 whatever the class ratio.
- Specificity or false positive rate. Useful when false alarms have a real cost, such as analyst time or patient anxiety. At low prevalence, even a small false positive rate produces many false positives in absolute terms, as the screening table showed.
- The confusion matrix itself. With raw counts you can always recompute any metric. Report them alongside the summary numbers.
The right choice follows from the cost of each error. If a missed positive is expensive, prioritize recall. If a false alarm is expensive, prioritize precision. If you can state a cost for each error type, you can compare models by expected cost directly instead of by a proxy metric.
Common mistakes
- Reporting accuracy without the baseline. Always compute the majority-class rate,
max(class counts) / total, next to your accuracy. - Resampling the test set. Oversampling or undersampling is sometimes used on training data to help a model learn the rare class. Apply it to the test set and the metrics no longer describe real deployment, because precision and accuracy depend on prevalence. Evaluate on data with the natural class ratio.
- Splitting without stratification. A random split of a 1% positive dataset can leave very few positives in the test set. Use
train_test_split(..., stratify=y)so both sets keep the ratio. - Tuning for accuracy. Cross-validation scored by accuracy will select models that favor the majority class. Pass a different
scoringargument, such as"f1","recall"or"balanced_accuracy". - Ignoring small counts. With 5 positives, one more found changes recall by 0.2. Metrics from a handful of positives are unstable, so look at the counts before trusting a percentage.
Exercise
Exercise
A fraud model is tested on 1,000 transactions, of which 20 are fraud. It flags 40 transactions as fraud, and 10 of those are actually fraud. Compute TP, FP, FN, TN, then accuracy, recall, precision and the accuracy of a model that always predicts "not fraud". What do the numbers say about the model?
Show answer
TP = 10 (flagged and fraud). FP = 40 - 10 = 30. FN = 20 - 10 = 10. TN = 1,000 - 10 - 30 - 10 = 950. Accuracy = (10 + 950) / 1,000 = 0.96. Recall = 10 / 20 = 0.5. Precision = 10 / 40 = 0.25. The always-"not fraud" model has accuracy 980 / 1,000 = 0.98, which beats the real model's 0.96 while catching no fraud. The real model finds half of the fraud, but three out of four of its flags are false alarms. Accuracy alone would rank the useless model higher.