Sub topic 13
Choosing a strategy for your problem
This chapter pulls the earlier techniques together into a decision process. It assumes you know scikit-learn estimators and pipelines, stratified cross-validation, and the metrics from earlier chapters: precision, recall, F1, average precision, and the idea of a decision threshold. It also assumes you have seen class weights, random resampling, SMOTE, and balanced ensembles. No single remedy wins every time. The goal here is to choose one on purpose and to check the choice honestly.
Start with the decision, not the technique
Most wasted effort in imbalanced problems comes from reaching for a remedy before settling three questions.
- What does each error cost? A missed fraud case, a missed tumor, and a false alarm that wastes an analyst's hour have different prices. If you can estimate them, even roughly, the cost ratio tells you where the decision threshold should sit.
- What will the model's output be used for? A hard label ("flag this transaction") needs a good threshold. A ranking ("review the top 200 cases") needs good ordering of scores. A probability ("this patient has a 3% risk") needs calibrated scores.
- How much data do you have? The number of minority examples matters more than the imbalance ratio. A 1% minority in ten million rows still gives you 100,000 positives. A 20% minority in 200 rows gives you 40.
The answers choose your evaluation metric first, and the metric constrains which remedies make sense.
| Deployment need | Primary metric | Remedy emphasis |
|---|---|---|
| Review a fixed number of top cases | Average precision, precision at k | Anything that improves ranking; threshold is irrelevant |
| Automatic yes/no decision with known costs | Expected cost, or F-beta at the chosen threshold | Threshold tuning on out-of-fold predictions |
| Probabilities fed into other systems | Brier score, log loss, calibration curve | Avoid distorting the base rate, or recalibrate afterwards |
| Catch nearly all positives | Recall at a minimum precision | Class weights or threshold shift, then check precision |
A decision flow
The flow below encodes the order that usually works. It starts with the cheapest and least invasive changes and moves toward heavier ones only when evidence says they are needed.
Two points about this flow deserve emphasis. First, the baseline and the threshold step come before any rebalancing. Many models already rank positives well, and the only problem is that the default 0.5 threshold is wrong for the base rate. Moving the threshold costs nothing and changes no training data. Second, the test set appears only at the end, once, after all choices are made.
Comparing candidates fairly
When you do compare strategies, hold everything else constant: the same split, the same folds, the same metrics. The script below compares a plain model, class weights, random undersampling, SMOTE, and a balanced random forest with the same stratified cross-validation. Resamplers are inside imbalanced-learn pipelines, so they only touch training folds.
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split, StratifiedKFold, cross_validate
from sklearn.linear_model import LogisticRegression
from imblearn.pipeline import Pipeline
from imblearn.over_sampling import SMOTE
from imblearn.under_sampling import RandomUnderSampler
from imblearn.ensemble import BalancedRandomForestClassifier
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
)
candidates = {
"plain": LogisticRegression(max_iter=1000),
"class_weight": LogisticRegression(class_weight="balanced", max_iter=1000),
"undersample": Pipeline([
("under", RandomUnderSampler(random_state=42)),
("clf", LogisticRegression(max_iter=1000)),
]),
"smote": Pipeline([
("smote", SMOTE(random_state=42)),
("clf", LogisticRegression(max_iter=1000)),
]),
"balanced_forest": BalancedRandomForestClassifier(
n_estimators=200, random_state=42, n_jobs=-1
),
}
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
scoring = {
"ap": "average_precision",
"f1": "f1",
"recall": "recall",
"brier": "neg_brier_score",
}
print(f"{'strategy':<16}{'AP':>8}{'F1':>8}{'recall':>8}{'Brier':>8}")
for name, estimator in candidates.items():
res = cross_validate(estimator, X_train, y_train, cv=cv, scoring=scoring)
print(
f"{name:<16}"
f"{res['test_ap'].mean():>8.3f}"
f"{res['test_f1'].mean():>8.3f}"
f"{res['test_recall'].mean():>8.3f}"
f"{-res['test_brier'].mean():>8.3f}"
)Read the table by column, not by row. Average precision measures ranking and does not depend on a threshold. F1 and recall at the default threshold will usually jump for the rebalanced models, because they push probabilities upward. That jump says little about better ranking. It mostly reflects the shifted scores. The Brier score, where lower is better, usually gets worse for the rebalanced models, which previews the calibration issue discussed below.
If average precision is nearly equal across strategies, you have learned something useful: the model's ranking is not improved by rebalancing, and the remaining question is only where to put the threshold.
How to read the results
Differences smaller than the fold-to-fold spread are noise
With 5% positives and 7,500 training rows, each validation fold holds roughly 75 positives. Metrics computed on so few positives vary a lot between folds. Print the standard deviation next to each mean, for example res['test_ap'].std(). If two strategies differ by less than that spread, treat them as tied and prefer the simpler one. For small datasets, repeat cross-validation with RepeatedStratifiedKFold to get a steadier estimate.
Compare at the same operating point
F1 at a threshold of 0.5 compares strategies at different operating points, because each one shifts the scores differently. A fair comparison either uses a threshold-free metric (average precision) or tunes each model's threshold on out-of-fold predictions first and then compares the tuned results. Otherwise a model that is merely shifted can look better than one that ranks better.
Tune on the training data, judge on the test data
Every choice in this chapter (strategy, hyperparameters, threshold) belongs to the training side of the split. Choose by cross-validation on the training set. Touch the test set once, for the final estimate of the chosen pipeline. If you look at the test set repeatedly and adjust, it becomes a second validation set and your final number is optimistic.
When each strategy fits
The following guidance is a starting point. Check it against your own cross-validated numbers.
- Threshold tuning alone. Works well when the model already separates the classes reasonably and the data is large. It is cheap, reversible, and leaves the training distribution untouched. Always try it first.
- Class weights. A good default when you want the model to pay more attention to the minority class during training. It adds no rows, so it is fast and has no leakage risk. It works with most linear models, trees, and boosting libraries through
class_weightorscale_pos_weight. - Random undersampling. Useful when the majority class is huge and training time matters, because it shrinks the data. The cost is discarded information, so it is a poor choice when the total data is small. Undersampling inside bagging (balanced ensembles) recovers some of the discarded rows.
- Random oversampling. Simple and keeps all the data, but duplicated rows make flexible models memorize the minority points. It suits regularized or low-capacity models better than deep trees.
- SMOTE. Can help models that depend on the geometry of feature space, but it has requirements. It needs numeric features, or a variant such as SMOTENC for mixed data. It behaves poorly with high-dimensional or noisy data, where interpolated points land in meaningless places. It often gives no measurable gain over class weights for gradient-boosted trees. Treat it as one candidate to test, not as the default.
- Balanced ensembles. Good when you want a strong nonlinear model and undersampling's information loss worries you. Each member sees a balanced subsample and the ensemble sees most of the data. Training costs more than a single model.
Very small minority classes
With a few dozen positives, every remedy has limits. Resampling cannot create information that is not in the data, and SMOTE's neighbors are unstable. Prefer simple, regularized models, stratified repeated cross-validation, and class weights. The most valuable fix is usually collecting more positive examples or adding labelled data.
Calibration after rebalancing
Class weights, resampling, and balanced ensembles all change the effective class ratio the model sees during training. The predicted probabilities then describe a world where positives are common, not your real data. A score of 0.8 might correspond to a true positive rate of 20%.
This does not matter if you only rank cases or choose a threshold on out-of-fold predictions. It matters if anyone reads the score as a probability, such as in expected-cost calculations, risk displays, or inputs to another model. In that case, check a calibration curve with sklearn.calibration.calibration_curve, and if the curve is off, wrap the model in CalibratedClassifierCV fitted on data with the true class ratio. Calibrate on held-out data from the real distribution, not on resampled data.
Common mistakes
- Resampling before the split. Duplicated or synthetic rows end up in both training and validation data, so the score is inflated by leakage. Resample only inside the pipeline.
- Rebalancing the test set. The test set should keep the natural class ratio, because that is what the model will face.
- Choosing a strategy by accuracy. Accuracy rewards the majority class and can rank a worse model higher.
- Stacking every remedy. Class weights plus oversampling plus threshold shifting plus a balanced ensemble pushes the same correction in several places at once. The result is often too many false positives. Add one change at a time and measure it.
- Tuning the threshold on the test set. Use out-of-fold predictions from the training data.
- Ignoring the cost of reviewing positives. If analysts can only review 100 cases per day, precision at 100 is the metric that matters, regardless of F1.
Quick checklist
- State the cost of each error and the use of the output (label, ranking, or probability).
- Pick a threshold-free metric for comparing models, and a threshold-dependent metric for the final operating point.
- Split with stratification and keep the test set untouched.
- Build a plain baseline and tune its threshold on out-of-fold predictions.
- Add class weights, then resampling or a balanced ensemble, only if they beat the baseline by more than the fold-to-fold spread.
- Keep all resampling inside the pipeline.
- Check calibration if the probabilities will be used as probabilities.
- Evaluate once on the untouched test set.
Exercise
A team compares a plain logistic regression and the same model with SMOTE. At the default 0.5 threshold, the SMOTE model has much higher recall and F1. Its cross-validated average precision is almost identical to the plain model's. What should the team conclude, and what should they do next?
Show answer
The higher recall and F1 mostly reflect shifted scores, not better ranking, since average precision (threshold-free) is nearly unchanged. The team should tune the threshold of the plain model on out-of-fold predictions and compare the two models at tuned operating points. If they then perform about equally, they should keep the simpler plain model, which also keeps its probabilities closer to calibrated.
Exercise
Why must a calibration check use validation data with the natural class ratio, and what should you do if a balanced model's probabilities are miscalibrated but its ranking is good?
Show answer
Balancing the validation data changes the base rate, so the measured calibration would not describe production behavior. If ranking is good but the probabilities are off, keep the model and fit a calibrator such as CalibratedClassifierCV on held-out data with the true class ratio, or use only the ranking and a tuned threshold if no one needs the probabilities.