Sub topic 3
Resampling, Thresholds, and Strategy Selection
Assume you know binary classification, train/test splits, cross-validation, scikit-learn estimators, and pipelines. The central rule is simple: resampling may change training data, but evaluation data must keep its natural class ratio.
Resampling Without Leakage
Resampling before cross-validation leaks information. For example, SMOTE may create a synthetic point using a neighbor that later appears in a validation fold. The validation score then becomes too optimistic.
Put the sampler and classifier in an imblearn pipeline. Each training fold is resampled independently, while its validation fold remains untouched.
import numpy as np
from imblearn.pipeline import Pipeline
from imblearn.over_sampling import SMOTE
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_predict
from sklearn.metrics import f1_score
X, y = make_classification(
n_samples=4000, weights=[0.95, 0.05], random_state=42
)
X_train, X_test = X[:3000], X[3000:]
y_train, y_test = y[:3000], y[3000:]
pipe = Pipeline([
("smote", SMOTE(random_state=42)),
("model", LogisticRegression(max_iter=1000)),
])
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
oof = cross_val_predict(
pipe, X_train, y_train, cv=cv, method="predict_proba"
)[:, 1]
precision, recall, thresholds = __import__(
"sklearn.metrics", fromlist=["precision_recall_curve"]
).precision_recall_curve(y_train, oof)
f1 = 2 * precision * recall / (precision + recall + 1e-12)
threshold = thresholds[np.argmax(f1[:-1])]
pipe.fit(X_train, y_train)
test_pred = (pipe.predict_proba(X_test)[:, 1] >= threshold).astype(int)
print("test F1:", f1_score(y_test, test_pred))Thresholds and Calibration
A classifier’s default threshold is usually 0.5. Choose another threshold when false negatives and false positives have different costs. Select it from out-of-fold predictions, as above, then apply it once to the test set.
Resampling changes the class ratio seen during fitting. Therefore, predicted probabilities may no longer represent real-world probabilities. If you need reliable probabilities, calibrate the final model with an untouched validation set that has the natural class distribution. Check calibration with reliability diagrams or Brier score.
Balanced Ensembles
Balanced random forests and bagging methods train many trees on balanced bootstrap samples. They often work well when nonlinear relationships exist. They cost more computation and can be harder to interpret than class-weighted linear models.
Choosing a Strategy
| Situation | First choice |
|---|---|
| Small dataset or clear error costs | Class weights and threshold tuning |
| Enough data and local minority patterns | SMOTE in a pipeline |
| Nonlinear boundaries | Balanced forest or another ensemble |
| Probability decisions | Natural-distribution calibration |
Exercise
Why must resampling occur inside each cross-validation training fold?
Show answer
To prevent synthetic or duplicated samples from influencing validation data and inflating the score.