Velamuvi AIAcademy

Lesson 11 of 12 · In Practice

Handling Imbalanced Classes

Rare classes such as fraud: measure with precision and recall, then fix with class weights, resampling after the split and a tuned threshold in scikit-learn.

  • 14 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • Explain why rare classes are hard to learn and easy to mismeasure
  • Measure imbalanced problems with precision, recall and average precision
  • Rebalance training with class weights, oversampling and undersampling
  • Avoid the leak caused by resampling before splitting
  • Choose a decision threshold on validation data and check it once on the test set

The idea in plain words

Many of the most valuable classification problems are imbalanced: the class you care about is rare. Fraudulent payments, faulty parts, patients with a rare disease and customers about to leave are usually a small minority of the data.

In Introduction to Machine Learning you saw that accuracy misleads on such data, and you met precision, recall and class_weight="balanced". This lesson gives you the full toolbox. There are two separate problems to handle:

  1. Measuring. Accuracy, and even some respected metrics, can look excellent while the model is poor at the rare class.
  2. Learning. With few rare examples, the training loss is dominated by the common class, so the model leans towards predicting it, and at the default threshold of 0.5 it rarely flags anything.

Measuring: look at the rare class

The program below creates 4,000 payments, about 5% of them fraud, and splits them in half with stratify=y so both halves get the same share of fraud:

Try it yourselfPython
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import average_precision_score, precision_score, recall_score, roc_auc_score
from sklearn.model_selection import train_test_split

# 4,000 payments, about 5% of them fraud (class 1)
X, y = make_classification(n_samples=4000, n_features=10, n_informative=4, n_clusters_per_class=1,
                           weights=[0.95], class_sep=0.6, flip_y=0.01, random_state=1)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5, stratify=y, random_state=0)
print(f"fraud in training set: {y_train.sum()} of {len(y_train)}, in test set: {y_test.sum()} of {len(y_test)}")

model = LogisticRegression().fit(X_train, y_train)
pred = model.predict(X_test)
proba = model.predict_proba(X_test)[:, 1]
print(f"accuracy {(pred == y_test).mean():.3f}  precision {precision_score(y_test, pred):.2f}  "
      f"recall {recall_score(y_test, pred):.2f}")
print(f"ROC AUC {roc_auc_score(y_test, proba):.3f}   average precision {average_precision_score(y_test, proba):.3f}")
Output
fraud in training set: 109 of 2000, in test set: 109 of 2000
accuracy 0.958  precision 0.70  recall 0.40
ROC AUC 0.933   average precision 0.586

An accuracy of 0.958 sounds good, but recall is only 0.40: the model misses 60% of the fraud. Two summary metrics also disagree:

The ROC AUC of 0.933 looks excellent, because it gives the 1,891 easy normal payments as much say as the 109 frauds. Average precision only looks at how well the frauds are found and how clean the flags are, and its 0.586 tells the more honest story: far better than chance, far from solved. For rare classes, report precision, recall and average precision.

Fix 1: class weights

class_weight="balanced" multiplies each training example's loss by a weight that is larger for the rarer class:

weight of a class = number of rows ÷ (number of classes × rows in that class)

fraud:   2000 ÷ (2 × 109)  ≈ 9.17
normal:  2000 ÷ (2 × 1891) ≈ 0.53

During training, missing one fraud now costs about 17 times as much as raising one false alarm, so the model pays far more attention to the rare class. Most scikit-learn classifiers accept class_weight, including logistic regression, trees, forests and support vector machines.

Fix 2: resampling

Instead of weighting the loss, you can change the training data itself:

  • Oversampling copies random rows of the rare class until the classes are equal.
  • Undersampling throws away random rows of the common class until the classes are equal.

Here are all three fixes side by side. Each one changes only the training data; all four models are tested on the same, untouched test set:

Try it yourselfPython
import numpy as np
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import f1_score, precision_score, recall_score
from sklearn.model_selection import train_test_split
from sklearn.utils import resample

X, y = make_classification(n_samples=4000, n_features=10, n_informative=4, n_clusters_per_class=1,
                           weights=[0.95], class_sep=0.6, flip_y=0.01, random_state=1)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5, stratify=y, random_state=0)

pos, neg = X_train[y_train == 1], X_train[y_train == 0]
# Oversampling: copy random fraud rows until there are as many as normal rows
pos_up = resample(pos, n_samples=len(neg), replace=True, random_state=0)
X_over, y_over = np.vstack([neg, pos_up]), np.array([0] * len(neg) + [1] * len(pos_up))
# Undersampling: keep only as many random normal rows as there are fraud rows
neg_down = resample(neg, n_samples=len(pos), replace=False, random_state=0)
X_under, y_under = np.vstack([neg_down, pos]), np.array([0] * len(neg_down) + [1] * len(pos))

