Overview
When 99 of 100 rows belong to one class, a model can be 99 percent accurate by always predicting that class, and it learns almost nothing about the rare one. Rebalancing changes what the model sees during training so that the rare class counts for more. You can repeat rare rows, invent new rare rows that resemble the real ones, throw away common rows, or leave the rows alone and make each rare row count more in the loss. SMOTE is the inventing option: it places new points on the line between a rare row and one of its nearest rare neighbours.
A short history
Classifiers trained on skewed classes tend to ignore the rare class, a problem studied through the 1990s with random over-sampling, under-sampling and cost-sensitive learning. In 2002 Nitesh Chawla, Kevin Bowyer, Lawrence Hall and Philip Kegelmeyer published SMOTE, which creates new minority rows by interpolating between neighbours instead of repeating rows. It became one of the most cited methods in the area, with many variants.
How it works
- Count the rows per class with class_counts and decide the target size from sampling_ratio, the wanted size of a small class relative to the largest.
- For random_over, draw existing rows of each small class at random, with repeats, until the class reaches the target size.
- For smote, find the k_neighbors nearest rows of the same class for every row of the small class.
- Pick a base row and one of its neighbours at random, draw a number between 0 and 1, and create a new row that far along the line from the base to the neighbour. Repeat until the target size is reached.
- For random_under, keep a random subset of each large class, cut down to the smallest class size divided by the ratio.
- fit_resample returns the new table and labels. sample_indices_ records the original row of each output row, with for a synthetic row.
- As an alternative to resampling, class_weights returns one weight per class for a weighted loss.
Watch out for
- Resampling before the split puts copies or near copies of the same rare row in both training and test data, and the test score becomes far too good. Split first, then resample the training part.
- A model trained on balanced data predicts probabilities as if the classes were balanced. For the true rare rate the probabilities are too high and need recalibration or a moved threshold.
- SMOTE interpolates in straight lines. If the rare class forms separate clusters or overlaps the common class, new points can land in the wrong region and act as label noise.
- SMOTE treats every column as a continuous number. On category codes or 0 and 1 flags it produces values such as 0.4 that mean nothing.
- Random undersampling throws data away. With a very rare class the remaining set can be too small to learn the common class well.
Use cases
When to use it
When a class you care about is rare, such as fraud or a disease, and the model ignores it. Resample the training split only, and judge the result with precision, recall or a similar measure, not accuracy.
In industry
- Fraud detection
- Fraud is a tiny share of card transactions, so teams weight the fraud class or under-sample normal transactions when training.
- Medical diagnosis
- Models for rare conditions are trained with class weights or over-sampling so that the few positive cases are not ignored.
- Predictive maintenance
- Failures are rare compared with normal operation, so failure records are over-sampled or weighted when training fault predictors.
Choosing it: what must hold
- Resampling applied to the training set only. Validation and test sets keep the real class shares.
- Evaluation with metrics suited to imbalance, such as precision, recall or the precision-recall curve, not accuracy.
- For SMOTE, numeric features on comparable scales and enough minority rows to have meaningful neighbours.
- Awareness that resampling shifts predicted probabilities, which may need recalibration.
When to choose something else
| If | Use instead |
|---|---|
| The model accepts class or sample weights | Class weights in the loss, which avoid changing the data |
| You only need better decisions, not a different model | Keep the data as it is and move the decision threshold |
| Features are categorical or mixed | Random over-sampling or under-sampling, or a SMOTE variant for categorical data |
| The minority class has only a handful of examples | Anomaly detection trained on the majority class |
Math foundations
Target size when oversampling
When oversampling, every class smaller than this is grown to it. A ratio makes all classes as large as the largest.
A synthetic SMOTE row
The new row lies on the segment between a real minority row and one of its nearest minority neighbours . It gets the minority label.
Undersampling limit
When undersampling, every class larger than this is cut to it by keeping a random subset.
Balanced class weights
Each row of class is weighted so that every class carries the same total weight in the loss. No rows are added or removed.
Symbols
- the number of rows and the number of classes
- the number of rows in class c
- the sizes of the largest and the smallest class
- sampling_ratio
- a real row of the minority class, used as the base
- one of the k nearest minority rows to the base
- a random number drawn uniformly between 0 and 1
- the loss weight of class c
Worked by hand
A training set has 90 rows of class 0 and 10 rows of class 1, with . Find how many rows SMOTE adds, make one synthetic row from the base and neighbour with , and compute the balanced weights.
SMOTE adds 80 synthetic rows, each on a line between two real minority rows. With weights instead, a rare row counts 9 times as much as a common one and both classes carry a total weight of 50.
Visual example
Loading the example.
Try this
- With smote, move the new row you inspect: every synthetic row lies on the line between a real minority row and one of its neighbours.
- Lower k_neighbors to 1 and the new rows bunch between closest pairs. Raise it and they spread across the whole cluster.
- Switch to random_over, then random_under, and compare what each does to the same points.
Code sample
import numpy as np
from impl import Resampler, class_counts, class_weights
from config import ResamplerConfig
rng = np.random.default_rng(0)
X = np.vstack([rng.normal(0.0, 1.0, size=(95, 2)), rng.normal(3.0, 1.0, size=(5, 2))])
y = np.array([0] * 95 + [1] * 5)
X_res, y_res = Resampler(ResamplerConfig(method="smote", k_neighbors=3)).fit_resample(X, y)
print(class_counts(y_res)) # {0: 95, 1: 95}
print(class_weights(y)) # {0: 0.526..., 1: 10.0}Read the implementation (99 lines)
"""Class-imbalance handling: SMOTE, random oversampling, random undersampling and balanced class weights.
NumPy only. `fit_resample` returns a rebalanced copy of the training data. Resample the training split only:
validation and test data must keep the real class shares.
"""
from __future__ import annotations
import numpy as np
try:
from .config import ResamplerConfig
except ImportError: # run from the template's own folder
from config import ResamplerConfig
def class_counts(y) -> dict:
"""Number of rows per class: {class: count}."""
classes, counts = np.unique(np.asarray(y), return_counts=True)
return {c.item(): int(n) for c, n in zip(classes, counts)}
def class_weights(y) -> dict:
""""Balanced" weights n_samples / (n_classes * count), for a weighted loss instead of resampling.
Every class then carries the same total weight; the weights average to 1 over the rows.
"""
counts = class_counts(y)
n, k = sum(counts.values()), len(counts)
return {c: n / (k * count) for c, count in counts.items()}
class Resampler:
"""Rebalances a labelled dataset. After `fit_resample`, `sample_indices_` gives, for every output row,
the index of the original row it is (or -1 for a synthetic SMOTE row)."""
def __init__(self, config: ResamplerConfig | None = None) -> None:
self.config = config or ResamplerConfig()
self.sample_indices_: np.ndarray | None = None
def _smote(self, rows: np.ndarray, n_new: int, rng: np.random.Generator) -> np.ndarray:
"""Make n_new synthetic rows from the rows of one class. rows: (m, d). Returns (n_new, d).
Each new row is base + u * (neighbour - base), with base a random row of the class, neighbour one of
its k nearest rows of the same class, and u uniform in [0, 1).
"""
m = rows.shape[0]
if m == 1:
return np.repeat(rows, n_new, axis=0) # no neighbour to interpolate with
k = min(self.config.k_neighbors, m - 1)
sq = (rows**2).sum(axis=1)
dist = sq[:, None] + sq[None, :] - 2.0 * rows @ rows.T
np.fill_diagonal(dist, np.inf)
neighbours = np.argsort(dist, axis=1, kind="stable")[:, :k] # (m, k)
base = rng.integers(0, m, size=n_new)
partner = neighbours[base, rng.integers(0, k, size=n_new)]
u = rng.random((n_new, 1))
return rows[base] + u * (rows[partner] - rows[base])
def fit_resample(self, X, y) -> tuple[np.ndarray, np.ndarray]:
"""Return (X_resampled, y_resampled). X: (n, d) floats, y: (n,) class labels.
Oversampling keeps all original rows first, in order, and appends the new rows class by class.
Undersampling returns a subset of the rows in their original order.
"""
X = np.asarray(X, dtype=float)
y = np.asarray(y)
if X.ndim != 2 or y.shape != (X.shape[0],):
raise ValueError("X must be (n, d) and y must be (n,)")
rng = np.random.default_rng(self.config.seed)
classes, counts = np.unique(y, return_counts=True)
ratio = self.config.sampling_ratio
if self.config.method == "random_under":
limit = max(int(round(counts.min() / ratio)), 1)
keep = []
for cls, count in zip(classes, counts):
idx = np.flatnonzero(y == cls)
keep.append(idx if count <= limit else rng.choice(idx, size=limit, replace=False))
keep = np.sort(np.concatenate(keep))
self.sample_indices_ = keep
return X[keep], y[keep]
target = int(round(ratio * counts.max()))
new_X, new_y, new_idx = [X], [y], [np.arange(X.shape[0])]
for cls, count in zip(classes, counts):
n_new = target - count
if n_new <= 0:
continue
idx = np.flatnonzero(y == cls)
if self.config.method == "smote":
new_X.append(self._smote(X[idx], n_new, rng))
new_idx.append(np.full(n_new, -1))
else:
picked = rng.choice(idx, size=n_new, replace=True)
new_X.append(X[picked])
new_idx.append(picked)
new_y.append(np.full(n_new, cls, dtype=y.dtype))
self.sample_indices_ = np.concatenate(new_idx)
return np.vstack(new_X), np.concatenate(new_y)- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 9, run with
python3 -m unittest -v
Practice
Make a two-column dataset with 950 rows of class 0 and 50 of class 1. Run Resampler.fit_resample with method smote, random_over and random_under through ResamplerConfig, and print class_counts of each result. Plot the SMOTE output and mark the rows whose sample_indices_ entry is . Then print class_weights for the original labels.
Check on learning
- Random oversampling adds no new information, only copies. Why can it still change what a model learns?
A way to think about it
Look at the loss as a sum over rows. Ask how the sum changes when a rare row appears nine times, and compare that with a class weight of nine.
- A model trained on a SMOTE-balanced set says a transaction is fraud with probability 0.5. The true fraud rate is 1 percent. Is 0.5 a fair estimate of the real chance?
A way to think about it
The model learned the odds in a world where half the rows are fraud. Think about how the prior rate enters a probability.
- The rare class forms two small clusters far apart, with common-class rows in between. What can SMOTE do wrong here, and how does k_neighbors affect it?
A way to think about it
A neighbour of a point in one cluster might be in the other cluster when the cluster is smaller than k. Follow the line between them.
- Why must the validation and test sets keep the original class shares?
A way to think about it
Ask what question the test score is meant to answer. The model will be used on data with the real shares.