Sub topic 8
SMOTE: generating synthetic minority samples
This chapter assumes you know how random oversampling works, how stratified cross-validation works, and how to use scikit-learn estimators and pipelines. It also assumes a basic grasp of nearest-neighbor distance. You will see how SMOTE builds new minority rows, how to run it without leaking information, and when it hurts more than it helps.
Why not just duplicate rows?
Random oversampling copies existing minority rows until the classes are balanced. A flexible model such as a deep tree or a k-nearest-neighbor classifier can then memorize those exact points. The decision region shrinks to tiny islands around each duplicate, and the model overfits.
SMOTE (Synthetic Minority Over-sampling Technique, Chawla et al., 2002) creates new points instead of copies. Each new point lies on the line segment between a minority sample and one of its minority-class neighbors. This fills in the region between known positives, so the classifier sees a broader minority area.
How the algorithm works
For each synthetic sample SMOTE does the following:
- Pick a minority sample at random. Call it the base point.
- Find its
knearest neighbors among minority samples only. The default isk_neighbors=5. - Pick one of those neighbors at random.
- Draw a number
gapuniformly between 0 and 1. - Create the new point:
base + gap * (neighbor - base).
The whole method fits in a few lines of NumPy. This version is for understanding, not production.
import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.neighbors import NearestNeighbors
def smote_samples(X_min, n_new, k=5, seed=0):
rng = np.random.default_rng(seed)
nn = NearestNeighbors(n_neighbors=k + 1).fit(X_min)
_, idx = nn.kneighbors(X_min) # column 0 is the point itself
base = rng.integers(0, len(X_min), size=n_new)
pick = rng.integers(1, k + 1, size=n_new)
neighbor = idx[base, pick]
gap = rng.random((n_new, 1))
return X_min[base] + gap * (X_min[neighbor] - X_min[base])
X, y = make_classification(
n_samples=10000, n_features=20, n_informative=5,
weights=[0.95, 0.05], flip_y=0.01, random_state=42,
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=42
)
X_min = X_train[y_train == 1]
n_new = int((y_train == 0).sum() - (y_train == 1).sum())
synthetic = smote_samples(X_min, n_new)
print("real minority rows:", len(X_min))
print("synthetic rows:", synthetic.shape[0])Every synthetic row is a convex combination of two real minority rows. It can never fall outside the region the minority points already span.
Using imbalanced-learn
In practice you use imblearn.over_sampling.SMOTE. Install it with pip install imbalanced-learn. Its main parameters are:
| Parameter | Meaning | Typical choice |
|---|---|---|
| `sampling_strategy` | Target class ratio. A float is minority/majority after resampling. `"auto"` balances fully. | `0.3` to `1.0` |
| `k_neighbors` | Neighbors considered for interpolation. Must be smaller than the minority count. | 3 to 10 |
| `random_state` | Seed for reproducibility. | Any integer |
Full balancing is not required. Raising the minority to 30% or 50% of the majority often works as well as 100% and distorts the data less.
from imblearn.over_sampling import SMOTE
sm = SMOTE(sampling_strategy=0.5, k_neighbors=5, random_state=42)
X_res, y_res = sm.fit_resample(X_train, y_train)
print("before:", np.bincount(y_train))
print("after: ", np.bincount(y_res))Here np.bincount shows the counts per class. After resampling, the minority count is half the majority count.
Resample inside the pipeline
SMOTE changes only the data it is fitted on. Apply it once to the whole training set and then cross-validate, and synthetic points built from a row can land in a different fold than the row itself. A validation fold then contains points that are interpolations of training rows. The model has effectively seen them, and the score is inflated.
The fix is to resample inside each fold. imblearn.pipeline.Pipeline applies samplers only during fit, never during predict or score. Use it in place of scikit-learn's Pipeline, which does not accept samplers.
from imblearn.pipeline import Pipeline
from imblearn.over_sampling import SMOTE
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
# Wrong: resample first, then cross-validate.
X_res, y_res = SMOTE(random_state=42).fit_resample(X_train, y_train)
leaky = cross_val_score(
LogisticRegression(max_iter=1000), X_res, y_res,
cv=cv, scoring="average_precision",
)
# Right: SMOTE runs on the training part of each fold only.
pipe = Pipeline([
("smote", SMOTE(random_state=42)),
("clf", LogisticRegression(max_iter=1000)),
])
honest = cross_val_score(
pipe, X_train, y_train, cv=cv, scoring="average_precision"
)
print("leaky score: ", leaky.mean())
print("honest score:", honest.mean())The leaky score is typically higher. Its validation folds are also balanced and contain synthetic points, so it does not measure what you will see on real, imbalanced data.
Scale your features first
SMOTE relies on Euclidean distance to find neighbors. A feature measured in thousands dominates one measured in fractions, so "nearest" is decided by the large-scale feature. Put a scaler before SMOTE in the pipeline.
from sklearn.preprocessing import StandardScaler
pipe = Pipeline([
("scale", StandardScaler()),
("smote", SMOTE(random_state=42)),
("clf", LogisticRegression(max_iter=1000)),
])The scaler is fitted on the training part of each fold only, like every other step.
Categorical features
Interpolating between two values of a one-hot column gives a fractional value that means nothing, such as 0.37 of a category. If your data has categorical columns, use SMOTENC (or SMOTEN when all columns are categorical). SMOTENC interpolates the numeric columns and assigns each categorical column the most common value among the neighbors.
import numpy as np
from imblearn.over_sampling import SMOTENC
rng = np.random.default_rng(0)
n = 1000
y_c = (rng.random(n) < 0.05).astype(int)
age = rng.normal(40, 10, n)
amount = rng.exponential(100, n) + 150 * y_c
channel = rng.integers(0, 3, n) # categorical, codes 0, 1, 2
X_c = np.column_stack([age, amount, channel])
sm = SMOTENC(categorical_features=[2], random_state=0)
X_res, y_res = sm.fit_resample(X_c, y_c)
print("class counts before:", np.bincount(y_c))
print("class counts after: ", np.bincount(y_res))
print("channel values after:", np.unique(X_res[:, 2]))The categorical column keeps only valid codes. The distance calculation still treats numeric scale as described above, so scale the numeric columns when you use SMOTENC in a real pipeline.
Variants
| Variant | Idea | Use when |
|---|---|---|
| `BorderlineSMOTE` | Synthesizes only from minority points near the class boundary. | The boundary is where errors occur. |
| `SVMSMOTE` | Uses support vectors of an SVM to find boundary points. | Moderate data size, since it fits an SVM. |
| `ADASYN` | Generates more samples where minority points are surrounded by majority points. | You want density-adaptive generation, and noise is low. |
| `KMeansSMOTE` | Clusters first and oversamples inside clusters. | The minority class has distinct sub-groups. |
| `SMOTENC`, `SMOTEN` | Handle mixed or fully categorical data. | Categorical features exist. |
Boundary-focused variants amplify label noise. A mislabeled point near the boundary becomes the source of many new points.
Failure modes
- Overlapping classes. SMOTE does not know where the majority class is. If a minority point sits inside a majority region, the line to its neighbor may cross majority territory, and the synthetic points fall in the wrong place. Cleaning methods such as
SMOTETomekorSMOTEENNremove ambiguous points after oversampling. - Noise. Outliers and mislabeled minority rows are copied outward by interpolation.
- High dimensions. In many dimensions, distances between points become similar, so the "nearest" neighbors are barely closer than any other minority point. The synthetic points add little information.
- Very few minority samples. With fewer than
k_neighbors + 1minority rows, SMOTE raises an error. With only a handful, the synthetic points all live in a tiny region, so the model gains little beyond duplication. - Shifted probabilities. After SMOTE, the model sees a training prior that differs from reality. Its predicted probabilities are inflated for the minority class. Rank-based metrics such as average precision are unaffected by this, but anything that reads the probability as a real-world frequency is wrong until you recalibrate. The calibration chapter covers this.
- Tree models. Gradient boosting and random forests often handle imbalance well with class weights or threshold tuning alone. SMOTE gives them smaller and less consistent gains than it gives linear models or neural networks.
Checklist
- Split with stratification and set the test set aside.
- Build an
imblearnPipelinewith a scaler, then SMOTE, then the classifier. - Choose
sampling_strategyandk_neighborsby cross-validation on the training set. - Use
SMOTENCif any feature is categorical. - Score on untouched folds with average precision or recall at a fixed precision.
- If you need real probabilities, recalibrate afterward.
Exercise
A teammate runs SMOTE().fit_resample(X, y) on the full dataset, then runs 5-fold cross-validation on the result and reports an F1 of 0.93. Give two reasons the number is unreliable, and describe the fix.
Show answer
First, synthetic points are interpolations of real minority rows, and those rows and their synthetic copies can land in different folds. The validation folds then contain information from the training folds, which inflates the score. Second, the validation folds are rebalanced and contain synthetic points, so they do not reflect the true class ratio the model will face. The fix is to put SMOTE in an imblearn Pipeline with the classifier, pass the original X and y to cross_val_score with a StratifiedKFold, and keep a test set that is never resampled.
Exercise
A dataset has 40 positive rows among 4,000, and one column is a categorical device_type stored as integer codes. Which SMOTE class would you pick, which parameter must you set, and why would the default k_neighbors=5 still be safe?
Show answer
Use SMOTENC and set categorical_features to the index of the device_type column, so its values are never interpolated into meaningless fractions. The default k_neighbors=5 is safe because the minority class has 40 rows, well above k_neighbors + 1. Inside cross-validation each training fold still holds about 32 positives, which is enough.