TExcelTAD
Home › Training Mechanics, Evaluation & Model Improvement › Class Imbalance: Training and Evaluating

Class Imbalance: Training and Evaluating

Fraud is 0.2 % of card payments, a rare disease 1 % of patients, a defective part 3 % of production. In such problems a model that always says "no" is right almost every time, and useless. Class imbalance affects two things: how the model learns (the loss is dominated by the majority class) and, more dangerously, how you measure it (the usual metrics hide the failure). Data Preparation covers the resampling methods themselves; this lesson is about choosing the metric, training with the imbalance in mind, and keeping the evaluation honest.

Why accuracy misleads

With a positive share (prevalence) π\pi, the classifier that always predicts the majority class has accuracy 1−π1 - \pi. At π=0.03\pi = 0.03 that is 0.97. Metrics that look at the minority class directly are:

recall=TPTP+FN,precision=TPTP+FP,balanced accuracy=12(TPTP+FN+TNTN+FP)\text{recall} = \frac{TP}{TP + FN}, \qquad \text{precision} = \frac{TP}{TP + FP}, \qquad \text{balanced accuracy} = \frac{1}{2}\left(\frac{TP}{TP + FN} + \frac{TN}{TN + FP}\right)

plus the threshold-free PR-AUC (average precision), whose chance level is π\pi rather than 0.5. ROC-AUC is insensitive to prevalence, which is a strength for comparing models and a weakness for judging usefulness: a ROC-AUC of 0.9 can still mean most alarms are false. Definitions in Accuracy, Precision, Recall, F1 and ROC-AUC, PR-AUC.

python · try it yourself
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.linear_model import LogisticRegression
from sklearn.metrics import (accuracy_score, balanced_accuracy_score, recall_score,
                             precision_score, roc_auc_score, average_precision_score)

X, y = make_classification(n_samples=6000, n_features=10, n_informative=4, weights=[0.97],
                           class_sep=1.5, random_state=0)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.5, stratify=y, random_state=0)
print(f"positives in test: {y_te.sum()} of {len(y_te)}")
for name, m in [("always 'no'", DummyClassifier(strategy="most_frequent")),
                ("logistic", LogisticRegression())]:
    m.fit(X_tr, y_tr)
    pred, score = m.predict(X_te), m.predict_proba(X_te)[:, 1]
    print(f"{name:12s} acc {accuracy_score(y_te, pred):.3f}  bal-acc {balanced_accuracy_score(y_te, pred):.3f}"
          f"  recall {recall_score(y_te, pred):.3f}  precision {precision_score(y_te, pred, zero_division=0):.3f}"
          f"  ROC-AUC {roc_auc_score(y_te, score):.3f}  PR-AUC {average_precision_score(y_te, score):.3f}")
positives in test: 105 of 3000
always 'no'  acc 0.965  bal-acc 0.500  recall 0.000  precision 0.000  ROC-AUC 0.500  PR-AUC 0.035
logistic     acc 0.971  bal-acc 0.581  recall 0.162  precision 1.000  ROC-AUC 0.766  PR-AUC 0.410

The test set has 105 positives among 3000 rows (3.5 %). Doing nothing scores an accuracy of 0.965; the trained logistic regression scores 0.971, almost the same, yet the two are very different models. Balanced accuracy (0.500 vs 0.581) and recall (0.000 vs 0.162) show what accuracy hides: at the default threshold of 0.5 the model flags only a sixth of the positives, but every flag is right (precision 1.000). The threshold-free scores say there is real signal to use: ROC-AUC 0.766 and PR-AUC 0.410, against chance levels of 0.5 and 0.035.

The lab: prevalence and the PR curve

The threshold lab with 5 % positives. The ROC curve and its AUC depend only on how well the two score distributions are separated, not on how many positives there are. Move the share of positives slider up to 0.5 and back down: the ROC curve stays put, while the PR curve and the precision at the current threshold collapse as positives become rare. Then lower the threshold until recall is about 0.8 and read the precision.

05010005scorecountScores by true classpositive →← negativenegativepositivepredicted +predicted −actual posactual neg23TP27FN74FP876TNprecision 0.237 recall 0.460 F1 0.3130.00.51.00.00.51.0false positive rateTPRROC curveAUC 0.833- - chance0.00.51.00.00.51.0recallprecisionPrecision-recallAP 0.322- - chance

