Rare classes: stratify, weigh, resample or move the threshold
Four tools with different effects on probabilities. Choose the right metric first, resample only inside folds, and see why moving the threshold is often enough.
What runs in CodeSplash
You will be able to
- Compare class weights, resampling and threshold moves, and what each changes
- Explain why resampling must stay inside training folds
- Choose metrics that can see a rare class
Read first
First, what's the actual problem?
ReadA rare classClass imbalanceOne outcome class is much rarer than the other, so accuracy can look high while the rare class is missed. doesn't necessarily mean the model can't learn. It often means:
- The metric hides it: accuracy rewards ignoring the class.
- The default threshold doesn't suit it: 0.5 is far too high for a 2% event.
- There are few real cases: nothing cures this except more of them.
Fix 1 and 2 before you reach for resampling.
Lazy models, again
ExploreSet Share of positives low. Move Decision threshold until the Cost is within 2% of the lowest. See how little of this needs a change to the model: ROC AUC doesn't move at all as you drag.
HExplorable · Rare events and the decision threshold
Why can a 98% accurate model be useless, and where should the threshold go?
A lazy model calls every case negative. What accuracy does it score?
| flagged | passed | |
|---|---|---|
| pos | 52 | 62 |
| neg | 312 | 4574 |
Bars are drawn to one count scale, so a rare positive class looks as rare as it is. The ROC curve barely notices the imbalance; the precision–recall curve shows it. Cheapest threshold here: 1.14; the binormal formula gives 1.35.
Commit your prediction above to see the result
Make your prediction to see the result.
Now press keep the default threshold on rare events. A threshold is a decision, and this one suits nobody.
Four tools
Read| Tool | What it changes | Effect on probabilities |
|---|---|---|
| Stratified folds | Which rows each fold tests | None |
| Class weights | How much each class's errors count | Inflates the rare class |
| Rebalance training rows | The rows a model trains on | Inflates the rare class |
| Threshold | Only the final decision | None |
Weighting and resampling trade calibration for sensitivity at 0.5. If you use them, recalibrate if the probabilities themselves matter.
Does resampling help?
PredictPredict first
A 10%-positive version of Pima, LightGBM, judged by balanced accuracy. Plain class weights plus a large positive-class weight give 0.649. What does SMOTE up to a 60% ratio do?
Reveal
Somewhat better on this metric: 0.706. XGBoost with its Positive-class weight alone gets 0.697. Balanced accuracy at 0.5 rewards pushing probabilities up, which is exactly what these tools do. So a threshold move on the plain model might get you the same place, without distorting the probabilities.
Inside the folds, always
PredictPredict first
SMOTE draws synthetic rows between a rare row and its neighbors. You run it on all rows first, then cross-validate. What happens to the score?
Reveal
It goes up, for no good reason. Validation rows now contain near-copies of training rows. The app resamples each fold's training rows only, so validation and test rows keep the true class balance, and scores stay honest.
Undersampling
ReadRandom undersampling drops common-class rows. It's cheap on large tables, and sometimes helps tree speed. On ordinary-balance Pima, keeping a class ratio of 0.8 gives an AUC of 0.845, close to 0.829 on seven features with no resampling. AUC doesn't care about the threshold, so resampling rarely moves it much.
Check your understanding
CheckpointCheck yourself
You train with balanced class weights on a 5% class. A model predicts 40% for a row. Which is right?
Show the answer
Answer: b
Weights change what the loss rewards. The ranking may be fine, but the probability scale isn't what it says it is.
Check yourself
Where should SMOTE happen in cross-validation?
Show the answer
Answer: b
Doing it earlier puts copies of validation information into training. Scoring on resampled rows would distort the metric too.
Check yourself
Balanced weights give each class the weight . With 1,000 rows, 2 classes and 91 positives, what's the positive class's weight? Give one decimal.
Show the answer
Answer: 5.5
. The app's help for Class weights gives this formula.
Check yourself
Your rare-event model has a good PR AUC but flags nothing at 0.5. What's the simplest first fix?
Show the answer
Answer: a
If the ranking is good, the model has already learned. All that's missing is a threshold suited to the decision.
Try the options
In the appIn Validation, under Preprocessing for every model, set Class weights or Rebalance training rows (random oversampling, undersampling or SMOTE), with Target class ratio. Compare runs on the Leaderboard. Then, on the best one, use Threshold on the Evaluation tab, and look at Recalibrate probabilities on Diagnostics.
import pandas as pd
from imblearn.over_sampling import SMOTE
from imblearn.pipeline import make_pipeline
from lightgbm import LGBMClassifier
from sklearn.metrics import balanced_accuracy_score, roc_auc_score
from sklearn.model_selection import StratifiedKFold, cross_val_predict
df = pd.read_csv("pima_rare.csv")
X, y = df[["glu", "bmi", "age", "ped"]], df["diabetic"]
cv = StratifiedKFold(5, shuffle=True, random_state=1)
base = LGBMClassifier(n_estimators=30, num_leaves=6, verbose=-1)
for name, m in [("plain", base), ("smote", make_pipeline(SMOTE(random_state=1), base))]:
p = cross_val_predict(m, X, y, cv=cv, method="predict_proba")[:, 1] # SMOTE stays inside each fold
print(name, round(roc_auc_score(y, p), 3), round(balanced_accuracy_score(y, p > 0.5), 3))df <- read.csv("pima_rare.csv")
df$y <- df$diabetic == "true" | df$diabetic == "TRUE"
set.seed(1)
fold <- sample(rep(1:5, length.out = nrow(df)))
p_plain <- p_over <- numeric(nrow(df))
for (k in 1:5) {
tr <- df[fold != k, ]; te <- df[fold == k, ]
p_plain[fold == k] <- predict(glm(y ~ glu + bmi + age + ped, binomial, tr), te, type = "response")
extra <- tr[sample(which(tr$y), sum(!tr$y) - sum(tr$y), replace = TRUE), ] # training rows only
p_over[fold == k] <- predict(glm(y ~ glu + bmi + age + ped, binomial, rbind(tr, extra)), te, type = "response")
}
bal <- function(p) mean(c(mean(p[df$y] > 0.5), mean(p[!df$y] <= 0.5)))
round(rbind(plain = c(as.numeric(pROC::auc(df$y, p_plain, quiet = TRUE)), bal(p_plain)),
oversampled = c(as.numeric(pROC::auc(df$y, p_over, quiet = TRUE)), bal(p_over))), 3)Recap
Recap- Choose a metric that sees the rare class, then a threshold that suits the decision.
- Weights and resampling inflate probabilities. Recalibrate if you need them as probabilities.
- Resample inside each fold's training rows, never before the split.
Concepts in this lesson