Pulse Data Hub

Imbalanced Data in Python: Class Weights vs SMOTE

Imbalanced data in Python is the situation where one class is rare, such as fraud, faults or disease, and a model can look excellent while finding almost none of them. This guide uses a real imbalanced dataset and compares the usual fixes, class weights and SMOTE, with proper cross-validation, then shows the common mistake that makes SMOTE look perfect when it is not.

The data is the oil spill dataset from Kubat, Holte and Matwin (1998): 937 patches of satellite radar images, of which 41 (4.38%) contain an oil slick. It has 48 numeric features after I dropped the first column, which looks like a record number. Code was run with scikit-learn 1.9.1 and imbalanced-learn 0.14.2.

Bar chart of average precision from repeated cross-validation: logistic regression 0.539, forest 0.546, forest with class weights 0.599, forest with SMOTE inside a pipeline 0.642, and a leaky SMOTE-before-split run showing 1.000.
Average precision (higher is better) from 5-fold CV repeated 3 times. The red bar is the leaky setup and is not a real result.

Imbalanced data in Python: the accuracy trap

import pandas as pd, numpy as np
url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/oil-spill.csv"
d = pd.read_csv(url, header=None)
y = d.iloc[:, -1].values
X = d.iloc[:, 1:-1].values
print(d.shape, np.bincount(y), round(y.mean() * 100, 2))

Output:

(937, 50) [896  41] 4.38

A model that always answers “no spill” would score about 95.6% accuracy and find nothing. We use repeated stratified 5-fold cross-validation (3 repeats, 15 fits per model) and report several metrics, because accuracy alone hides the problem.

from sklearn.model_selection import RepeatedStratifiedKFold, cross_validate
from sklearn.dummy import DummyClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

cv = RepeatedStratifiedKFold(n_splits=5, n_repeats=3, random_state=1)
scoring = ["accuracy", "recall", "precision", "average_precision"]

def run(name, model):
    r = cross_validate(model, X, y, cv=cv, scoring=scoring, n_jobs=2)
    print(f"{name:30s}" + "  ".join(f"{k[:6]}={r['test_'+k].mean():.3f}" for k in scoring))

run("always no spill", DummyClassifier())
run("logistic regression", make_pipeline(StandardScaler(), LogisticRegression(max_iter=2000)))
run("random forest", RandomForestClassifier(200, random_state=0, n_jobs=2))

Output:

always no spill               accura=0.956  recall=0.000  precis=0.000  averag=0.044
logistic regression           accura=0.964  recall=0.452  precis=0.584  averag=0.539
random forest                 accura=0.963  recall=0.211  precis=0.664  averag=0.546

The dummy model has 95.6% accuracy and 0 recall: it never finds a spill. The forest has almost the same accuracy (96.3%) but finds only 21.1% of spills. Average precision, the area under the precision-recall curve, is the better single number here: the dummy gets 0.044, which is just the share of spills, and the models get about 0.54.

Fix 1: class weights

Class weights make mistakes on the rare class cost more during training. It is one argument and does not change the data.

run("logistic + balanced weights", make_pipeline(StandardScaler(), LogisticRegression(max_iter=2000, class_weight="balanced")))
run("forest + balanced_subsample", RandomForestClassifier(200, random_state=0, n_jobs=2, class_weight="balanced_subsample"))

Output:

logistic + balanced weights   accura=0.921  recall=0.737  precis=0.336  averag=0.520
forest + balanced_subsample   accura=0.958  recall=0.098  precis=0.444  averag=0.599

For logistic regression, recall jumps from 0.452 to 0.737 but precision falls from 0.584 to 0.336 and accuracy drops to 92.1%. That is a trade, not a gain: the model raises more alarms. The forest’s average precision rises to 0.599, though its recall at the default 0.5 threshold is still only 0.098.

Fix 2: SMOTE, inside the pipeline

SMOTE creates synthetic minority rows by interpolating between neighbours. With imbalanced-learn it must go in an imblearn pipeline, so it is applied only to the training part of each fold.

from imblearn.pipeline import make_pipeline as imb_pipeline
from imblearn.over_sampling import SMOTE

