TExcelTAD
Home › Data Preparation Toolkit: Cleaning to Leakage-Free Splits › Undersampling, Oversampling, SMOTE and ADASYN

Undersampling, Oversampling, SMOTE and ADASYN

A fraud model sees 1 fraudulent transaction for every 50 honest ones. Trained as usual, it learns that "honest" is almost always right, reaches 98% accuracy and catches almost no fraud. Class Distribution showed how to measure imbalance; this lesson and the next two fix it. The first family of remedies changes the training set itself: remove majority rows, repeat minority rows, or invent new minority rows. The scikit-learn basics are in Imbalanced Data; here we go deeper and use imbalanced-learn (imblearn), which runs in the browser.

See it first

The lab trains a logistic regression on 200 majority points (blue circles) and a few minority points (orange squares). Switch the remedy and watch the boundary and the minority recall on a test set that keeps the real imbalance.

−2024−2024x₁x₂Remedy: noneplain logistic regressionA (200)B (15)p(B) = 0.5Test set: 1000 A, 75 Bpred. Bpred. Aactual Bactual A39TP36FN8FP992TNRecall of B0.520Precision for B0.830Accuracy0.959

With no remedy (15 minority points) the model finds 39 of the 75 minority test points, a recall of 0.520, with precision 0.830 and an impressive-looking accuracy of 0.959. The boundary cuts through the minority cloud, because every misclassified majority point costs as much as a missed minority point and there are more than 13 times as many of them. Random oversampling pushes the boundary towards the majority: recall 0.853, precision 0.481. The SMOTE-like option gives the same recall with precision 0.500. Recall goes up, precision and accuracy go down. That trade is the whole story of rebalancing; no method gives recall for free.

The four resampling methods

Method What it does Risk
Random undersampling drops majority rows at random until the classes match (or reach a chosen ratio) throws away data; fine when the majority is huge
Random oversampling repeats minority rows (sampling with replacement) exact copies make overfitting to those points easy
SMOTE creates new minority points between a minority point and one of its minority neighbours can create points inside the majority region when classes overlap
ADASYN like SMOTE, but creates more points around minority samples that are hard (surrounded by majority) amplifies noise: a mislabelled minority point gets many children

SMOTE (Synthetic Minority Over-sampling TEchnique) picks a minority sample xix_i, one of its kk nearest minority neighbours xnnx_{nn}, and a random uu between 0 and 1:

xnew=xi+u (xnn−xi),u∼U(0,1)x_{\text{new}} = x_i + u \,(x_{nn} - x_i), \qquad u \sim \mathcal{U}(0, 1)

So every synthetic point lies on a segment between two real minority points. ADASYN first measures how hard each minority point is: among its kk nearest neighbours of any class, let Δi\Delta_i be the number that belong to the majority. Its share of the synthetic points is

gi=G⋅Δi/k∑jΔj/kg_i = G \cdot \frac{\Delta_i / k}{\sum_j \Delta_j / k}

where GG is the total number of points to create. A minority point with no majority neighbours gets none; one surrounded by the majority gets the most.

SMOTE from scratch

Six lines of NumPy are enough for the core idea:

python · try it yourself
import numpy as np

rng = np.random.default_rng(0)
minority = rng.normal([2.0, 2.0], 0.5, size=(6, 2))

def smote(X, n_new, k=3, rng=rng):
    d = ((X[:, None, :] - X[None, :, :]) ** 2).sum(-1)
    np.fill_diagonal(d, np.inf)
    nbrs = np.argsort(d, axis=1)[:, :k]          # k nearest minority neighbours
    i = rng.integers(0, len(X), n_new)            # a random base point
    j = nbrs[i, rng.integers(0, k, n_new)]        # one of its neighbours
    u = rng.random((n_new, 1))
    return X[i] + u * (X[j] - X[i]), i, j, u.ravel()

new, i, j, u = smote(minority, 4)
for a, b, t, p in zip(i, j, u, new):
    print(f"between #{a} and #{b}, u = {t:.2f} -> ({p[0]:.2f}, {p[1]:.2f})")
lo, hi = minority.min(0), minority.max(0)
print("inside the minority bounding box:", bool(((new >= lo) & (new <= hi)).all()))
between #2 and #1, u = 0.86 -> (2.24, 2.07)
between #5 and #1, u = 0.54 -> (2.03, 2.04)
between #3 and #2, u = 0.30 -> (2.38, 2.39)
between #0 and #1, u = 0.42 -> (2.17, 1.98)
inside the minority bounding box: True

Each new point is a weighted average of two real minority points, so it can never leave the region spanned by the minority class (here its bounding box). That is the strength of SMOTE (no copies) and its weakness (if the majority class lives between two minority points, the new point lands among the majority).

The library: imbalanced-learn

All four methods share one interface, fit_resample(X, y), which returns a new X and y:

python · try it yourself
from collections import Counter
from sklearn.datasets import make_classification
from imblearn.under_sampling import RandomUnderSampler
from imblearn.over_sampling import RandomOverSampler, SMOTE, ADASYN

X, y = make_classification(n_samples=2000, n_features=6, n_informative=4,
                           weights=[0.95], flip_y=0.01, random_state=0)
print("original     ", dict(sorted(Counter(y.tolist()).items())))
for sampler in [RandomUnderSampler(random_state=0), RandomOverSampler(random_state=0),
                SMOTE(k_neighbors=5, random_state=0), ADASYN(n_neighbors=5, random_state=0)]:
    Xr, yr = sampler.fit_resample(X, y)
    print(f"{type(sampler).__name__:<19}", dict(sorted(Counter(yr.tolist()).items())))

