To handle imbalanced classes in Python, first change the decision threshold: fit your classifier as usual and wrap it in scikit-learn's TunedThresholdClassifierCV with a metric that reflects your costs. Class weights (class_weight="balanced") and resampling such as SMOTE are the other common options. For many models they mostly shift the predicted probabilities, which a threshold does without distorting them.
Quick Example
This example makes up 20,000 insurance claims, of which about 3% are fraudulent. Suppose reviewing a claim costs $200 and each fraud caught saves $2,000.
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix, make_scorer
from sklearn.model_selection import TunedThresholdClassifierCV, train_test_split
rng = np.random.default_rng(91)
n = 20_000
claims = pd.DataFrame({
"claim_amount": rng.lognormal(7.8, 0.7, n).round(),
"days_since_policy_start": rng.uniform(1, 1500, n).round(),
"prior_claims": rng.poisson(0.7, n),
"report_delay_days": rng.gamma(1.5, 4, n).round(1),
})
log_odds = (-6.2 + 1.5 * np.log(claims.claim_amount / 2500)
+ 3.0 * (claims.days_since_policy_start < 150)
+ 0.8 * claims.prior_claims
+ 0.13 * claims.report_delay_days)
fraud = rng.binomial(1, 1 / (1 + np.exp(-log_odds)))
X_train, X_test, y_train, y_test = train_test_split(
claims, fraud, test_size=0.3, stratify=fraud, random_state=91)
def savings(y_true, y_pred):
tn, fp, fn, tp = confusion_matrix(y_true, y_pred).ravel()
return 2000 * tp - 200 * (tp + fp)
model = LogisticRegression(max_iter=1000)
tuned = TunedThresholdClassifierCV(
model, scoring=make_scorer(savings), cv=5, store_cv_results=True)
tuned.fit(X_train, y_train)
default = model.fit(X_train, y_train)
print("fraud rate:", fraud.mean().round(4))
print("chosen threshold:", round(tuned.best_threshold_, 3))
for name, clf in [("threshold 0.5", default), ("tuned threshold", tuned)]:
pred = clf.predict(X_test)
tn, fp, fn, tp = confusion_matrix(y_test, pred).ravel()
print(f"{name:<16} caught {tp:>3} of {tp + fn}, reviewed {tp + fp:>4}, "
f"savings ${savings(y_test, pred):,}")
fig, ax = plt.subplots(figsize=(8, 4.5), layout="constrained")
ax.plot(tuned.cv_results_["thresholds"],
tuned.cv_results_["scores"] / 1000, color="#be123c", lw=2)
ax.axvline(tuned.best_threshold_, color="#111827", ls="--",
label=f"Best threshold: {tuned.best_threshold_:.2f}")
ax.axvline(0.5, color="#9ca3af", ls=":", label="Default: 0.50")
ax.set(title="Savings by decision threshold (cross-validation)",
xlabel="Flag a claim if its fraud probability is at least",
ylabel="Average savings per fold ($ thousands)", xlim=(0, 0.7),
ylim=(-50, 75))
ax.legend()
plt.show()

About 3.7% of the claims are fraud. At the default threshold of 0.5, the model flags only 26 of the 6,000 test claims, catches 16 of 225 frauds, and saves $26,800. The tuned threshold of about 0.10 flags 464 claims, catches 104 frauds, and saves $115,200. The model is identical in both cases.
The threshold makes sense from the costs: a $200 review pays off when the chance of fraud is above 200 / 2,000, or 10%. If your probabilities are well calibrated and the costs are fixed, you can set that value directly with FixedThresholdClassifier(model, threshold=0.1).
Which Metrics Work for Imbalanced Data?
Accuracy is the wrong score here: calling every claim honest is about 97% accurate and catches nothing. Use metrics that look at the rare class:
- Precision: the share of flagged claims that are fraud.
- Recall: the share of fraud that gets flagged.
- Average precision (
average_precision_score): summarizes the precision-recall curve across all thresholds. A random ranking scores about the positive rate. - A cost function, like
savingsabove, when you can put numbers on each kind of error.
Split with stratify=y so both sides keep the same share of positives.
Class Weights vs SMOTE vs Undersampling
There are three common ways to make training pay more attention to the rare class:
class_weight="balanced"weights errors inversely to class frequency.SMOTEcreates synthetic positives between existing ones.RandomUnderSamplerthrows away negatives until the classes match.
The last two come from imbalanced-learn (pip install imbalanced-learn). Use its make_pipeline, which resamples during fit() only, so test data is never resampled.
from imblearn.over_sampling import SMOTE
from imblearn.pipeline import make_pipeline
from imblearn.under_sampling import RandomUnderSampler
from sklearn.metrics import PrecisionRecallDisplay, average_precision_score
from sklearn.preprocessing import StandardScaler
def logistic(**kwargs):
return LogisticRegression(max_iter=1000, **kwargs)
methods = {
"No adjustment": make_pipeline(StandardScaler(), logistic()),
"Class weights": make_pipeline(StandardScaler(),
logistic(class_weight="balanced")),
"SMOTE": make_pipeline(StandardScaler(), SMOTE(random_state=91),
logistic()),
"Undersampling": make_pipeline(
StandardScaler(), RandomUnderSampler(random_state=91), logistic()),
}
colors = ["#111827", "#be123c", "#d97706", "#0891b2"]
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4.3), layout="constrained")
rows = []
for (name, pipe), color in zip(methods.items(), colors):
p = pipe.fit(X_train, y_train).predict_proba(X_test)[:, 1]
flagged = p >= 0.5
rows.append({"method": name,
"average precision": average_precision_score(y_test, p),
"recall at 0.5": y_test[flagged].sum() / y_test.sum(),
"claims flagged": flagged.sum(),
"mean probability": p.mean()})
PrecisionRecallDisplay.from_predictions(
y_test, p, ax=ax1, name=name, curve_kwargs={"color": color})
ax2.hist(p, bins=np.linspace(0, 1, 41), histtype="step", lw=1.8,
color=color, label=name)
print(pd.DataFrame(rows).set_index("method").round(3))
ax1.set_title("Precision-recall curves")
ax2.set(title="Predicted probabilities", xlabel="Probability of fraud",
ylabel="Claims (log scale)", yscale="log")
ax2.legend()
plt.show()