Training with the imbalance

Three common responses, on the same data: class weights (each minority example counts n2n1\frac{n}{2 n_1} times in the loss, as class_weight="balanced" does), moving the threshold on an unweighted model, and doing nothing. Thresholds are chosen here for the illustration; in practice choose them on validation data (Log Loss and Choosing a Threshold).

python · try it yourself
import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import recall_score, precision_score, f1_score, average_precision_score

X, y = make_classification(n_samples=6000, n_features=10, n_informative=4, weights=[0.97],
                           class_sep=1.5, random_state=0)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.5, stratify=y, random_state=0)
plain = LogisticRegression().fit(X_tr, y_tr)
weighted = LogisticRegression(class_weight="balanced").fit(X_tr, y_tr)
for name, m, thr in [("plain, threshold 0.5", plain, 0.5), ("plain, threshold 0.1", plain, 0.1),
                     ("balanced weights, 0.5", weighted, 0.5)]:
    p = m.predict_proba(X_te)[:, 1]
    pred = (p >= thr).astype(int)
    print(f"{name:22s} recall {recall_score(y_te, pred):.3f}  precision {precision_score(y_te, pred, zero_division=0):.3f}"
          f"  F1 {f1_score(y_te, pred):.3f}  PR-AUC {average_precision_score(y_te, p):.3f}  mean p {p.mean():.3f}")
plain, threshold 0.5   recall 0.162  precision 1.000  F1 0.279  PR-AUC 0.410  mean p 0.035
plain, threshold 0.1   recall 0.467  precision 0.280  F1 0.350  PR-AUC 0.410  mean p 0.035
balanced weights, 0.5  recall 0.705  precision 0.085  F1 0.152  PR-AUC 0.323  mean p 0.380

The unweighted model's mean predicted probability, 0.035, equals the share of positives in the data: its probabilities are about right, they are just rarely above 0.5. Moving the threshold to 0.1 trades precision for recall (0.467 recall, 0.280 precision) and gives the best F1 of the three, 0.350. Balanced class weights push every probability up (mean 0.380) and reach recall 0.705 at the default threshold, with precision 0.085: about 11 false alarms per caught positive. Which operating point is right depends on the costs, not on the metric. Note also that reweighting changed the ranking slightly (PR-AUC 0.410 to 0.323 here): on this data it did not help, and it made the probabilities wrong. Reweighting is most useful for models without a threshold to move, or when the minority class is so rare that the unweighted fit ignores it.

Resampling belongs inside the folds

Oversampling copies (or synthesises) minority rows. Done before cross-validation, copies of the same row land in training and validation folds, and a flexible model recognises them: the same contamination as in Data Leakage in Evaluation. With imbalanced-learn's Pipeline the sampler runs on each training fold only and never touches validation data:

python · try it yourself
from sklearn.datasets import make_classification
from sklearn.model_selection import cross_val_score, StratifiedKFold
from sklearn.tree import DecisionTreeClassifier
from imblearn.over_sampling import RandomOverSampler
from imblearn.pipeline import make_pipeline

X, y = make_classification(n_samples=3000, n_features=10, n_informative=4, weights=[0.95],
                           flip_y=0.02, random_state=1)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
tree = DecisionTreeClassifier(random_state=0)

X_os, y_os = RandomOverSampler(random_state=0).fit_resample(X, y)      # WRONG: before the split
wrong = cross_val_score(tree, X_os, y_os, cv=cv, scoring="f1")
right = cross_val_score(make_pipeline(RandomOverSampler(random_state=0), tree), X, y, cv=cv, scoring="f1")
print(f"oversample, then CV : F1 {wrong.mean():.3f}")
print(f"oversample in folds : F1 {right.mean():.3f}")
oversample, then CV : F1 0.980
oversample in folds : F1 0.503

Oversampling before the split reports F1 0.980; the honest estimate is 0.503. The unpruned tree memorises every training row, and with copies of the same minority rows in both training and validation folds, "predicting" a validation row means recalling its twin.

The rule from Threshold Adjustment and the Training-Data-Only Rule: resample, reweight and choose thresholds using training data only, and keep the validation and test sets at their natural class ratio, so the scores describe the world the model will meet.

