Back to Tutorials
Machine Learning
Intermediate

Imbalanced Data: When What You Want Is Rare

Try class weights, oversampling, undersampling and SMOTE on the same factory line, see what they really change, and watch a resampling mistake fake a perfect score.

11 minInteractive: drag, click and try things as you read


Fraud, disease, faulty parts, customers about to leave: the cases you most want a model to find are often 1 in 50, or far rarer. Train on data like that and the model hardly ever raises its hand. The usual advice is to rebalance the data first, with class weights, oversampling or SMOTE. Most of those fixes simply move the model’s threshold for you, and they quietly break its probabilities along the way. Here you’ll try every fix on the same factory line, then watch a common mistake fake a perfect score.

When the thing you want is rare#

A factory tests every electric motor at the end of the line, measuring how hot it runs and how much it vibrates. About 2 motors in 100 are faulty. Faulty ones tend to run hotter and shake more, but plenty of good motors do too, so the readings overlap. You train a model on 5,000 tested motors to flag the faulty ones for a closer look.

The model is a logistic regression: it turns the two readings into a chance that the motor is faulty, and anything at or above a threshold gets flagged. The usual threshold is 0.5: flag a motor if it’s more likely faulty than not. With a rare class, that’s where the trouble starts.

Predict first

Trained on the 5,000 motors as they are, with the threshold at 0.5, roughly how many of the faulty motors does the model flag?

Try it
Made-up motors: 5,000 to train on, 2% faulty, and 20,000 new ones to test on. All five models are trained in your browser, on the same 5,000 motors. Pick a fix, then slide the threshold.

With no fix, at 0.5 the model catches 29% of the faulty motors. When it does flag one, it’s right two times in three, but it misses most of what you built it for. Its accuracy is still over 98%, which is why accuracy is the wrong score here (the confusion matrix explainer shows that trap).

Now pick Class weights, which counts every faulty motor about 48 times over in training, so the two classes carry equal weight. At the same 0.5 it catches 92%. The price: 135 false alarms for every 1,000 working motors, and only 12% of flagged motors are really faulty. Oversampling (copying faulty motors until there are as many as working ones), undersampling (throwing away working motors until the numbers match) and SMOTE (making new, in-between faulty motors) all land in almost the same place.

What the fixes really do#

Predict first

Class weights catch 92% of faults at 0.5. Go back to the model with no fix and lower its threshold to 0.02. How many faults does it catch now?

At 0.02, the model with no fix catches 350 of the 380 faulty test motors, exactly as many as class weights at 0.5, with 146 false alarms per 1,000 working motors against 135. Look at the curve on the right, which traces every threshold at once: the precision–recall curves of all five models sit on top of each other, and the area under each is 0.47. A fix moves you along the curve; it doesn’t give you a better curve.

What the fixes do change is the model’s sense of the odds. Trained as it is, the model’s average chance of a fault across all test motors is 2.2%, close to the real 1.9%. With any of the fixes it’s around 18 or 19%. The model learned from a world where half the motors were faulty, so it now overstates the odds roughly tenfold.

That matters whenever someone uses the numbers, not just the yes or no: to price risk, to rank inspections, or to choose the threshold from what mistakes cost. In 2022 Ruben van den Goorbergh and colleagues tested these corrections on medical risk models and found the same thing: strongly overestimated risks, and no better ranking of patients. The same year Yotam Elor and Hadar Averbuch-Elor compared balancing methods across 73 datasets. Balancing helped weaker models, but not strong ones like boosted trees, and tuning the threshold worked as well as balancing, more simply. Plain copying did as well as SMOTE.

Resampling still has honest uses. With millions of rows, throwing away most of the common class makes training far faster. Google’s Machine Learning Crash Course suggests exactly that, then counting each kept example more heavily so the model’s probabilities stay true. Balancing can also help weaker models and very small datasets. Just treat it as one option to test, not a step every project needs.

The mistake that fakes a perfect score#

If you do resample, when you do it matters more than how. It’s easy to balance the whole dataset first and then split it into training and test sets, because that’s the order the steps come to mind in. Here’s what that does, this time with a k-nearest neighbours model, which flags a motor when most of the 5 most similar training motors were faulty.

Predict first

You copy faulty motors until the classes balance, then split 75% for training and 25% for testing. The test says the model catches 100% of faults. On new motors from the line, about how many will it catch?

