🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Handling Imbalanced Data with SMOTE, Weights and Ensembles

Module 10: Specialized MLđŸŸĸ Free Lesson
Specialized ML

The one-line mental model

When the minority class is the one that matters, the default pipeline — accuracy, 0.5 threshold, unweighted loss — is optimized for the wrong objective; fix the metric, the loss, and the threshold in that order before reaching for resampling.

You will be able to:

  • Diagnose imbalance and explain why accuracy becomes meaningless near 95:5
  • Apply random over/under-sampling and SMOTE without leaking validation data
  • Use class weights and threshold tuning as first-line remedies
  • Evaluate with F1, AUPRC, and Matthews correlation instead of raw accuracy

Prerequisites

  • !Train/test splitting and cross-validation
  • !Logistic regression or gradient boosting classifiers
  • !Precision, recall, and the confusion matrix

What You'll Learn

  • 1Measure class imbalance and connect it to a business cost matrix
  • 2Implement SMOTE and weighted training inside a leakage-safe CV loop
  • 3Tune a decision threshold against an explicit cost function
  • 4Compare models with AUPRC and balanced accuracy on severely skewed data

Why 95% accuracy can mean a useless model

Consider fraud detection at a 2% positive rate. A model that always predicts "not fraud" achieves 98% accuracy and catches zero fraud cases — it has learned nothing except the base rate. Gradient-boosted trees trained without intervention happily converge toward that solution because the loss landscape rewards majority correctness.

The deeper issue is that most classifiers output a probability and then a label via a 0.5 cut. Under heavy imbalance, a well-calibrated model may legitimately assign 0.3 to a genuine positive, and the default threshold discards it. So the levers you actually control are three: the training objective (weights or resampling), the decision threshold, and the evaluation metric. Resampling is the loudest lever, but it is not always the best first move.

TechniqueWhat it changesRisk
Class weightsLoss contribution per classSimple, low variance, usually safe
Threshold tuningDecision cut on probabilitiesRequires a held-out or CV-derived threshold
Random oversamplingMinority row frequencyOverfits exact duplicates
Random undersamplingMajority row frequencyDiscards information
SMOTESynthetic minority geometryCan blur class boundaries, leaks if misused
Balanced ensemblesPer-bag class compositionSlower training

Resampling: the blunt instruments

Random oversampling duplicates minority rows; random undersampling drops majority rows. Both are useful baselines and both have sharp failure modes — oversampling invites overfitting to the same handful of cases, undersampling throws away signal that might have separated borderline points. Implementations live in imblearn, whose estimators mirror the scikit-learn API so you can drop them into an existing pipeline.

python
import numpy as np
import pandas as pd
from sklearn.utils import resample
from sklearn.model_selection import train_test_split

# Synthetic imbalanced dataset: 2% positive rate
rng = np.random.default_rng(42)
n = 20000
X = pd.DataFrame({
    "amount": rng.gamma(2.0, 500, n),
    "tenure_days": rng.integers(1, 1000, n),
    "n_products": rng.poisson(2.0, n),
})
y = (X["amount"] > 1500).astype(int).rename("target")
print(y.value_counts(normalize=True).round(4))

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, stratify=y, random_state=42
)

train_df = pd.concat([X_train, y_train], axis=1)
majority = train_df[train_df["target"] == 0]
minority = train_df[train_df["target"] == 1]

over = resample(minority, replace=True, n_samples=len(majority),
                random_state=42)
under = resample(majority, replace=False, n_samples=len(minority),
                 random_state=42)

print("Original:", y_train.value_counts().to_dict())
print("Oversampled:", pd.concat([over, minority])["target"].value_counts().to_dict())
print("Undersampled:", pd.concat([under, minority])["target"].value_counts().to_dict())

Two rules keep this honest: resample inside the training fold only, never before the train/test split, and never touch the test set — it must keep its natural prevalence or your metrics will not reflect production.

SMOTE: interpolating the minority manifold