All four rank claims about equally well, with average precision between 0.265 and 0.280, and no adjustment scores highest. What changes is the probability scale. The mean predicted probability rises from 0.036, close to the true fraud rate, to about 0.31, so many more claims cross 0.5: around 1,300 are flagged and recall jumps from 0.07 to 0.76.
That higher recall comes from flagging more claims. With class weights, catching 171 frauds by reviewing 1,338 claims saves $74,400, less than the $115,200 from the tuned threshold. Whichever method you use, still choose the threshold.
These results are for logistic regression on four columns. Other models and datasets can benefit more, so compare with cross-validation on your own data.
How Does SMOTE Create New Samples?
SMOTE picks a rare-class point, picks one of its nearest rare-class neighbors (5 by default, set with k_neighbors), and places a new point somewhere on the line between them. Two features make that visible:
rng = np.random.default_rng(4)
many = rng.multivariate_normal([0, 0], [[1.4, 0.5], [0.5, 1.0]], 600)
few = rng.multivariate_normal([2.0, 1.6], [[0.5, -0.2], [-0.2, 0.4]], 30)
X_toy = np.vstack([many, few])
y_toy = np.r_[np.zeros(600), np.ones(30)]
X_new, y_new = SMOTE(random_state=4).fit_resample(X_toy, y_toy)
synthetic = X_new[len(X_toy):]
fig, axes = plt.subplots(1, 2, figsize=(10, 4.3), sharex=True, sharey=True,
layout="constrained")
for ax, title in zip(axes, ["Original data", "After SMOTE"]):
ax.scatter(*many.T, s=12, color="#cbd5e1", label="Common class")
ax.set_title(title)
axes[1].scatter(*synthetic.T, s=12, color="#d97706", alpha=0.6,
label="Synthetic")
for ax in axes:
ax.scatter(*few.T, s=22, color="#7f1d1d", label="Rare class")
axes[1].legend(loc="upper left")
plt.show()

SMOTE added 570 synthetic points to match the 600 common ones. They all fall between existing rare points, including where those overlap the common class. SMOTE adds no new information about where fraud occurs. For categorical columns, use SMOTENC instead.
Resample Inside Cross-Validation, Not Before
Resampling the whole dataset and then cross-validating puts copies, or near copies, of validation rows into the training folds. The scores look far better than the model is.
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import StratifiedKFold, cross_val_score
cv = StratifiedKFold(5, shuffle=True, random_state=91)
forest = RandomForestClassifier(n_estimators=100, random_state=91, n_jobs=-1)
X_res, y_res = SMOTE(random_state=91).fit_resample(X_train, y_train)
wrong = cross_val_score(forest, X_res, y_res, cv=cv,
scoring="average_precision")
right = cross_val_score(make_pipeline(SMOTE(random_state=91), forest),
X_train, y_train, cv=cv, scoring="average_precision")
final = make_pipeline(SMOTE(random_state=91), forest).fit(X_train, y_train)
test = average_precision_score(y_test, final.predict_proba(X_test)[:, 1])
scores = [wrong.mean(), right.mean(), test]
print(np.round(scores, 3))
fig, ax = plt.subplots(figsize=(8, 4), layout="constrained")
bars = ax.bar(["SMOTE, then\ncross-validate", "SMOTE inside\neach fold",
"Untouched\ntest set"], scores,
color=["#be123c", "#0f766e", "#334155"])
ax.bar_label(bars, fmt="%.2f", padding=3)
ax.set(title="Average precision of the same random forest",
ylabel="Average precision", ylim=(0, 1.1))
plt.show()

Resampling first reports an average precision of 0.97. Done correctly, cross-validation gives 0.21, in line with 0.24 on the untouched test set. The same mistake with other preprocessing steps is covered in cross-validation done right.
Which Approach Should You Use?
| Approach | Use it when | Watch out for |
|---|---|---|
| Move the threshold | Always try this first | Choose it on training data, not the test set |
| Class weights | The model underfits the rare class, or has no probabilities to threshold | Probabilities no longer match real rates |
| SMOTE | It beats the simpler options in cross-validation | Must run inside each fold; distorts probabilities |
| Undersampling | The common class is so large that training is slow | Discards data |
| More positive examples | You can label or collect them | Usually the most effort |
Practical Tips
- Count the positives, not the percentage. Fifty positives is little data at any ratio.
- If you act on the probabilities, check a calibration curve after weighting or resampling.
- A lift or gains chart answers "if we can review 500 claims, how much fraud do we catch?"
- Gradient boosting libraries have their own weights, such as
scale_pos_weightin XGBoost and LightGBM.