Learning path: Classify and Evaluate: Logistic Regression to Cross-Validation · Step 6 of 7
Handling Imbalanced Data: class_weight, SMOTE and the Resampling Leak
With 150 frauds among 15,000 training payments, a model learns to ignore fraud. Compare class_weight, random oversampling and SMOTE, see why full balance overshoots, pick a gentle SMOTE on validation data and avoid the resample-before-split leak.
What you will learn
- Use class_weight='balanced' and RandomOverSampler to make a rare class count more
- Explain how SMOTE creates new minority rows
- Put a sampler inside an imblearn Pipeline so it only touches training rows
- Choose a gentle sampling_strategy on validation data and avoid resampling before the split
Before you start
- Precision, Recall and F1 Score
- Train-Test Split and Data Leakage
Picture a jury that hears 100 cases a day: 99 innocent, one guilty. It soon learns a lazy habit: always say innocent. It's right 99 times in 100, and catches zero guilty people.
Two ways to teach it: show it the guilty cases more often, or make each guilty case count more. A model trained on 1% fraud has the same habit, and these are the same two fixes. Let's try them on payments.csv.
Stratify the split
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import (accuracy_score, recall_score,
precision_score, f1_score)
from imblearn.pipeline import Pipeline
from imblearn.over_sampling import RandomOverSampler, SMOTE
df = pd.read_csv("payments.csv")
X = df.drop(columns="fraud")
y = df["fraud"]
def test_frauds(strat):
split = train_test_split(
X, y, test_size=0.25,
stratify=strat, random_state=7)
return split[3].sum()
print("plain ", test_frauds(None))
print("stratified", test_frauds(y))
plain 56
stratified 50
With a rare class, even the split can be unfair: the plain split put 56 frauds in the test part, the stratified one exactly 50. (More on stratify in Train-Test Split and Data Leakage.) SMOTE and RandomOverSampler come from the imbalanced-learn package (pip install imbalanced-learn).
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25,
stratify=y, random_state=42)
counts = y_train.value_counts().to_dict()
print("training rows:", counts)
training rows: {0: 14850, 1: 150}
What SMOTE does
SMOTE makes new frauds from real ones. It picks a fraud and one of its nearest fraud neighbours, then drops a new point somewhere on the line between them: a made-up fraud that looks like the real ones. It repeats until the classes are equal.
X_res, y_res = SMOTE(random_state=42).fit_resample(
X_train, y_train)
print(y_res.value_counts().to_dict())
{0: 14850, 1: 14850}
150 frauds became 14,850. These rows are only for training the model.
Resample while fitting, never while predicting
Put the sampler inside a Pipeline from imblearn (not the scikit-learn one). It resamples during fit and is skipped during predict.
def pipe(sampler):
return Pipeline([("resample", sampler),
("clf", LogisticRegression())])
smote = pipe(SMOTE(random_state=42))
smote.fit(X_train, y_train)
pred = smote.predict(X_test)
print("flagged:", pred.sum(), "of", len(pred))
flagged: 762 of 5000
Pipeline, the sampler balances the training rows during fit. During predict the test rows go straight to the model, untouched.Four ways, full balance
A small helper prints one score line per model on the test part:
def report(name, model):
p = model.predict(X_test)
a = accuracy_score(y_test, p)
r = recall_score(y_test, p)
pr = precision_score(y_test, p)
f = f1_score(y_test, p)
print(f"{name:<10} acc {a:.3f} rec {r:.2f}",
f"prec {pr:.2f} F1 {f:.2f}")
Now the plain model, class_weight="balanced" (each fraud counts much more in training), RandomOverSampler (copies fraud rows) and SMOTE (invents new ones):
plain = LogisticRegression()
weighted = LogisticRegression(
class_weight="balanced")
over = pipe(RandomOverSampler(random_state=42))
smote = pipe(SMOTE(random_state=42))
models = {"plain": plain, "weighted": weighted,
"over": over, "SMOTE": smote}
for name, m in models.items():
report(name, m.fit(X_train, y_train))
plain acc 0.994 rec 0.42 prec 0.95 F1 0.58
weighted acc 0.857 rec 0.84 prec 0.06 F1 0.11
over acc 0.857 rec 0.84 prec 0.06 F1 0.10
SMOTE acc 0.854 rec 0.82 prec 0.05 F1 0.10
Recall jumps from 0.42 to around 0.84. But precision crashes to 0.06 and F1 falls to about 0.1. Full balance overshoots: the model now flags hundreds of normal payments.
A gentler SMOTE, chosen on validation data
sampling_strategy sets the share of frauds compared with normal rows after SMOTE. 1.0 is full balance. To choose it fairly, split the training rows again; the test rows stay locked.
X_fit, X_val, y_fit, y_val = train_test_split(
X_train, y_train, test_size=0.25,
stratify=y_train, random_state=42)
for s in [0.02, 0.05, 0.1, 0.25, 1.0]:
m = pipe(SMOTE(sampling_strategy=s,
random_state=42))
m.fit(X_fit, y_fit)
f1 = f1_score(y_val, m.predict(X_val))
print(f"{s:<5} validation F1 {f1:.3f}")
0.02 validation F1 0.528
0.05 validation F1 0.552
0.1 validation F1 0.464
0.25 validation F1 0.345
1.0 validation F1 0.098
0.05 wins on validation. Now refit it on all training rows and open the test part once:
gentle = pipe(SMOTE(sampling_strategy=0.05,
random_state=42))
gentle.fit(X_train, y_train)
report("plain", plain)
report("SMOTE 0.05", gentle)
plain acc 0.994 rec 0.42 prec 0.95 F1 0.58
SMOTE 0.05 acc 0.994 rec 0.52 prec 0.84 F1 0.64
Recall goes from 0.42 to 0.52, five more of the 50 frauds caught. F1 rises from 0.58 to 0.64, accuracy stays at 0.994 and precision is still 0.84. A gentle fix keeps the false alarms low.
The leak to avoid: resampling before the split
Here's the wrong order: SMOTE on all the rows first, then split.
X_bad, y_bad = SMOTE(random_state=42).fit_resample(
X, y)
Xb_tr, Xb_te, yb_tr, yb_te = train_test_split(
X_bad, y_bad, test_size=0.25,
stratify=y_bad, random_state=42)
bad = LogisticRegression().fit(Xb_tr, yb_tr)
pred = bad.predict(Xb_te)
rec = recall_score(yb_te, pred)
prec = precision_score(yb_te, pred)
print(f"recall {rec:.2f} precision {prec:.2f}")
print("frauds in test:", yb_te.sum())
recall 0.81 precision 0.86
frauds in test: 4950
Recall 0.81, precision 0.86. Too good to be true. The test part now holds 4,950 "frauds", though the whole dataset has only 200 real ones. Most are made-up points, built from the same real frauds that the training rows were built from, so the test part is full of near-copies of what the model already saw. Split first, and resample the training rows only.
Resample inside the pipeline, after the split. The test part must look like real life: 1% fraud, nothing invented.
Common mistakes
- Going straight to full balance. Here it raised recall but dropped F1 from 0.58 to about 0.1.
- Using scikit-learn's
Pipelinewith a sampler. Useimblearn.pipeline.Pipeline, which knows to skip samplers at predict time. - Judging by accuracy. The balanced models drop to 0.857 accuracy and catch twice as many frauds. Use recall and F1.
- Choosing
sampling_strategyon the test part. Choose it on validation data.
Quick recap
| Model (test part) | Recall | Precision | F1 |
|---|---|---|---|
| Plain | 0.42 | 0.95 | 0.58 |
class_weight="balanced" | 0.84 | 0.06 | 0.11 |
| RandomOverSampler | 0.84 | 0.06 | 0.10 |
| SMOTE, full balance | 0.82 | 0.05 | 0.10 |
| SMOTE 0.05 (chosen on validation) | 0.52 | 0.84 | 0.64 |
Try it yourself
Fit LogisticRegression(class_weight={0: 1, 1: 5}) on the fit part and compare its recall and F1 with SMOTE 0.05 on the validation part. To compare these fixes on more than one split, see Cross-Validation.
The notebook and payments.csv are in the StudyEasy AI Community, free to join.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →ROC Curve, AUC and Choosing a Classification Threshold
Next →Cross-Validation: KFold, StratifiedKFold, cross_val_score and cross_validate
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Linear Regression and the Cost Function: Draw a Line, Score It
Draw a straight line through six kids' ages and weights, measure every miss, and turn the misses into one score, the mean squared error. Then let np.polyfit find the line with the lowest score.
Gradient Descent Explained: Feel the Slope, Step Downhill
Instead of handing over the best line, let the computer walk to it: measure the slope of the cost, step downhill with a learning rate, repeat. Shown step by step on six kids' ages and weights.
Linear Regression in scikit-learn: Fit, Predict and Read the Price Tags
Predict a yearly medical bill with scikit-learn's LinearRegression: first from age alone, then from every column inside a pipeline. Each coefficient reads like a price tag, and smoker_yes is by far the biggest.
Regression Metrics: MAE, RMSE, R-squared and the Baseline to Beat
Score a regression model honestly: MAE, MSE and RMSE from four darts, then the insurance model on 268 test people, a DummyRegressor baseline to beat, R-squared and adjusted R-squared, and a residual plot.