half = RandomUnderSampler(sampling_strategy=0.5, random_state=0)   # minority / majority = 0.5
print("under to 1:2       ", dict(sorted(Counter(half.fit_resample(X, y)[1].tolist()).items())))
original      {0: 1888, 1: 112}
RandomUnderSampler  {0: 112, 1: 112}
RandomOverSampler   {0: 1888, 1: 1888}
SMOTE               {0: 1888, 1: 1888}
ADASYN              {0: 1888, 1: 1897}
under to 1:2        {0: 224, 1: 112}

ADASYN does not hit an exact 50/50 split: it rounds each point's share gig_i separately. sampling_strategy sets the target ratio; full balance is rarely needed, and a milder ratio often keeps precision higher.

Resample inside cross-validation only

Resampling is a fitted step: it must see training data only. If you oversample first and then split, copies (or SMOTE neighbours) of the same minority point land in both the training and the test folds, and the score is inflated. imblearn.pipeline.Pipeline is a drop-in replacement for scikit-learn's Pipeline that calls fit_resample during fit and skips it during predict, so each validation fold keeps the real class ratio:

python · try it yourself
import numpy as np
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_validate
from sklearn.preprocessing import StandardScaler
from imblearn.pipeline import Pipeline
from imblearn.under_sampling import RandomUnderSampler
from imblearn.over_sampling import RandomOverSampler, SMOTE, ADASYN

X, y = make_classification(n_samples=2000, n_features=6, n_informative=4,
                           n_redundant=0, n_clusters_per_class=1, weights=[0.95],
                           flip_y=0.01, class_sep=1.0,
                           random_state=0)
cv = StratifiedKFold(5, shuffle=True, random_state=0)
samplers = {"none": None, "undersample": RandomUnderSampler(random_state=0),
            "oversample": RandomOverSampler(random_state=0),
            "SMOTE": SMOTE(random_state=0), "ADASYN": ADASYN(random_state=0)}
print(f"{'method':<12}{'recall':>8}{'precision':>11}{'F1':>7}{'AP':>7}")
for name, s in samplers.items():
    pipe = Pipeline([("scale", StandardScaler()), ("resample", s),
                     ("clf", LogisticRegression(max_iter=1000))])
    r = cross_validate(pipe, X, y, cv=cv,
                       scoring=["recall", "precision", "f1", "average_precision"],
                       error_score="raise")
    print(f"{name:<12}{r['test_recall'].mean():>8.3f}{r['test_precision'].mean():>11.3f}"
          f"{r['test_f1'].mean():>7.3f}{r['test_average_precision'].mean():>7.3f}")
method        recall  precision     F1     AP
none           0.666      0.843  0.742  0.773
undersample    0.910      0.310  0.462  0.751
oversample     0.910      0.344  0.499  0.734
SMOTE          0.910      0.351  0.506  0.748
ADASYN         0.919      0.283  0.432  0.715

Five-fold stratified cross-validation on 2,000 rows with about 5% positives (the minority class), every number the mean over the five validation folds. Without resampling the model finds two thirds of the positives (recall 0.666) with high precision (0.843). Every resampler raises recall to about 0.91 and drops precision to 0.28–0.35: the model now flags many more rows. F1 falls here, but whether that trade is good depends on the cost of a miss versus a false alarm, not on F1. Notice also that SMOTE did not beat plain oversampling by much; on many tabular problems it doesn't, so try the simple method first.

Note: Average precision (AP) summarises the whole precision–recall curve, so it barely depends on where the threshold sits. That is why resampling, which mostly shifts the threshold of a linear model, changes recall and precision a lot and AP only a little. The next two lessons show the cheaper ways to get the same shift: class weights and threshold adjustment.

Pitfalls

  • Resampling before the split (or before cross-validation): duplicated or interpolated minority points leak into the test folds. Always resample inside the training part, with imblearn.pipeline.Pipeline.
  • Rebalancing the test set: the test set must keep the real class ratio, or precision and accuracy describe a world that does not exist.
  • SMOTE on unscaled or categorical features: neighbours are found with Euclidean distance, so scale first; for categorical columns use SMOTENC or SMOTEN, since "halfway between red and blue" means nothing.
  • Judging by accuracy: use recall, precision, F1, AP or a cost-based metric chosen with the people who own the problem.

Practice

  1. Why can SMOTE produce a misleading point when the minority class forms two separate clusters?
Answer

If a minority point's kk nearest minority neighbours include points of the other cluster, the segment between them crosses whatever lies between the clusters, often majority territory. The synthetic point then sits among majority points with a minority label, which teaches the model a wrong region. Smaller kk, or variants such as Borderline-SMOTE, reduce this.

  1. A colleague oversamples the whole dataset to 50/50 and then runs cross_val_score. The recall is 0.97. What do you tell them?
Answer

The copies of each minority row are spread over the folds, so the model is tested on exact copies of rows it was trained on: the recall is inflated. Put the sampler in an imblearn.pipeline.Pipeline with the model and cross-validate the pipeline, so resampling happens on each training fold only.

Test yourself

Where does SMOTE place a synthetic minority point?

  1. At a random place in feature space
  2. On the segment between a minority point and one of its nearest minority neighbours
  3. At the mean of the minority class
  4. On top of an existing minority point

Which minority points get the most synthetic neighbours in ADASYN?

  1. Those far from every majority point
  2. Those whose nearest neighbours are mostly majority points
  3. The first ones in the table
  4. All get the same number

What does imblearn.pipeline.Pipeline do with the sampler when the pipeline predicts?

  1. Resamples the test data too
  2. Skips it: resampling happens only during fit
  3. Raises an error
  4. Undersamples the predictions

Which statement about random undersampling is true?

  1. It creates new majority points
  2. It discards majority rows, which is cheap but loses information
  3. It always beats SMOTE
  4. It must be applied to the test set as well