Try it
4,000 made-up recorded motors, 2% faulty, and 10,000 new ones. The balancing, the split, the model and both scores are all computed in your browser.

Balanced first, the test quarter reports 100% of faults caught and 96% of flags right. On new motors the same model catches 58% of faults, and only 23% of its flags are right. 916 of the 939 faulty motors in that test quarter were made by the balancing step. SMOTE leaks in the same way, because each new motor it makes is a blend of real ones that may sit on either side of the split.

Split first, and the test quarter keeps only real motors: 25 of them faulty, which makes the test small and noisy, but honest. That’s the real cost of rare classes. You need enough rare cases in your test data to measure anything, so collect them, keep the test set’s class mix the same as real life, and use stratified cross-validation to get more out of the ones you have. Do any resampling after you split, and only on the training data.

This isn’t a beginner’s-only mistake. In 2020, Gilles Vandewiele and colleagues at Ghent University looked at published studies that predicted premature births from a public dataset of recordings, many reporting near-perfect results. The cause was this exact flaw: oversampling before splitting. Re-run correctly, the methods often did no better than random guessing.

A checklist for rare classes#

  • Decide which mistake costs more before you train, ideally in money or time.
  • Score with precision, recall and average precision (the area under the precision–recall curve), not accuracy. Report counts too: “caught 16 of 25” says how much to trust the number.
  • Train on the data as it is first, then choose the threshold on validation data, from your costs or a target recall.
  • If you resample or weight, do it inside the training data only, and check the probabilities if anyone will use them.
  • Get more of the rare class if you can: more labelled examples beat any rebalancing trick.

In code#

With scikit-learn and imbalanced-learn (pip install scikit-learn imbalanced-learn), on a made-up dataset with 2% positives. imbalanced-learn’s make_pipeline applies SMOTE only while fitting, so the test data is never resampled, and scikit-learn’s TunedThresholdClassifierCV chooses a threshold with cross-validation:

from imblearn.over_sampling import SMOTE
from imblearn.pipeline import make_pipeline
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import average_precision_score, precision_score, recall_score
from sklearn.model_selection import TunedThresholdClassifierCV, train_test_split

X, y = make_classification(n_samples=20_000, weights=[0.98], class_sep=1.0, flip_y=0, random_state=0)
X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, test_size=0.5, random_state=0)

models = {
    "no fix": LogisticRegression(),
    "class weights": LogisticRegression(class_weight="balanced"),
    "SMOTE": make_pipeline(SMOTE(random_state=0), LogisticRegression()),  # resamples training data only
    "tuned threshold": TunedThresholdClassifierCV(LogisticRegression(), scoring="f1"),
}
for name, model in models.items():
    model.fit(X_train, y_train)
    flagged = model.predict(X_test)
    chance = model.predict_proba(X_test)[:, 1]
    print(f"{name:15} recall {recall_score(y_test, flagged):.2f}  precision {precision_score(y_test, flagged):.2f}  "
          f"avg precision {average_precision_score(y_test, chance):.2f}  mean chance {chance.mean():.3f}")
print(f"threshold chosen: {models['tuned threshold'].best_threshold_:.2f}, real rate {y_test.mean():.3f}")
# no fix          recall 0.30  precision 0.85  avg precision 0.54  mean chance 0.020
# class weights   recall 0.81  precision 0.10  avg precision 0.43  mean chance 0.230
# SMOTE           recall 0.81  precision 0.10  avg precision 0.43  mean chance 0.209
# tuned threshold recall 0.51  precision 0.58  avg precision 0.54  mean chance 0.020
# threshold chosen: 0.22, real rate 0.020

On this data the fixes do worse than nothing at ranking (average precision 0.43 against 0.54), and inflate the average chance about tenfold. Tuning the threshold keeps the honest probabilities and the better ranking. F1 weighs both mistakes equally; swap in a scorer built from your own costs.

What to remember

  • With a rare class, a model’s honest probabilities are mostly low, so the default 0.5 threshold flags very little; accuracy hides it.
  • Class weights, oversampling, undersampling and SMOTE mostly move the threshold for you and inflate the probabilities; choosing the threshold yourself usually does as well.
  • Resample only after splitting, on the training data, or copies of your test cases will fake a near-perfect score.

Keep going

Sign in to save your place and keep a learning streak. Free, with Google.