Sub topic 13
Choosing a strategy for your problem
This chapter assumes you know how to compute precision, recall and average precision, and that you have seen class weights, resampling, SMOTE, threshold tuning and calibration in earlier chapters. Here you will learn how to choose among them.
Start from the cost of errors
No remedy is best in general. Begin with three questions.
- What does a missed positive cost compared with a false alarm? If missing a fraud case is far worse than reviewing a clean transaction, favor recall and accept lower precision.
- Do you need probabilities or only a decision? A risk score that feeds a pricing rule needs calibrated probabilities. A yes/no alert does not.
- How much data do you have? With millions of rows, undersampling is cheap. With a few hundred positives, discarding negatives or inventing synthetic points both carry risk.
Fix the evaluation metric before you compare methods. For a rare positive class, average precision on stratified cross-validation folds is a sound default. Use F1 or recall at a fixed precision if the business sets a target.
A practical order of attempts
Try the cheapest, least invasive options first.
Class weights and threshold tuning change no data, so they cannot leak information. Resampling and ensembles add moving parts, so use them only when the simpler steps fall short.
Compare candidates fairly
Run every candidate through the same folds and the same metric. Any resampler must sit inside an imblearn pipeline so that only the training folds are resampled.
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score
from imblearn.pipeline import Pipeline
from imblearn.over_sampling import SMOTE
from imblearn.under_sampling import RandomUnderSampler
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,
)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
candidates = {
"plain": LogisticRegression(max_iter=1000),
"class_weight": LogisticRegression(class_weight="balanced", max_iter=1000),
"smote": Pipeline([
("smote", SMOTE(random_state=42)),
("clf", LogisticRegression(max_iter=1000)),
]),
"undersample": Pipeline([
("under", RandomUnderSampler(random_state=42)),
("clf", LogisticRegression(max_iter=1000)),
]),
}
for name, est in candidates.items():
s = cross_val_score(est, X, y, cv=cv, scoring="average_precision")
print(f"{name:13s} AP = {s.mean():.3f} +/- {s.std():.3f}")In a real project, run this on the training split only and keep the test set for one final check. Look at the standard deviation as well as the mean. If two methods differ by less than the fold-to-fold spread, pick the simpler one.
Rules of thumb
| Situation | Reasonable first choice | Watch out for |
|---|---|---|
| Moderate imbalance, linear or tree model | Class weights | Probabilities shift upward and need recalibration |
| Very large majority class | Random undersampling or a balanced ensemble | Lost information, high variance |
| Small dataset, numeric features | SMOTE inside a pipeline | Synthetic points in noisy or overlapping regions |
| Fixed precision or recall target | Threshold tuning on out-of-fold scores | Tuning on the test set |
| Probabilities drive downstream decisions | Any method, then calibrate | Calibrating on data used for training |
SMOTE interpolates between neighbors, so it does not suit categorical features unless you use a variant such as SMOTENC. Gradient-boosting libraries often offer their own weight parameters, such as scale_pos_weight in XGBoost, which can replace resampling.
Common mistakes
- Resampling before the split, which puts copies or neighbors of the same sample in both train and validation sets.
- Choosing the threshold on the test set.
- Reporting probabilities from a weighted or resampled model as if they were true risks.
- Reaching for SMOTE first, when class weights plus a tuned threshold would have matched it.
Exercise
A hospital screening model has 300 positive cases in 60,000 records. A missed case is far costlier than a false alarm, and clinicians want a risk score they can read as a probability. Which steps would you take, in order, and why?
Show answer
Use a stratified split and a baseline, then add class weights. Choose a threshold from out-of-fold predictions that reaches the required recall, and evaluate with average precision and recall on untouched folds. Use resampling only if this falls short, and only inside a pipeline. Because clinicians read the score as a probability and class weights inflate predicted probabilities, calibrate the model on held-out data before release.