fixes = {
    "no fix": (LogisticRegression(), X_train, y_train),
    "class_weight='balanced'": (LogisticRegression(class_weight="balanced"), X_train, y_train),
    "oversample fraud": (LogisticRegression(), X_over, y_over),
    "undersample normal": (LogisticRegression(), X_under, y_under),
}
print(f"{'':<24} precision  recall    F1   average P(fraud)")
for name, (model, X_fit, y_fit) in fixes.items():
    model.fit(X_fit, y_fit)                      # each fix changes only the TRAINING data
    pred = model.predict(X_test)                 # every model is tested on the same, untouched test set
    print(f"{name:<24} {precision_score(y_test, pred):9.2f} {recall_score(y_test, pred):7.2f} "
          f"{f1_score(y_test, pred):5.2f} {model.predict_proba(X_test)[:, 1].mean():12.3f}")
print(f"real share of fraud in the test set: {y_test.mean():.3f}")
Output
                         precision  recall    F1   average P(fraud)
no fix                        0.70    0.40  0.51        0.056
class_weight='balanced'       0.27    0.87  0.41        0.218
oversample fraud              0.26    0.87  0.41        0.218
undersample normal            0.25    0.88  0.39        0.234
real share of fraud in the test set: 0.054

The three fixes behave almost identically: recall jumps from 0.40 to about 0.87, while precision falls from 0.70 to about 0.26, so roughly three of every four alerts are now false alarms. Their F1 is actually lower than doing nothing. Look at the last column too: the untouched model's average predicted probability (0.056) matches the real share of fraud (0.054), but after rebalancing the models think fraud is about four times more common than it is. Rebalancing doesn't add information; it mostly shifts the model's predictions upwards, much as lowering the threshold would, and the probabilities stop meaning what they say.

Undersampling also throws away most of the training data, and oversampling feeds the model exact copies, which flexible models can memorise. A popular refinement, SMOTE from the separate imbalanced-learn library, creates new synthetic rare-class examples between existing neighbours instead of copying them.

The resampling trap

Resampling must happen after the split, and only on the training data. Here is what happens if you oversample first:

Try it yourselfPython
import numpy as np
from sklearn.datasets import make_classification
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import f1_score
from sklearn.model_selection import train_test_split
from sklearn.utils import resample

X, y = make_classification(n_samples=4000, n_features=10, n_informative=4, n_clusters_per_class=1,
                           weights=[0.95], class_sep=0.6, flip_y=0.01, random_state=1)

def oversample(X, y):
    pos, neg = X[y == 1], X[y == 0]
    pos_up = resample(pos, n_samples=len(neg), replace=True, random_state=0)
    return np.vstack([neg, pos_up]), np.array([0] * len(neg) + [1] * len(pos_up))

# WRONG: oversample first, then split. Copies of the same fraud row land on both sides.
X_big, y_big = oversample(X, y)
Xa, Xb, ya, yb = train_test_split(X_big, y_big, test_size=0.5, stratify=y_big, random_state=0)
wrong = RandomForestClassifier(random_state=0).fit(Xa, ya)
print(f"oversample, then split:  F1 {f1_score(yb, wrong.predict(Xb)):.2f}")

# RIGHT: split first, oversample only the training part, test on untouched data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5, stratify=y, random_state=0)
X_up, y_up = oversample(X_train, y_train)
right = RandomForestClassifier(random_state=0).fit(X_up, y_up)
print(f"split, then oversample:  F1 {f1_score(y_test, right.predict(X_test)):.2f}")
Output
oversample, then split:  F1 0.99
split, then oversample:  F1 0.70

An F1 of 0.99 would be a sensational fraud detector. It is an illusion: each fraud row was copied many times, so almost every fraud in the "test" set has identical twins in the training set, and the forest simply recognises rows it has memorised. The honest score is 0.70. This is the train-test contamination you met in Introduction to Machine Learning: split first, then resample the training part only (inside every fold when cross-validating; the imbalanced-learn library provides a pipeline that does this for you).

Fix 3: move the threshold

Often the simplest and best fix is to keep the model and change the threshold. Choose the threshold on validation data: here, out-of-fold probabilities from cross_val_predict, which gives every training row a prediction from a model that didn't see it, so the test set stays untouched:

Try it yourselfPython
import numpy as np
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import f1_score, precision_recall_curve, precision_score, recall_score
from sklearn.model_selection import cross_val_predict, train_test_split