SMOTE (Synthetic Minority Over-sampling Technique) picks a minority point, finds one of its k nearest minority neighbors, and interpolates along the segment between them. The formula is simple; the effect is that the classifier sees a denser minority region instead of identical clones.

Borderline-SMOTE restricts synthesis to minority points near the decision boundary, where extra density actually helps; ADASYN allocates more synthetic points to minority regions that are harder to learn. Both variants can amplify noise when the minority class contains mislabeled points, so clean labels come first.

python
from imblearn.over_sampling import SMOTE, BorderlineSMOTE, ADASYN
from imblearn.under_sampling import TomekLinks
from imblearn.combine import SMOTETomek
from imblearn.pipeline import Pipeline as ImbPipeline
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import average_precision_score, classification_report

# Never resample before the split; the pipeline enforces fold-safe behavior
pipe = ImbPipeline([
    ("smote", SMOTE(random_state=42, k_neighbors=5)),
    ("model", RandomForestClassifier(n_estimators=300, random_state=42,
                                     class_weight=None)),
])

pipe.fit(X_train, y_train)
prob = pipe.predict_proba(X_test)[:, 1]
print(f"AUPRC: {average_precision_score(y_test, prob):.4f}")
print(classification_report(y_test, (prob >= 0.5).astype(int), digits=3))

# Cleaning hybrid: synthesize, then remove Tomek boundary pairs
hybrid = SMOTETomek(random_state=42)
X_res, y_res = hybrid.fit_resample(X_train, y_train)
print("After SMOTETomek:", np.bincount(y_res))

If AUPRC barely moves after SMOTE, the minority signal may simply not be present in your features — more synthetic rows of the same geometry will not conjure information that the columns do not carry.

Class weights and cost-sensitive learning

Weighting moves the same algorithm without inventing rows: each misclassified minority example contributes more to the gradient, so the boundary shifts toward the majority. Scikit-learn's class_weight="balanced" sets weights inversely proportional to class frequencies; a custom dict lets you encode an explicit business cost — say a false negative costs ten times a false positive.

python
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.model_selection import cross_validate
from sklearn.metrics import make_scorer, average_precision_score, f1_score

counts = np.bincount(y_train)
auto_weights = {0: len(y_train) / (2 * counts[0]), 1: len(y_train) / (2 * counts[1])}
cost_weights = {0: 1.0, 1: 10.0}   # miss a fraud case: 10x the cost
print("Auto:", {k: round(v, 3) for k, v in auto_weights.items()})

scoring = {
    "auprc": make_scorer(average_precision_score, needs_threshold=True),
    "f1": make_scorer(f1_score),
}

for label, cw in [("unweighted", None), ("balanced", "balanced"),
                  ("cost_10x", cost_weights)]:
    clf = LogisticRegression(class_weight=cw, max_iter=1000, random_state=42)
    cv = cross_validate(clf, X_train, y_train, cv=5, scoring=scoring)
    print(f"{label:10s}  AUPRC={cv['test_auprc'].mean():.4f}  "
          f"F1={cv['test_f1'].mean():.4f}")

Weights are usually the right first experiment: no new hyperparameters to babysit, no synthetic outliers, and they compose cleanly with calibration and threshold tuning.

Threshold optimization: the cheapest accuracy gain

Given trained probabilities, moving the threshold is free. Compute the precision-recall curve on held-out predictions, then pick the cut that maximizes F1 — or, better, the cut that minimizes an explicit expected cost when false positives and false negatives have different prices.

python
from sklearn.metrics import precision_recall_curve, f1_score

prob = pipe.predict_proba(X_test)[:, 1]
precision, recall, thresholds = precision_recall_curve(y_test, prob)

f1 = 2 * precision * recall / (precision + recall + 1e-12)
best_f1_idx = np.argmax(f1)
print(f"F1-optimal threshold: {thresholds[best_f1_idx]:.3f} "
      f"(F1={f1[best_f1_idx]:.3f})")

cost_fp, cost_fn = 1.0, 10.0
expected_cost = (1 - precision[:-1]) * cost_fp + (1 - recall[:-1]) * cost_fn
cost_idx = np.argmin(expected_cost)
print(f"Cost-optimal threshold: {thresholds[cost_idx]:.3f} "
      f"(expected cost={expected_cost[cost_idx]:.2f})")

