Imbalanced Data & Cost-Sensitive Learning
Resampling, class weights and moving the threshold.
When one class is rare, the class ratio itself is rarely the real problem. The problems are what each mistake costs, how few rare examples there are in absolute terms, and whether the probabilities survive the fixes. This lesson derives the cost-optimal decision rule and the exact effect of rebalancing on a model's probabilities, adapts probabilities to new class priors, takes apart SMOTE, class weights and focal loss, and reviews what the evidence says about when corrections help.
What you’ll learn
- Derive the Bayes-optimal threshold for any two-class cost matrix, and Elkan's rule for rebalancing a training set to reach it.
- Show how resampling and class weights change predicted odds, correct the probabilities afterwards, and adapt them to new class priors with the EM procedure of Saerens et al.
- Explain SMOTE, class-weighted losses and focal loss, and what each does to calibration.
- Derive the optimal thresholds for balanced error (the prevalence) and for F1 (half the best F1), and evaluate imbalanced classifiers honestly.
- Summarize the evidence on when imbalance corrections help, for risk models, strong tabular learners and deep networks.
Costs, not counts
Write for the cost of predicting class when the true class is , so is the cost of a false positive and of a false negative. A sensible matrix makes each error cost more than the correct decision for that class: and (Elkan, 2001). Given the true posterior , the cost-sensitive decision is a threshold on :
The expected cost of predicting class averages the costs over the two possible truths:
Predict 1 exactly when that is no more expensive than predicting 0:
Rearranging gives a single threshold. A cost matrix has only one degree of freedom that matters for decisions; with zero cost for correct answers it is the familiar :
Give every negative weight (or replicate negatives by a factor ). Near any input there are now times as many negatives relative to positives, so the posterior odds the learner estimates are the true odds divided by :
Thresholding at is thresholding the true odds at . Setting this equal to the odds of gives the factor:
A false negative costs 4, a false positive 1, correct decisions nothing, and the learner thresholds at . By what factor should the number of negatives in the training set be multiplied?
Show the answer
0.25
, so the factor is : keep one negative in four (or, equivalently, weight each positive 4 times). The trained model then flags exactly the cases with true probability above 0.2. Its probabilities are no longer the population's, which the next step corrects.
Absolute versus relative rarity. A ratio of 1 positive to 1,000 negatives is harmless with examples, which leaves 10,000 positives to learn from, and crippling with , which leaves 10. Weiss (2004) argued that much of the difficulty attributed to imbalance is really absolute rarity: too few minority examples to estimate a decision region, especially when the rare class is made of small disjoint pockets. No resampling scheme creates information that the data lack.
Probabilities after resampling, and new priors
Any scheme that changes the class proportions the learner sees, by undersampling, oversampling or weighting, multiplies the learned odds by a constant, so the outputs are probabilities for a population that does not exist. With negatives kept at rate (or the classes weighted in ratio ), the correction is (Dal Pozzolo, Caelen, Johnson & Bontempi, 2015). For logistic regression it touches only the intercept: King & Zeng (2001) subtract from it, where is the population fraction of positives and the fraction in the sample.
The same algebra handles label shift at deployment. If the class-conditional distributions stay fixed while the priors move from to , a calibrated model can be adapted without retraining (Saerens, Latinne & Decaestecker, 2002).
Bayes' rule with unchanged : the new posterior reweights the old one by the ratio of priors and renormalizes:
If the new priors are unknown, estimate them from unlabeled deployment inputs by EM. E-step: adjust every posterior with the current guess , using the formula above. M-step: the new prior estimate is the average adjusted posterior:
Each iteration does not decrease the likelihood of the unlabeled inputs as a function of , so the procedure converges to a maximum-likelihood estimate of the new priors. It relies on calibrated training posteriors and on really staying fixed; Covariate, Label & Concept Shift covers alternatives that tolerate miscalibration.
A calibrated model trained on balanced data () outputs for a case. At deployment, positives are 10% of cases, and is unchanged. What is the adjusted probability?
- 0.5
- 0.05
- 0.1
- 0.9
Show the answer
C. 0.1
The reweighting factors are for positives and for negatives, so . A case the balanced model considered a coin flip carries only the new base rate's worth of evidence: the likelihood ratio at this is 1.
SMOTE, class weights and focal loss
SMOTE (Chawla, Bowyer, Hall & Kegelmeyer, 2002) oversamples the minority class without exact duplicates: for a minority example , pick one of its nearest minority neighbors ( in the original paper) and create with . It widens the minority region instead of sharpening it around copies. It also places synthetic points wherever two minority examples are neighbors, including across majority territory and around mislabeled points; it needs adapting for categorical features; and, like any resampling, it changes the base rate, so probabilities must be corrected afterwards. Many variants change where the synthetic points go.
Class weights minimize , which in expectation is resampling without the sampling noise. For flexible models that can fit the training data exactly the story changes. Byrd & Lipton (2019) found that in deep networks the effect of importance weights diminishes over successive epochs of training; L2 regularization and batch normalization partly restore it, dropout does not. Theory had prompted the question: on linearly separable data, gradient descent on linear models, and on deep linear networks, converges in direction to a solution that does not depend on the weights.
| 0 | 0.5 | 1 | 2 | 5 | |
|---|---|---|---|---|---|
| when the true probability is 0.9 | 0.900 | 0.833 | 0.774 | 0.694 | 0.597 |
For many classes with a long tail of rare ones, the deep-learning literature reweights by the "effective number" of examples per class rather than the raw count (Cui, Jia, Lin, Song & Belongie, 2019), enlarges the margins of rare classes in proportion to (Cao, Wei, Gaidon, Arechiga & Ma, 2019), or adjusts the logits by the label frequencies, either after training or inside the loss (Menon et al., 2021), which encourages larger relative margins for rare labels.
A large network that can fit its training set exactly is trained with class weights 10:1 in favor of the rare class, on separable data, for many epochs. What happens to the effect of the weights?
- It grows over training, as the rare class accumulates gradient
- It is exactly equivalent to moving the threshold by a factor of 10
- It stays constant throughout training
- It tends to fade as training continues and the network fits every example
Show the answer
D. It tends to fade as training continues and the network fits every example
Once every training example is fitted, the weighted and unweighted losses are both driven toward zero by similar solutions, and the weights matter less and less: Byrd & Lipton (2019) observed this diminishing effect in deep networks. For reliable cost-sensitive behavior, adjust the decision threshold or logits after training, on held-out data.
The right threshold for the right metric
The balanced error rate averages the error rates of the two classes. Per case, a false negative happens with probability and a false positive with , so balanced error is a cost-weighted error with these per-case costs:
Plug into the cost-optimal threshold: the optimal rule flags a case exactly when its calibrated probability exceeds the base rate, that is when its likelihood ratio exceeds 1. With classes the rule is : subtract from the logits.
F1 is not a cost-weighted error, but its optimum has a clean form too. Lipton, Elkan & Narayanaswamy (2014) showed that for calibrated probabilities the F1-optimal threshold is half the best achievable F1, and that a completely uninformative classifier maximizes F1 by labeling everything positive, an odd property for a metric often recommended for rare classes.
Write F1 with expected counts, . Flagging one more case whose calibrated probability is adds to TP, to FP and to FN, so the denominator grows by exactly 1:
Flagging the case helps exactly when exceeds half the current F1 (and unflagging a case helps exactly when its is below half). At the optimum neither move helps, so the flagged cases are those with probability above half the best F1. With uninformative scores every case has ; flagging all of them gives , and since , no case is worth unflagging: "flag everything" wins. The widget below lets you check the threshold rule.
Evaluating honestly. Use the precision–recall curve and average precision (whose chance level is the prevalence), precision at the number of cases you can act on, and expected cost with the costs stated. Stratify the folds so every fold has rare examples, report per-class rates with intervals, and never evaluate on a resampled test set: the test set must have the deployment class balance, or every precision you report describes a population that does not exist.
What the evidence says
Risk models. In clinical prediction the probability itself is the product. Van den Goorbergh, van Smeden, Timmerman & Van Calster (2022) compared logistic regression models trained with random undersampling, random oversampling and SMOTE against no correction. The corrected models were poorly calibrated, strongly overestimating the probability of the minority class; none had a higher area under the ROC curve; and the better balance of sensitivity and specificity they bought was matched by simply shifting the probability threshold. Their conclusion: outcome imbalance is not a problem in itself, and correcting it may worsen model performance.
Strong learners. Elor & Averbuch-Elor (2022) benchmarked balancing methods with several state-of-the-art classifiers and found that balancing did not improve the predictive performance of the strong ones, while supporting its known usefulness for weak classifiers.
Deep networks. Weights fade with long training (Byrd & Lipton, 2019), while post-hoc logit adjustment and margin-based losses are, as of the mid-2020s, common baselines for long-tailed recognition. Results depend heavily on the metric, the tuning budget and whether thresholds are tuned for the baselines too, so many published comparisons are hard to read.
Key takeaways
- The cost-optimal rule thresholds the calibrated posterior at ; Elkan's theorem gives the rebalancing factor that makes a threshold- learner act at .
- Resampling and class weights multiply the learned odds by a constant; undo it with or an intercept shift. New class priors are handled by reweighting posteriors, with EM when the priors are unknown.
- SMOTE interpolates between minority neighbors; class weights equal resampling in expectation but fade in overparameterized networks; focal loss is classification-calibrated but not proper.
- Balanced error is minimized by thresholding at the prevalence, F1 by thresholding at half the best F1; evaluate with PR curves, expected cost and per-class rates.
- For calibrated risk models and strong learners, corrections often do not help and can hurt; moving the threshold is the first resort.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Correct decisions cost nothing, a false positive costs 1 and a false negative costs 3. Above what calibrated probability should a case be classified positive?
- 0.75
- 0.5
- 0.33
- 0.25
Show the answer
D. 0.25
. Predicting positive at probability costs in expectation, predicting negative costs ; they balance at .
To minimize the balanced error rate, , at what calibrated probability should you threshold, if positives make up a fraction of the population?
- At
- At
- At
- At
Show the answer
B. At
Balanced error charges each false negative and each false positive per case, so . Flag a case when it is more likely to be positive than the base rate says: the likelihood ratio exceeds 1. With several classes the rule is , which logit adjustment implements.
A model is trained after randomly discarding 90% of the negatives. On real data, how do its predicted probabilities of the positive class compare with the truth?
- They are too high: the learned odds are 10 times the true odds
- They are correct, because each class's distribution is unchanged
- They are too low: the learned odds are a tenth of the true odds
- They are too high or too low at random
Show the answer
A. They are too high: the learned odds are 10 times the true odds
Keeping negatives at rate multiplies the posterior odds by . Correct with , or shift the logit by ; the ranking, and so the AUC, is unaffected.
Which statement about the focal loss with is correct?
- It is strictly proper, like log loss
- It changes which class the Bayes-optimal classifier predicts
- It is classification-calibrated but not strictly proper: its minimizer is a distorted version of the true posterior
- It can only be used with balanced classes
Show the answer
C. It is classification-calibrated but not strictly proper: its minimizer is a distorted version of the true posterior
The minimizer of the expected focal loss still lands on the correct side of , so the induced classifier is Bayes-optimal, but it is not the true probability: with and a true probability of 0.9 the minimizer is about 0.69. Its scores need a correction before being read as probabilities.
Further reading
- C. Elkan, "The foundations of cost-sensitive learning," Proceedings of IJCAI, 973–977 (2001).
- M. Saerens, P. Latinne & C. Decaestecker, "Adjusting the outputs of a classifier to new a priori probabilities: a simple procedure," Neural Computation 14(1), 21–41 (2002).
- N. V. Chawla, K. W. Bowyer, L. O. Hall & W. P. Kegelmeyer, "SMOTE: synthetic minority over-sampling technique," Journal of Artificial Intelligence Research 16, 321–357 (2002).
- H. He & E. A. Garcia, "Learning from imbalanced data," IEEE Transactions on Knowledge and Data Engineering 21(9), 1263–1284 (2009).
- R. van den Goorbergh, M. van Smeden, D. Timmerman & B. Van Calster, "The harm of class imbalance corrections for risk prediction models: illustration and simulation using logistic regression," Journal of the American Medical Informatics Association 29(9), 1525–1534 (2022).