Sub topic 2
Stratified Splits and Resampling for Imbalanced Classification
Assume you know binary classification, train/test splits, cross-validation, and scikit-learn pipelines. This chapter uses a rare positive class, such as fraud or a failed product.
Stratified train/test splits and cross-validation
A stratified split preserves the class ratio in every subset. Without stratification, a small test set might contain too few positive examples, making evaluation unstable.
Use stratification for both the initial split and each cross-validation fold:
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split, StratifiedKFold
X, y = make_classification(
n_samples=2000,
n_features=10,
weights=[0.95, 0.05],
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
)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)Stratification preserves proportions. It does not prevent duplicate records, time-order problems, or other forms of leakage. Choose the split method that matches how predictions will be made in production.
Class weights
Class weights increase the penalty for mistakes on the rare class. With balanced, scikit-learn gives each class a weight inversely related to its frequency.
from sklearn.linear_model import LogisticRegression
model = LogisticRegression(class_weight="balanced", max_iter=1000)
model.fit(X_train, y_train)This changes the training objective, not the data. Check whether the resulting precision and recall match the cost of each error.
Random oversampling and undersampling
Random oversampling copies minority examples. Random undersampling removes majority examples. Oversampling keeps more data but can overfit repeated examples. Undersampling is faster but may discard useful information.
SMOTE
SMOTE creates synthetic minority points between nearby minority examples. It can help when the minority class has enough representative neighbors, but it can create unrealistic points near class boundaries.
Apply every resampling method only to training data. An imbalanced-learn pipeline performs this correctly inside each cross-validation fold:
from imblearn.over_sampling import SMOTE
from imblearn.pipeline import Pipeline
from sklearn.model_selection import cross_val_score
pipe = Pipeline([
("smote", SMOTE(random_state=42)),
("model", LogisticRegression(max_iter=1000)),
])
scores = cross_val_score(
pipe, X_train, y_train, cv=cv, scoring="average_precision"
)
print(scores.mean())Exercise
Why should SMOTE be inside the cross-validation pipeline?
Show answer
It must create synthetic samples using only each training fold. Resampling before cross-validation can leak information into validation folds and inflate the score.