AI and machine learning · Advanced · 25 min
Handle imbalanced classes without fooling yourself
By Padding · Updated 18 Nov 2026
Python 3.15 (python:3.15-slim) · scikit-learn 1.9.1 · imbalanced-learn 0.14.2 · NumPy 2.5.5
You will take a mobile-money fraud set with 0.5% positives from a 99.5% accurate model that catches nothing to a scored, budgeted alert list, after testing class weights, undersampling and SMOTE inside an imbalanced-learn pipeline.
On this page
A mobile-money operator sees tens of thousands of transfers a day, and a handful of them are fraud: a stolen phone, a SIM swapped by someone posing as the owner, a scammer emptying a wallet at 2am. The fraud team can review perhaps one transfer in a hundred. The model's job is to put the real fraud near the top of that short list.
With 1 fraud in 200 transfers, the usual habits break. A model that never says "fraud" is 99.5% accurate. Popular fixes such as SMOTE are easy to misuse, and misused they produce scores that look excellent and mean nothing. In this tutorial you build that trap on purpose, measure the model the way the fraud team will use it, compare the three standard fixes fairly, and set a cut-off from the team's review capacity.
The data is synthetic, generated with fixed seeds, so your numbers should match the ones shown here closely. Everything runs on a laptop CPU in a few seconds per script.
Step 1 · Create the project and install the libraries
Make a throwaway folder and a virtual environment, then install pinned versions of scikit-learn, imbalanced-learn (imported as imblearn) and NumPy:
mkdir -p ~/fraud-imbalance-demo
cd ~/fraud-imbalance-demo
python3 -m venv .venv
source .venv/bin/activate
pip install --quiet scikit-learn==1.9.1 imbalanced-learn==0.14.2 numpy==2.5.5The download is around 60 MB, most of it SciPy and scikit-learn. On prepaid mobile data, do this once on Wi-Fi; nothing later needs a connection.
Check it worked
python -c "import sklearn, imblearn, numpy; print(sklearn.__version__, imblearn.__version__, numpy.__version__)"The output is 1.9.1 0.14.2 2.5.5.
Step 2 · Generate 40,000 transfers with 0.5% fraud
Each transfer has six features and a label:
amount: the transfer, in thousands of the local currencynight: 1 if it was sent between midnight and 5amnew_recipient: 1 if it is the first transfer to that numberaccount_age_days: how long the sending wallet has existedtxns_last_hour: transfers from the same wallet in the hour beforesim_swap_7d: 1 if the SIM behind the wallet was replaced in the last seven daysfraud: 1 for a fraudulent transfer, the thing to predict
A hidden rule makes fraud more likely after a recent SIM swap, to a new recipient, at night, for larger amounts and in bursts, and less likely from older wallets. Random noise on top means two identical-looking transfers can have different outcomes.
cat > make_data.py <<'PY'
import csv
import numpy as np
rng = np.random.default_rng(7)
N = 40_000
amount = rng.lognormal(mean=np.log(8), sigma=0.8, size=N).round(1) # thousands of local currency
night = (rng.random(N) < 0.08).astype(int) # sent between midnight and 5am
new_recipient = (rng.random(N) < 0.2).astype(int) # first transfer to this number
account_age_days = rng.integers(1, 2001, size=N)
txns_last_hour = rng.poisson(0.4, size=N) # transfers in the hour before
sim_swap_7d = (rng.random(N) < 0.02).astype(int) # SIM replaced in the last 7 days
score = (
-6.4
+ 3.0 * sim_swap_7d
+ 1.6 * new_recipient
+ 1.3 * night
+ 0.04 * amount
+ 0.6 * txns_last_hour
- 0.001 * account_age_days
)
fraud = (rng.random(N) < 1 / (1 + np.exp(-score))).astype(int)
with open("transactions.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["amount", "night", "new_recipient", "account_age_days", "txns_last_hour", "sim_swap_7d", "fraud"])
for row in zip(amount, night, new_recipient, account_age_days, txns_last_hour, sim_swap_7d, fraud):
writer.writerow([f"{row[0]:.1f}", *[int(v) for v in row[1:]]])
print(f"wrote {N} transactions, {fraud.sum()} fraud ({fraud.mean():.2%})")
PY
python make_data.pyEvery later script needs the same split and the same idea of "what the fraud team can review", so put both in a shared file. stratify=y matters more than usual here: without it, a random split could leave the test set with noticeably fewer fraud cases than the training set.
cat > common.py <<'PY'
import numpy as np
from sklearn.model_selection import train_test_split
ALERT_BUDGET = 0.01 # the fraud team can review 1 transaction in 100
def load_split():
data = np.loadtxt("transactions.csv", delimiter=",", skiprows=1)
X, y = data[:, :-1], data[:, -1].astype(int)
return train_test_split(X, y, test_size=0.25, stratify=y, random_state=42)
def recall_at_budget(y_true, scores, budget=ALERT_BUDGET):
"""Share of fraud caught if only the top `budget` share of transactions is reviewed."""
k = max(1, int(round(budget * len(scores))))
top = np.argsort(scores)[::-1][:k]
return y_true[top].sum() / y_true.sum()
def budget_scorer(estimator, X, y):
return recall_at_budget(y, estimator.predict_proba(X)[:, 1])
PYALERT_BUDGET is the single most important number in this tutorial, and it comes from operations, not from the model. Replace 0.01 with your own team's capacity: reviewers per shift times transfers each can check, divided by daily volume.
Check it worked
The script prints wrote 40000 transactions, 214 fraud (0.53%). That is about 1 in 190. After the 75/25 split, the test set holds 10,000 transfers and only 53 of them are fraud, which is why every score later in this tutorial moves noticeably with a few cases either way.
Step 3 · Build a 99.5% accurate model that catches nothing
Train two models: a DummyClassifier that always answers the most common class, and a standard logistic regression. Print each one's accuracy and confusion matrix, the 2 by 2 table of actual class against predicted class:
cat > accuracy_trap.py <<'PY'
from sklearn.dummy import DummyClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report, confusion_matrix, recall_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from common import load_split
X_train, X_test, y_train, y_test = load_split()
print(f"test rows: {len(y_test)} fraud in test: {y_test.sum()}")
dummy = DummyClassifier(strategy="most_frequent").fit(X_train, y_train)
logreg = make_pipeline(StandardScaler(), LogisticRegression()).fit(X_train, y_train)
for name, model in [("always 'legit'", dummy), ("logistic regression", logreg)]:
pred = model.predict(X_test)
tn, fp, fn, tp = confusion_matrix(y_test, pred).ravel()
print(f"\n{name}: accuracy {model.score(X_test, y_test):.2%}")
print(f" predicted legit predicted fraud")
print(f" actual legit {tn:>15} {fp:>15}")
print(f" actual fraud {fn:>15} {tp:>15}")
print("\nlogistic regression, per class:")
print(classification_report(y_test, pred, target_names=["legit", "fraud"], digits=3, zero_division=0))
assert dummy.score(X_test, y_test) > 0.99
assert recall_score(y_test, dummy.predict(X_test)) == 0
PY
python accuracy_trap.pyCheck it worked
The dummy model scores 99.47% accuracy and its bottom row reads 53 and 0: all 53 fraud cases predicted legit. The logistic regression scores 99.48% and catches 1 of 53.
The classification report shows where the problem hides. For the fraud row, recall is about 0.019 (1 in 53) while the accuracy and weighted avg rows sit at 0.995, because 9,947 legit rows swamp the 53 fraud rows in any average weighted by count. With a rare class, read the row for that class and ignore the overall figures.
Step 4 · Measure the ranking, not the 0.5 cut-off
The logistic regression did not fail to learn. It failed to cross 0.5: when only 1 transfer in 190 is fraud, very few transfers are more likely fraud than not, so predict() almost never says yes. What the fraud team needs is a good ordering, so score the ordering:
- Average precision summarises the precision-recall curve. A random ordering scores the fraud rate (about 0.005 here), and a perfect one scores 1.
- ROC AUC is the chance a random fraud case scores above a random legit one. A random ordering scores 0.5.
- Recall at 1% is the share of fraud in the top 1% of scores: the cases the team would see.
cat > ranking.py <<'PY'
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import average_precision_score, roc_auc_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from common import load_split, recall_at_budget
X_train, X_test, y_train, y_test = load_split()
model = make_pipeline(StandardScaler(), LogisticRegression()).fit(X_train, y_train)
scores = model.predict_proba(X_test)[:, 1]
random_scores = np.random.default_rng(0).random(len(y_test))
print(f"fraud rate in test: {y_test.mean():.4f}")
print(f"highest fraud score: {scores.max():.3f} (predict() flags at 0.5)\n")
print(" avg_precision roc_auc recall@1%")
for name, s in [("random scores", random_scores), ("logistic regression", scores)]:
print(f"{name:<20} {average_precision_score(y_test, s):>13.3f} {roc_auc_score(y_test, s):>7.3f}"
f" {recall_at_budget(y_test, s):>9.1%}")
assert average_precision_score(y_test, scores) > 10 * y_test.mean()
PY
python ranking.pyCheck it worked
The table reads close to this:
avg_precision roc_auc recall@1%
random scores 0.006 0.485 1.9%
logistic regression 0.225 0.877 32.1%The same model that "caught 1 of 53" puts about a third of the fraud into the top 100 transfers. Its average precision of 0.225 is around 40 times the random baseline, while its ROC AUC of 0.877 sounds better than the model really is: ROC AUC counts how well the model separates fraud from thousands of easy legit transfers, which barely matters to a team that only looks at the top 100. With rare positives, lead with average precision and recall at your budget, and report ROC AUC alongside rather than instead.
Step 5 · Compare class weights, undersampling and SMOTE fairly
There are three common fixes, and each changes what the model sees during training:
class_weight="balanced": keeps every row, but each fraud row counts about 190 times as much as a legit row in the loss.RandomUnderSampler: throws away legit rows at random until the classes are equal.SMOTE: invents new fraud rows by interpolating between real fraud rows and their nearest fraud neighbours.
Samplers must only ever touch training data. imbalanced-learn's own Pipeline (from imblearn.pipeline, not sklearn.pipeline) guarantees that: it runs the sampler during fit and skips it during predict and scoring. Put that pipeline inside cross_validate, and each fold resamples its four training parts while the fifth part keeps its real 0.5% fraud rate.
cat > compare.py <<'PY'
from imblearn.over_sampling import SMOTE
from imblearn.pipeline import make_pipeline
from imblearn.under_sampling import RandomUnderSampler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import make_scorer, precision_score
from sklearn.model_selection import StratifiedKFold, cross_validate
from sklearn.preprocessing import StandardScaler
from common import budget_scorer, load_split
X_train, X_test, y_train, y_test = load_split()
candidates = {
"plain": make_pipeline(StandardScaler(), LogisticRegression()),
"class_weight": make_pipeline(StandardScaler(), LogisticRegression(class_weight="balanced")),
"undersample": make_pipeline(StandardScaler(), RandomUnderSampler(random_state=0), LogisticRegression()),
"smote": make_pipeline(StandardScaler(), SMOTE(random_state=0), LogisticRegression()),
}
scoring = {
"ap": "average_precision",
"budget": budget_scorer,
"recall": "recall",
"precision": make_scorer(precision_score, zero_division=0),
}
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
print("strategy avg_precision recall@1% recall@0.5 precision@0.5")
results = {}
for name, pipe in candidates.items():
res = cross_validate(pipe, X_train, y_train, cv=cv, scoring=scoring)
results[name] = res
ap, bud = res["test_ap"], res["test_budget"]
print(f"{name:<13} {ap.mean():.3f} ± {ap.std():.3f} {bud.mean():>5.1%} ± {bud.std():.1%}"
f" {res['test_recall'].mean():>10.1%} {res['test_precision'].mean():>13.1%}")
# Resampling moves the 0.5 cut-off; it does not make the ranking better here.
assert results["class_weight"]["test_recall"].mean() > 5 * results["plain"]["test_recall"].mean()
for name in ["class_weight", "undersample", "smote"]:
assert results[name]["test_ap"].mean() < results["plain"]["test_ap"].mean() + 0.02
PY
python compare.pybudget_scorer from common.py is a plain function taking (estimator, X, y), which cross_validate accepts as a scorer next to the built-in names.
Check it worked
You see something close to this:
strategy avg_precision recall@1% recall@0.5 precision@0.5
plain 0.140 ± 0.027 26.1% ± 5.1% 2.5% 50.0%
class_weight 0.132 ± 0.028 24.9% ± 4.5% 75.7% 2.0%
undersample 0.121 ± 0.029 26.7% ± 4.3% 75.1% 2.1%
smote 0.120 ± 0.032 24.9% ± 3.0% 74.5% 2.0%Read the two halves separately. On the right, all three fixes take recall at 0.5 from about 2.5% to about 75%, at a precision of 2%: they flag roughly 1 transfer in 5, far beyond any team's budget. On the left, the columns that measure ranking barely move, and the differences sit well inside one standard deviation across folds. On this data the fixes shift where 0.5 falls and leave the ordering much as it was.
That is the common result for a well-specified linear model. Weighting or resampling can help more with flexible models such as gradient-boosted trees, or when training would otherwise stop learning the rare class, so run the same comparison on your own model before choosing. Undersampling also has a practical upside on a slow machine: it trains on a few hundred rows instead of 30,000.
Step 6 · See how resampling before the split fools you
The most common mistake is to resample the whole dataset first and then split or cross-validate. Do it here on purpose and compare it with the pipeline version:
cat > leak.py <<'PY'
from imblearn.over_sampling import SMOTE
from imblearn.pipeline import make_pipeline as make_imb_pipeline
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_validate
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from common import load_split
X_train, X_test, y_train, y_test = load_split()
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
scoring = {"ap": "average_precision", "auc": "roc_auc"}
# Wrong: resample everything first, then cross-validate on the resampled rows.
X_res, y_res = SMOTE(random_state=0).fit_resample(X_train, y_train)
print(f"after SMOTE: {len(y_res)} rows, {y_res.mean():.0%} fraud")
wrong = cross_validate(make_pipeline(StandardScaler(), LogisticRegression()), X_res, y_res, cv=cv, scoring=scoring)
# Right: SMOTE is a pipeline step, so it only touches each training fold.
right = cross_validate(
make_imb_pipeline(StandardScaler(), SMOTE(random_state=0), LogisticRegression()),
X_train, y_train, cv=cv, scoring=scoring,
)
for name, res in [("SMOTE before the split", wrong), ("SMOTE inside the pipeline", right)]:
print(f"{name:<26} avg_precision {res['test_ap'].mean():.3f} roc_auc {res['test_auc'].mean():.3f}")
assert wrong["test_ap"].mean() > 3 * right["test_ap"].mean()
PY
python leak.pyCheck it worked
The output reads close to this:
after SMOTE: 59678 rows, 50% fraud
SMOTE before the split avg_precision 0.879 roc_auc 0.888
SMOTE inside the pipeline avg_precision 0.120 roc_auc 0.858The leaked version reports an average precision seven times higher for the same model. Two things went wrong. The validation folds are now half fraud, so even a weak model finds fraud wherever it looks; average precision rises with the positive rate, which is why you must evaluate on data with the real rate. And most of those "fraud" rows are synthetic points drawn between real fraud rows that sit in the training folds, so the model is graded on near-copies of what it was taught. ROC AUC hardly changes, which is a reason not to rely on it alone: it would not have warned you.
The same leak happens with any sampler, and with train_test_split after resampling. If a score jumps after you add resampling, check where the sampler runs before you celebrate.
Step 7 · Set the cut-off from the alert budget
Two last checks before the model goes near the fraud team. First, class weights and resampling change what the scores mean. Second, the cut-off should come from the team's capacity, chosen on training data so the test set stays honest:
cat > threshold.py <<'PY'
import numpy as np
from imblearn.over_sampling import SMOTE
from imblearn.pipeline import make_pipeline
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import FixedThresholdClassifier, StratifiedKFold, cross_val_predict
from sklearn.preprocessing import StandardScaler
from common import ALERT_BUDGET, load_split
X_train, X_test, y_train, y_test = load_split()
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
print(f"real fraud rate in test: {y_test.mean():.2%}")
for name, pipe in [
("plain", make_pipeline(StandardScaler(), LogisticRegression())),
("class_weight", make_pipeline(StandardScaler(), LogisticRegression(class_weight="balanced"))),
("smote", make_pipeline(StandardScaler(), SMOTE(random_state=0), LogisticRegression())),
]:
p = pipe.fit(X_train, y_train).predict_proba(X_test)[:, 1]
print(f" {name:<13} mean predicted P(fraud): {p.mean():.2%}")
model = make_pipeline(StandardScaler(), LogisticRegression())
# Pick the cut-off on training data: out-of-fold scores, top ALERT_BUDGET share flagged.
oof = cross_val_predict(model, X_train, y_train, cv=cv, method="predict_proba")[:, 1]
threshold = float(np.quantile(oof, 1 - ALERT_BUDGET))
print(f"\nthreshold for a {ALERT_BUDGET:.0%} alert budget: {threshold:.4f}")
for label, t in [("default 0.5", 0.5), ("budget", threshold)]:
clf = FixedThresholdClassifier(model, threshold=t).fit(X_train, y_train)
flagged = clf.predict(X_test) == 1
caught = int((flagged & (y_test == 1)).sum())
print(f" {label:<12} flagged {flagged.sum():>4} ({flagged.mean():.2%}), caught {caught} of {y_test.sum()} fraud"
f" ({caught / y_test.sum():.0%}), precision {caught / max(flagged.sum(), 1):.0%}")
assert 0.005 < flagged.mean() < 0.02
assert caught >= 5
PY
python threshold.pycross_val_predict scores every training row with a model that never saw it, so the 99th percentile of those scores is an honest estimate of where the top 1% begins. FixedThresholdClassifier wraps the pipeline so predict() uses that cut-off instead of 0.5, and the chosen number travels with the saved model.
Check it worked
The first block shows the plain model's average score, about 0.56%, close to the real fraud rate of 0.53%. The class-weighted and SMOTE models average about 30%. Their ordering is fine, but a dashboard that shows "30% chance of fraud" on an ordinary transfer would mislead every agent who reads it. If you use weights or resampling and need real probabilities, recalibrate on data with the real rate.
The last two lines are the result the fraud team cares about:
default 0.5 flagged 1 (0.01%), caught 1 of 53 fraud (2%), precision 100%
budget flagged 106 (1.06%), caught 17 of 53 fraud (32%), precision 16%The threshold is about 0.066. At that cut-off the model flags 106 of 10,000 test transfers, close to the 1% budget, and 17 of them are fraud: about 1 alert in 6 is real, against 1 in 190 if reviewers picked at random. Same model as the 99.5% accurate one that caught a single case; only the cut-off changed.
Before this goes live, have analysts review a sample of unflagged transfers each month too, since fraud the model never scores highly is invisible in alert counts. Treat a flag as a reason to call or hold, not proof: a customer who changed phones legitimately last week looks a lot like a SIM-swap victim.
Step 8 · Clean up
Leave the virtual environment and delete the project folder:
deactivate
cd ~
rm -rf ~/fraud-imbalance-demo
ls ~/fraud-imbalance-demo 2>/dev/null || echo "removed"Check it worked
The last command prints removed.
Next steps
- Draw precision-recall and ROC curves, check calibration and tune a threshold automatically: measure a classifier with precision, recall and ROC.
- Fraud data has many rows per wallet and changes over time; split by group and by date: validate a model honestly with cross-validation.
- Revisit the basics of scores, baselines and cost-based cut-offs on a less extreme problem: classify data with logistic regression and decision trees.
Related tutorials
- Measure a classifier with precision, recall and ROC curvesYou will score a fraud classifier on rare-class data with a confusion matrix, precision, recall, F1, precision-recall and ROC curves and a reliability curve, then pick its decision threshold from the cost of each mistake.
- Validate a model honestly with cross-validationYou will score a scikit-learn model with k-fold cross-validation, report its mean and spread, choose stratified, grouped or time-ordered folds to match your data, and catch two planted leaks that make a model look better than it is.
- Classify data with logistic regression and decision treesYou will train a logistic regression and a shallow decision tree to flag loan instalments likely to be late, print the tree's rules, watch a deep tree overfit, and pick a decision threshold from what each kind of mistake costs.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials