Sub topic 4
When accuracy misleads: imbalanced classes
This chapter assumes you can read basic Python, know what supervised binary classification is, and have seen a train/test split. You should also know the four confusion matrix cells (TP, FP, TN, FN) and the accuracy formula from earlier in this tutorial. Here you will see why accuracy can look excellent for a model that does nothing useful, and what to check before trusting it.
Accuracy depends on the class mix
Accuracy is the share of predictions that are correct:
accuracy = (TP + TN) / (TP + FP + TN + FN)
The formula treats every example the same. When the two classes are roughly equal in size, that is reasonable. When one class is much larger, correct predictions on that class dominate the number. The model gets credit for the easy, common case, and the rare case barely moves the score.
A dataset is imbalanced when one class (the majority class) is much more frequent than the other (the minority class). In many real problems the minority class is the one you care about:
- Fraud: roughly 1 in 1,000 transactions or fewer.
- Disease screening: a small share of patients have the condition.
- Equipment failure: most machines are fine on a given day.
- Spam in a well-filtered inbox, or defects on a production line.
The prevalence of the positive class is its share of the data, positives / total. Prevalence is the number that tells you how worried to be.
The accuracy paradox
The accuracy paradox is the fact that a model with high accuracy can be worse than a model with lower accuracy. Start with the simplest case, a model that always predicts the majority class:
# 1 fraud case in 100 transactions; the model predicts "not fraud" every time
y_true = [1] + [0] * 99
y_pred = [0] * 100
correct = sum(t == p for t, p in zip(y_true, y_pred))
print(correct / len(y_true)) # 0.99
tp = 0
fn = 1
print(tp / (tp + fn)) # 0.0This model scores 0.99 accuracy. It also never detects a single fraud case. Its recall, the share of real positives it found (TP / (TP + FN)), is 0.0. The accuracy figure is correct arithmetic, but it answers a question nobody asked: "How often does the model agree with the labels, mostly on the easy class?"
The majority-class baseline
The model above is a useful reference point. Its accuracy is the majority-class baseline: the accuracy you get by ignoring the input and always predicting the most common class.
For a binary problem with positive prevalence p, the baseline is max(p, 1 - p). For a multiclass problem it is the share of the largest class.
| Positive prevalence | Majority-class baseline accuracy |
|---|---|
| 50% | 0.500 |
| 10% | 0.900 |
| 1% | 0.990 |
| 0.1% | 0.999 |
Any reported accuracy only means something relative to this baseline. On a 1% prevalence problem, a model with 0.985 accuracy is worse than doing nothing. Always compute the baseline first. It takes one line.
scikit-learn provides DummyClassifier for this purpose. The most_frequent strategy always predicts the most common class in the training labels:
from sklearn.dummy import DummyClassifier
from sklearn.metrics import accuracy_score, balanced_accuracy_score, recall_score
X = [[i] for i in range(1000)] # features are irrelevant to this baseline
y = [1] * 20 + [0] * 980 # 2% positives
baseline = DummyClassifier(strategy="most_frequent").fit(X, y)
pred = baseline.predict(X)
print(accuracy_score(y, pred)) # 0.98
print(recall_score(y, pred)) # 0.0
print(balanced_accuracy_score(y, pred)) # 0.5Here we fit and score on the same data only because the baseline ignores the features. A real model must be scored on held-out test data.
When a better model gets a lower accuracy
The paradox is stronger than "high accuracy can hide a useless model". Accuracy can also rank a useful model below a useless one. Consider 1,000 examples with 20 positives (2% prevalence) and three models:
# (tp, fp, tn, fn) for each model; 20 positives and 980 negatives in all
models = {
"always negative": (0, 0, 980, 20),
"model A": (10, 5, 975, 10),
"model B": (18, 40, 940, 2),
}
for name, (tp, fp, tn, fn) in models.items():
accuracy = (tp + tn) / (tp + fp + tn + fn)
recall = tp / (tp + fn)
print(f"{name:16} accuracy={accuracy:.3f} recall={recall:.2f} false alarms={fp}")
# always negative accuracy=0.980 recall=0.00 false alarms=0
# model A accuracy=0.985 recall=0.50 false alarms=5
# model B accuracy=0.958 recall=0.90 false alarms=40Ranked by accuracy, the order is model A, then "always negative", then model B. Model B finds 18 of the 20 positives. Model A finds 10. The "always negative" model finds none. Yet model B has the lowest accuracy, because its 40 false alarms cost more accuracy than its extra detections gain.
Whether model B is the best choice depends on what a false alarm costs compared with a missed positive. That is the topic of a later chapter. The point here is narrower: accuracy cannot even express the question, because it counts a false positive and a false negative as the same single error.
A checklist for imbalanced data
Before you trust an accuracy number, work through these steps.
- Count the classes. Use
collections.Counter(y_test)orpandas.Series.value_counts(). Note the prevalence of the positive class. - Compute the majority-class baseline. Compare your model with it, not with 1.0.
- Read the confusion matrix. Look at FN and FP separately. A model with a large FN count on the class you care about has a problem, whatever its accuracy.
- Report per-class metrics. Recall and precision on the positive class show what accuracy hides. The next chapters define them in depth.
- Consider balanced accuracy as a quick sanity check. It is the mean of the recall of each class, so every class counts equally regardless of size. For the majority-class model on a binary problem it is always 0.5.
Edge cases and mistakes
Multiclass imbalance
The same effect appears with more than two classes. If one class makes up 90% of the data, a model that always predicts it scores 0.90. The baseline is the share of the largest class, and a good model must beat that. Rare classes can be wrong on almost every example without much effect on the total.
Imbalance in the test set, not only the training set
What matters for evaluation is the class mix of the data you score on. A few points:
- Use a stratified split (
train_test_split(..., stratify=y)) so the test set keeps the same prevalence as the full data. Otherwise a small test set may contain very few positives, or none. - Do not rebalance the test set by oversampling or undersampling. Resampling is a training technique. If you resample the test set, your metrics describe a world with a different prevalence than the one the model will see in production.
- With only a handful of positives in the test set, every metric about the positive class is noisy. One extra missed positive can move recall by several percentage points. Say how many positives you evaluated on.
Prevalence shifts after deployment
A model evaluated at 2% prevalence may later run on data with 0.2% prevalence. Accuracy then rises toward 0.998 on its own, because the baseline moved, even if the model did not change. Compare accuracy only between runs with the same class mix.
Accuracy is not always wrong
Accuracy is a fine summary when classes are close to balanced and the cost of both error types is similar. The problem is not the metric itself. The problem is reading it without the class counts beside it. If your data is 55% / 45%, the baseline is 0.55, and accuracy tells you a lot.
Fixing the metric versus fixing the model
Imbalance affects two separate things. First, how you measure: use the checklist above. Second, how you train: class weights (class_weight="balanced" in many scikit-learn models), resampling the training set, or changing the decision threshold. Changing training does not make accuracy a better metric. After any such change, the model should still be judged on an untouched test set with the original class mix.
Summary
- Accuracy counts all correct predictions equally, so the majority class dominates it.
- On imbalanced data a model that always predicts the majority class can reach 0.99 accuracy with 0.0 recall.
- The majority-class baseline,
max(p, 1 - p)for binary data, is the number to beat.DummyClassifier(strategy="most_frequent")computes it. - Accuracy can rank a useful model below a useless one, because it does not distinguish false positives from false negatives.
- Always check class counts, the confusion matrix, and per-class metrics. Keep the test set's natural class mix, stratify your splits, and state how many positives you tested on.
Exercise
A test set has 2,000 examples, 40 of them positive. Model X has TP=25, FP=60, TN=1900, FN=15. (a) What is the majority-class baseline accuracy? (b) What is Model X's accuracy, and does it beat the baseline? (c) What is its recall on the positive class, and what does comparing (b) and (c) tell you?
Show answer
(a) The negatives number 1,960, so the baseline is 1960 / 2000 = 0.98. (b) Accuracy is (25 + 1900) / 2000 = 1925 / 2000 = 0.9625, which is below the 0.98 baseline, so by accuracy alone the model is worse than always predicting negative. (c) Recall is 25 / (25 + 15) = 0.625, so the model finds 62.5% of the real positives, while the always-negative model finds 0%. Accuracy ranks the model below a model that detects nothing, which shows that accuracy is the wrong metric here. Whether Model X is good depends on the cost of its 60 false alarms versus the 15 missed positives.
Exercise
You are given a three-class problem where class "a" is 90% of the data, class "b" is 7%, and class "c" is 3%. A model reaches 0.91 accuracy. Why is that number not convincing, and what two checks would you run next?
Show answer
Always predicting "a" gives a baseline accuracy of 0.90, so 0.91 is only one point better and the model may be ignoring "b" and "c". First, compute the per-class recall (or a confusion matrix) to see how many "b" and "c" examples are found. Second, compute balanced accuracy, the mean of the per-class recalls, which counts each class equally. A majority-class predictor would score 1/3 there.