When the prevalence changes

Precision depends on the prevalence even for a fixed model. If a classifier has true-positive rate TPR\text{TPR} and false-positive rate FPR\text{FPR} (both properties of the score distributions), then

precision(π)=TPR⋅πTPR⋅π+FPR⋅(1−π).\text{precision}(\pi) = \frac{\text{TPR} \cdot \pi}{\text{TPR} \cdot \pi + \text{FPR} \cdot (1 - \pi)} .
python · try it yourself
tpr, fpr = 0.80, 0.05
for prevalence in [0.5, 0.1, 0.03, 0.01, 0.001]:
    precision = tpr * prevalence / (tpr * prevalence + fpr * (1 - prevalence))
    print(f"prevalence {prevalence:6.3f}  precision {precision:.3f}  false alarms per true alarm {(1 - precision) / precision:6.1f}")
prevalence  0.500  precision 0.941  false alarms per true alarm    0.1
prevalence  0.100  precision 0.640  false alarms per true alarm    0.6
prevalence  0.030  precision 0.331  false alarms per true alarm    2.0
prevalence  0.010  precision 0.139  false alarms per true alarm    6.2
prevalence  0.001  precision 0.016  false alarms per true alarm   62.4

The same classifier, catching 80 % of positives with a 5 % false-positive rate, has precision 0.941 when half the cases are positive and 0.016 at a prevalence of 1 in 1000: 62 false alarms per real one. Before deploying, evaluate at the prevalence of the population the model will see; a validation set drawn from a different period or region can have a different one (Distribution Shift).

Pitfalls

  • Reporting accuracy alone on imbalanced data. Always give recall and precision of the minority class (or PR-AUC), and the prevalence of the test set.
  • Evaluating on a balanced test set built by undersampling: precision then describes a world with 50 % positives that does not exist.
  • Oversampling before splitting, as shown above.
  • Trusting probabilities after reweighting: weighted or resampled models overestimate the minority probability; recalibrate if you need real probabilities.
  • Too few positives to measure anything. With 30 positives in the test set, a recall of 0.7 has a standard error of about 0.7⋅0.3/30≈0.08\sqrt{0.7 \cdot 0.3 / 30} \approx 0.08. Use cross-validation and report intervals.

Practice

  1. A test set has 2 % positives. Model A has accuracy 0.981, model B 0.960 with recall 0.85. What do you need before choosing?
Answer

The minority-class numbers of A (its recall may be near 0: predicting "no" always gives 0.98) and the costs of the two errors. Accuracy alone cannot rank them; compare recall and precision at the operating point, or PR-AUC.

  1. Why is the chance level of PR-AUC equal to the prevalence?
Answer

A random score ranks positives and negatives in random order, so at every threshold the fraction of positives among the flagged rows is, on average, the overall share π\pi. The precision-recall curve is then flat at π\pi, and its area is π\pi.

  1. With TPR=0.9\text{TPR} = 0.9 and FPR=0.01\text{FPR} = 0.01, what is the precision at prevalence 0.001?
Answer

0.9⋅0.0010.9⋅0.001+0.01⋅0.999=0.00090.0009+0.00999≈0.083\frac{0.9 \cdot 0.001}{0.9 \cdot 0.001 + 0.01 \cdot 0.999} = \frac{0.0009}{0.0009 + 0.00999} \approx 0.083. About 11 false alarms per true one, despite an excellent-looking classifier.

Test yourself

At a prevalence of 3 %, what accuracy does the classifier that always predicts the majority class reach?

  1. 0.03
  2. 0.5
  3. 0.97
  4. 1.0

Which metric's chance level equals the prevalence of the positive class?

  1. ROC-AUC
  2. Balanced accuracy
  3. PR-AUC (average precision)
  4. Accuracy

Where should random oversampling happen in a cross-validated evaluation?

  1. On the whole data set before splitting
  2. On each training fold only, inside the pipeline
  3. On the validation folds
  4. On the test set

A model's TPR and FPR stay the same, but the share of positives in production falls from 10 % to 1 %. What happens to its precision?

  1. It stays the same
  2. It rises
  3. It falls
  4. It becomes 0.5