y_pred = (prob >= thresholds[cost_idx]).astype(int)
print(classification_report(y_test, y_pred, digits=3))

Validate the chosen threshold inside cross-validation, not on the test set you will report — otherwise the threshold itself becomes a source of leakage.

Metrics that tell the truth under imbalance

Accuracy and even AUROC can flatter a model on a 2% positive rate. AUROC integrates over all thresholds including regions you will never operate in; AUPRC (average precision) focuses on the retrieval-quality region and moves sharply when the model fails to rank positives highly. Matthews correlation coefficient folds all four confusion-matrix cells into a single balanced score, and balanced accuracy averages per-class recalls.

python
from sklearn.metrics import (
    classification_report, confusion_matrix, roc_auc_score,
    average_precision_score, matthews_corrcoef, balanced_accuracy_score,
)

def full_eval(y_true, prob, threshold=0.5):
    pred = (prob >= threshold).astype(int)
    cm = confusion_matrix(y_true, pred)
    return {
        "accuracy": (pred == y_true).mean(),
        "balanced_accuracy": balanced_accuracy_score(y_true, pred),
        "f1": f1_score(y_true, pred),
        "auprc": average_precision_score(y_true, prob),
        "auroc": roc_auc_score(y_true, prob),
        "mcc": matthews_corrcoef(y_true, pred),
        "cm": cm,
    }

for name, p in [("random-forest+smote", pipe.predict_proba(X_test)[:, 1])]:
    print(name, {k: round(v, 4) if isinstance(v, float) else v
                 for k, v in full_eval(y_test, p, threshold=0.35).items()})

Report the confusion matrix itself alongside the scalar metrics. In fraud, credit, and medical settings, stakeholders eventually want to know how many actual positives were missed — a number no single score carries.

Balanced ensembles when you need one estimator to do it all

Balanced ensembles combine resampling with ensemble learning so that a single estimator handles imbalance internally, without a separate preprocessing step that must be kept in sync with the model. Balanced Random Forest draws a different bootstrap sample for each tree, undersampling the majority class per-tree so no single tree is dominated by negatives. EasyEnsemble bags multiple AdaBoost learners trained on different majority-class subsets. RUSBoost applies random undersampling inside a boosting loop. All three share the same core idea: diversity across learners compensates for the information lost to undersampling.

These methods tend to be more robust than a single SMOTE pass followed by a single model, because the variance introduced by resampling is averaged out across learners rather than baked into one training set. The cost is training time — you are fitting an ensemble, not one model — and a less transparent pipeline for production teams to maintain. When accuracy and robustness matter more than simplicity, they are often the best default; when simplicity and auditability dominate, class weights plus threshold tuning remain hard to beat.

imblearn ships ensembles that bake resampling into bagging or boosting: BalancedRandomForest draws a balanced bootstrap per tree, EasyEnsemble trains AdaBoost learners on successive majority undersamples, and RUSBoost combines random undersampling with boosting. They are strong baselines when you want imbalance handling and ensembling in a single estimator.

python
from imblearn.ensemble import (
    BalancedRandomForestClassifier, EasyEnsembleClassifier,
    RUSBoostClassifier,
)

candidates = {
    "balanced_rf": BalancedRandomForestClassifier(
        n_estimators=200, random_state=42, sampling_strategy="auto"),
    "easy_ensemble": EasyEnsembleClassifier(n_estimators=10, random_state=42),
    "rusboost": RUSBoostClassifier(n_estimators=200, random_state=42),
}

for name, model in candidates.items():
    model.fit(X_train, y_train)
    prob = model.predict_proba(X_test)[:, 1]
    print(f"{name:15s} AUPRC={average_precision_score(y_test, prob):.4f}")

Compare every candidate against a weighted-logistic baseline. If a simple weighted linear model lands within a point of AUPRC, prefer it — fewer moving parts, easier calibration, faster inference.

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Data Science Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement