Skip to content

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.

Applied ~12 min9 steps

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

01

First, what's the actual problem?

Read

A 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:

  1. The metric hides it: accuracy rewards ignoring the class.
  2. The default threshold doesn't suit it: 0.5 is far too high for a 2% event.
  3. There are few real cases: nothing cures this except more of them.

Fix 1 and 2 before you reach for resampling.

02

Lazy models, again

Explore

Set 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?

0.500
How sure?
0.020
1.5
1.50
20
5000
threshold
flaggedpassed
pos5262
neg3124574

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 first; the figure appears when you commit.

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.

03

Four tools

Read
ToolWhat it changesEffect on probabilities
Stratified foldsWhich rows each fold testsNone
Class weightsHow much each class's errors countInflates the rare class
Rebalance training rowsThe rows a model trains onInflates the rare class
ThresholdOnly the final decisionNone

Weighting and resampling trade calibration for sensitivity at 0.5. If you use them, recalibrate if the probabilities themselves matter.

04

Does resampling help?

Predict

Predict 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?

Yes, far betterSomewhat better on this metric, at a priceNo effect
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.

05

Inside the folds, always

Predict

Predict 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?

The score goes up, for no good reasonThe score goes downNo change
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.

06

Undersampling

Read

Random 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.

07

Check your understanding

Checkpoint

Check 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 n/(k⋅nc)n / (k \cdot n_c). 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

1000/(2×91)≈5.51000 / (2 \times 91) \approx 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.

08

Try the options

In the app

In 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.

Python
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))
R
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)
09

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