Sub topic 2
Why a Model That Predicts the Majority Class Scores Well on Accuracy
This chapter assumes you can write basic Python and NumPy, know what binary classification is, and have used scikit-learn's train_test_split and estimators. You don't need any imbalance-specific knowledge. By the end, you will be able to explain why a model that has learned nothing can score about 95% accuracy. You will also know how to measure that effect on your own data and which baseline to compare against.
The Setup: A Rare Class That Matters
Many classification problems have a rare class that is the reason the model exists. Examples are fraud transactions, patients with a disease, and defective parts on a production line. In this tutorial the rare class is called the minority class and is labelled 1, also known as the positive class. The common class is the majority class and is labelled 0.
Accuracy is the fraction of predictions that are correct:
accuracy = (correct predictions) / (all predictions)
In terms of the confusion matrix cells, this is (TP + TN) / (TP + TN + FP + FN). Here TP is true positives, TN is true negatives, FP is false positives, and FN is false negatives.
Accuracy counts every example equally. It does not ask which class an example belongs to, so a mistake on a rare example costs the same as a mistake on a common one. When 95% of examples belong to one class, that class makes up 95% of the score.
The Base Rate and the Trivial Classifier
The base rate is the share of examples that belong to a class. The majority base rate is the share of the largest class. Consider a classifier that ignores its input and always predicts the majority class. Its accuracy equals the majority base rate. This value is sometimes called the null accuracy.
| Positive share | Majority share | Accuracy of "always predict 0" | Positives found |
|---|---|---|---|
| 50% | 50% | 0.50 | 0 of 100 |
| 20% | 80% | 0.80 | 0 of 100 |
| 5% | 95% | 0.95 | 0 of 100 |
| 1% | 99% | 0.99 | 0 of 100 |
| 0.1% | 99.9% | 0.999 | 0 of 100 |
The last column never changes. The trivial classifier finds none of the positives at any ratio, but its accuracy climbs as the data becomes more skewed. The more imbalanced the data, the better a useless model looks.
Seeing It in Code
The example below builds a synthetic dataset with about 5% positives. It splits the data with stratification, which keeps the class ratio the same in the train and test sets. Then it fits scikit-learn's DummyClassifier with the most_frequent strategy. This estimator learns nothing from the features. It only remembers the most common training label.
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.dummy import DummyClassifier
from sklearn.metrics import accuracy_score, recall_score
X, y = make_classification(
n_samples=10000,
n_features=20,
n_informative=5,
weights=[0.95, 0.05],
flip_y=0.01,
random_state=42,
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=42
)
baseline = DummyClassifier(strategy="most_frequent").fit(X_train, y_train)
pred = baseline.predict(X_test)
print("accuracy:", accuracy_score(y_test, pred))
print("minority recall:", recall_score(y_test, pred))Expect an accuracy of about 0.95 and a minority recall of 0.0. The accuracy is not exactly 0.95 because flip_y=0.01 assigns a small share of labels at random, which moves the positive share slightly above 5%. Recall is the fraction of real positives the model finds, and here it is exactly zero.
The model catches no positives, yet an accuracy-only report would show 0.95 and look like a success.
Looking at the Confusion Matrix
Accuracy collapses four numbers into one, so it hides which kind of error is happening. The confusion matrix shows all four. The next snippet runs on its own and prints the matrix along with the base rate.
import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.dummy import DummyClassifier
from sklearn.metrics import confusion_matrix, balanced_accuracy_score
X, y = make_classification(
n_samples=10000,
n_features=20,
n_informative=5,
weights=[0.95, 0.05],
flip_y=0.01,
random_state=42,
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=42
)
pred = DummyClassifier(strategy="most_frequent").fit(X_train, y_train).predict(X_test)
print("positive share in test set:", np.mean(y_test))
print("confusion matrix [[TN, FP], [FN, TP]]:")
print(confusion_matrix(y_test, pred))
print("balanced accuracy:", balanced_accuracy_score(y_test, pred))The output has this shape:
- The right-hand column is all zeros, because the model never predicts class
1. That means FP = 0 and TP = 0. - The bottom-left cell, FN, holds every real positive. All of them were missed.
- The top-left cell, TN, holds every negative, all predicted correctly.
- Balanced accuracy is 0.5. It is the mean of recall on each class, here (1.0 + 0.0) / 2. It is the score of a coin flip, which is a more honest summary of this model than 0.95.
The next chapter covers precision, recall and F1 in detail. For now, note that the zero in the TP cell is the information accuracy hides.
Why This Happens: The Mechanism
Three facts combine to produce the effect.
- Accuracy weights every example equally. The score is a plain count of correct predictions, with no notion of which examples matter more.
- The majority class dominates the count. With 95% negatives, getting all negatives right already yields 0.95, however the positives are handled.
- Training objectives often behave the same way. Most classifiers minimize an average loss over all training examples. The average is dominated by the majority class, so a model can lower its loss by fitting the majority well and treating the minority as noise.
The third point matters for later chapters. The accuracy pitfall is a problem in measurement. The model itself can also be biased toward the majority class, and that bias is what class weights and resampling try to correct.
It Is Not Only About Dummy Models
A real model can fall into the same trap in less obvious ways.
- A weak model that rarely predicts positive. Suppose a classifier flags 10 of 1,000 real positives and gets everything else right. In a 95%/5% dataset its accuracy is about 0.953, which is barely above the 0.95 baseline. Its recall is 1%. The accuracy difference is small, and a reader looking only at the second decimal place may miss it.
- A model that is much better but still looks the same. A model that finds 70% of positives at the cost of some false alarms may score 0.96 accuracy. The gap between a nearly useless model and a very useful one can be one or two points of accuracy, which is within the noise of a typical test set.
- A tuned model that gets worse. If you tune hyperparameters to maximize accuracy, the search can favor settings that predict the majority class more often. You then optimize toward the useless model.
Always compare accuracy to the null accuracy, not to 1.0. A score of 0.95 is excellent when the base rate is 0.50 and meaningless when the base rate is 0.95.
When Accuracy Is Still Fine
Accuracy is not always wrong. It is a reasonable metric when both of these hold:
- The classes are roughly balanced.
- Errors in either direction cost about the same.
It also remains useful as a secondary number, as long as you report the base rate beside it. Be careful with multiclass problems. The same effect appears when one of many classes dominates, even if no class exceeds 50%. A majority share of 40% in a ten-class problem still makes accuracy easy to inflate for the dominant class.
A Practical Checklist
Use these steps before you trust any accuracy number on a classification task:
- Compute the class counts with
np.bincount(y)orpd.Series(y).value_counts(). - Compute the null accuracy, which is the share of the largest class.
- Fit a
DummyClassifier(strategy="most_frequent")as a baseline and score it with the metric you plan to use for your real model. - Print the confusion matrix, not just a single score.
- Report at least one metric that focuses on the rare class, such as recall, precision or average precision.
- Split with
stratify=yso that a small test set still contains enough positives to measure.
Common Errors
- Reporting accuracy without the base rate. A reader cannot tell if 0.97 is good. Always state the majority share beside it.
- Treating a high score as proof of a working pipeline. A very high accuracy on an imbalanced problem can mean the model predicts a single class. Check the confusion matrix first.
- Using accuracy as the scoring function in a grid search. The search will reward majority-class behavior. Choose a scorer such as
average_precision,f1orrecallinstead. - Evaluating on a split without stratification. A random split can leave the test set with a very different positive share, or none at all, which makes comparisons across runs meaningless.
Exercise
A fraud dataset has 2,000 transactions, and 40 of them are fraud. A model labels every transaction as legitimate. What are its accuracy, its recall for fraud, and its balanced accuracy? Then a second model catches 20 of the 40 frauds and wrongly flags 60 legitimate transactions. Compute its accuracy and say whether accuracy makes it look better or worse than the first model.
Show answer
The first model is correct on 1,960 of 2,000 transactions, so accuracy is 1,960 / 2,000 = 0.98. Recall for fraud is 0 / 40 = 0.0. Balanced accuracy is (1.0 + 0.0) / 2 = 0.5. The second model has TP = 20, FN = 20, FP = 60 and TN = 1,900. Its accuracy is (20 + 1,900) / 2,000 = 0.96, and its recall is 20 / 40 = 0.5. Accuracy rates the second model lower (0.96 against 0.98), even though it finds half of the fraud and the first model finds none. This is the accuracy pitfall: the useless model wins on accuracy. Its balanced accuracy is (0.5 + 1,900/1,960) / 2, which is about 0.73, and that correctly ranks it above the first model.