X, y = make_classification(n_samples=4000, n_features=10, n_informative=4, n_clusters_per_class=1,
                           weights=[0.95], class_sep=0.6, flip_y=0.01, random_state=1)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5, stratify=y, random_state=0)
model = LogisticRegression()

# 1. Out-of-fold probabilities for the TRAINING rows (the test set stays untouched)
p_train = cross_val_predict(model, X_train, y_train, cv=5, method="predict_proba")[:, 1]
for t in [0.5, 0.3, 0.2, 0.1, 0.05]:
    flag = p_train >= t
    print(f"threshold {t:<4}  precision {precision_score(y_train, flag):.2f}  recall {recall_score(y_train, flag):.2f}")

# 2. Choose the threshold with the best F1 on those out-of-fold probabilities
precision, recall, thresholds = precision_recall_curve(y_train, p_train)
f1 = 2 * precision * recall / (precision + recall + 1e-12)
best = thresholds[np.argmax(f1[:-1])]
print(f"best threshold for F1: {best:.2f}")

# 3. Apply it once to the test set
p_test = model.fit(X_train, y_train).predict_proba(X_test)[:, 1]
flag = p_test >= best
print(f"test set: precision {precision_score(y_test, flag):.2f}  recall {recall_score(y_test, flag):.2f}  "
      f"F1 {f1_score(y_test, flag):.2f}")
Output
threshold 0.5   precision 0.68  recall 0.35
threshold 0.3   precision 0.54  recall 0.57
threshold 0.2   precision 0.48  recall 0.69
threshold 0.1   precision 0.36  recall 0.80
threshold 0.05  precision 0.25  recall 0.87
best threshold for F1: 0.19
test set: precision 0.49  recall 0.74  F1 0.59

Lowering the threshold from 0.5 to 0.05 raises recall from 0.35 to 0.87 while precision falls from 0.68 to 0.25: you choose where to sit on that trade-off. precision_recall_curve lists every possible threshold, and the one with the best F1 is 0.19. Applied once to the test set, it gives an F1 of 0.59, better than both the untouched model (0.51) and the rebalanced ones (0.41), and the model's probabilities stay honest because the model itself didn't change. scikit-learn 1.5 and later can automate this search with TunedThresholdClassifierCV.

F1 is only one way to choose. When you know what each mistake costs, choose the threshold that minimises the total cost, as in Probabilistic Models; when a team can only review a fixed number of alerts a day, choose the threshold that produces that many.

FixWhat it doesWatch out for
class_weight="balanced"Makes mistakes on the rare class cost more during trainingProbabilities come out too high; still check the threshold
OversamplingCopies rare-class rows in the training dataOnly after the split; flexible models can memorise the copies
UndersamplingDrops common-class rows from the training dataThrows away information
Threshold tuningKeeps the model, moves the cut-offChoose it on validation data, never on the test set

A few more habits help: stratify every split (cross_val_score already uses stratified folds for classifiers), expect noisy scores when there are only a few dozen rare examples (one more catch can move recall by several points), and remember that more labelled rare examples beat every trick in this lesson. When the rare class is extremely rare or has no labels at all, anomaly detection, covered in Unsupervised Learning, may suit better.

Common mistakes

Practice

Practice exercise

Move the threshold and watch precision and recall trade places.

Your solutionPython
probs  = [0.92, 0.15, 0.40, 0.08, 0.65, 0.30, 0.05, 0.55, 0.22, 0.12]   # P(fraud)
labels = [1, 0, 1, 0, 1, 0, 0, 0, 1, 0]                                 # 1 = really fraud

# For each threshold, flag every case whose probability is >= the threshold,
# then print precision and recall with two decimals, like:
# threshold 0.50: precision 0.00, recall 0.00
for threshold in [0.50, 0.25]:
    precision, recall = 0, 0
    print(f"threshold {threshold:.2f}: precision {precision:.2f}, recall {recall:.2f}")
Knowledge check

Why must you oversample only the training data, after splitting?

Summary

  • With imbalanced classes, accuracy and even ROC AUC can look excellent while the rare class is handled badly; report precision, recall and average precision.
  • Class weights, oversampling and undersampling raise recall at the cost of precision, and they make predicted probabilities too high.
  • Resample after splitting, and only the training data; otherwise copies leak into the test set.
  • Threshold tuning on validation data is often the simplest and best fix, and it keeps the probabilities honest.
  • Keep the test set's real class mix, stratify your splits, and choose the threshold from the real costs where you can.

Next: Project: Customer Churn Prediction, where you put the whole course to work.

Finished reading? Tick it off to track your progress.