run("logistic + SMOTE", imb_pipeline(StandardScaler(), SMOTE(random_state=0), LogisticRegression(max_iter=2000)))
run("forest + SMOTE", imb_pipeline(SMOTE(random_state=0), RandomForestClassifier(200, random_state=0, n_jobs=2)))

Output:

logistic + SMOTE              accura=0.927  recall=0.729  precis=0.350  averag=0.525
forest + SMOTE                accura=0.967  recall=0.438  precis=0.710  averag=0.642

SMOTE with logistic regression behaves like class weights (recall 0.729, precision 0.350). With the forest, SMOTE gives the best average precision, 0.642 against 0.546 without it. That is on 41 positive rows only, so a gap of 0.1 between methods is suggestive rather than settled, and I did not repeat the experiment on other datasets.

The mistake that makes SMOTE look perfect

A common error is to oversample the whole dataset first and cross-validate afterwards. Synthetic copies of a row then land in both the training and test folds.

from sklearn.model_selection import cross_val_score

Xr, yr = SMOTE(random_state=0).fit_resample(X, y)
print(np.bincount(yr))
rf = RandomForestClassifier(200, random_state=0, n_jobs=2)
print("average precision:", round(cross_val_score(rf, Xr, yr, cv=cv, scoring="average_precision", n_jobs=2).mean(), 3))
print("recall:", round(cross_val_score(rf, Xr, yr, cv=cv, scoring="recall", n_jobs=2).mean(), 3))

Output:

[896 896]
average precision: 1.0
recall: 0.992

Average precision of 1.000 and recall of 0.992 are not real. The honest figure, from the pipeline above, was 0.642. This is data leakage, the same problem we measured in train test split in Python. Always resample after the split, and never on the test data.

Fix 3: choose the threshold

Often the best fix needs no resampling: keep the model and move the cutoff. Here are out-of-fold probabilities from the plain forest at four thresholds.

from sklearn.model_selection import cross_val_predict, StratifiedKFold
from sklearn.metrics import recall_score, precision_score

p = cross_val_predict(RandomForestClassifier(200, random_state=0, n_jobs=2), X, y,
                      cv=StratifiedKFold(5, shuffle=True, random_state=0), method="predict_proba")[:, 1]
for t in [0.5, 0.3, 0.2, 0.1]:
    pred = p >= t
    print(t, "flagged", pred.sum(), "recall", round(recall_score(y, pred), 3), "precision", round(precision_score(y, pred), 3))

Output:

0.5 flagged 12 recall 0.22 precision 0.75
0.3 flagged 35 recall 0.439 precision 0.514
0.2 flagged 56 recall 0.634 precision 0.464
0.1 flagged 100 recall 0.707 precision 0.29

At 0.5 the forest flags 12 patches and finds 22% of the 41 spills with 75% precision. At 0.2 it flags 56 and finds 63% with 46% precision. Which is right depends on what a missed spill costs compared to a false alarm, a business decision the data cannot make. Pick the threshold on training or validation data, not on the final test set.

For the metrics themselves see our scikit-learn model tutorial and the random forests guide; the free confusion matrix calculator turns counts into precision and recall. The imbalanced-learn user guide documents SMOTE and its variants. Dataset citation: Kubat, Holte and Matwin (1998), Machine Learning 30, from the jbrownlee Datasets repository. Not tested: undersampling, ensembles built for imbalance, and cost-sensitive boosting.

FAQ

How do you handle imbalanced data in Python?

Use a metric that fits the problem (average precision, recall and precision rather than accuracy), validate with stratified cross-validation, then try class weights, resampling inside a pipeline and threshold tuning. Here the forest with SMOTE in a pipeline scored best, 0.642 average precision.

Is SMOTE better than class weights?

Not always. With logistic regression the two gave nearly the same results here (recall 0.729 against 0.737). With the forest SMOTE scored higher on average precision, but on only 41 positive examples.

Why is my SMOTE score near 100%?

You probably oversampled before splitting. Synthetic neighbours of test rows end up in training. Our leaky run reported 1.000 average precision against 0.642 for the correct pipeline.

Which metric should I use for imbalanced classification?

Average precision or the precision-recall curve when you care about the rare class, plus recall and precision at the threshold you will use. ROC AUC was 0.93 for the plain logistic model here and hides how many false alarms it produces.

Newsletter Signup Form

Latest tutorials

Latest articles

On this page
Verified by MonsterInsights