Simple Algorithm
Machine Learning · Convergence · 26 min

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 c(i,j)c(i,j) for the cost of predicting class ii when the true class is jj, so c(1,0)c(1,0) is the cost of a false positive and c(0,1)c(0,1) of a false negative. A sensible matrix makes each error cost more than the correct decision for that class: c(1,0)>c(0,0)c(1,0)>c(0,0) and c(0,1)>c(1,1)c(0,1)>c(1,1) (Elkan, 2001). Given the true posterior p=P(y=1∣x)p=P(y=1\mid\mathbf x), the cost-sensitive decision is a threshold on pp:

DerivationThe optimal decision for any cost matrix
  1. R(i∣x)=(1−p) c(i,0)+p c(i,1)R(i\mid\mathbf x)=(1-p)\,c(i,0)+p\,c(i,1)

    The expected cost of predicting class ii averages the costs over the two possible truths:

  2. (1−p) c(1,0)+p c(1,1) ≤ (1−p) c(0,0)+p c(0,1)(1-p)\,c(1,0)+p\,c(1,1)\ \le\ (1-p)\,c(0,0)+p\,c(0,1)

    Predict 1 exactly when that is no more expensive than predicting 0:

  3. p ≥ p⋆=c(1,0)−c(0,0)c(1,0)−c(0,0)+c(0,1)−c(1,1)p\ \ge\ p^\star=\frac{c(1,0)-c(0,0)}{c(1,0)-c(0,0)+c(0,1)-c(1,1)}

    Rearranging gives a single threshold. A 2×22\times2 cost matrix has only one degree of freedom that matters for decisions; with zero cost for correct answers it is the familiar cFP/(cFP+cFN)c_{\mathrm{FP}}/(c_{\mathrm{FP}}+c_{\mathrm{FN}}):

DerivationProof
  1. pw1−pw=1w⋅p1−p\frac{p_w}{1-p_w}=\frac1w\cdot\frac{p}{1-p}

    Give every negative weight ww (or replicate negatives by a factor ww). Near any input there are now ww times as many negatives relative to positives, so the posterior odds the learner estimates are the true odds divided by ww:

  2. w p01−p0=p⋆1−p⋆⟹w=p⋆1−p⋆⋅1−p0p0w\,\frac{p_0}{1-p_0}=\frac{p^\star}{1-p^\star}\quad\Longrightarrow\quad w=\frac{p^\star}{1-p^\star}\cdot\frac{1-p_0}{p_0}

    Thresholding pwp_w at p0p_0 is thresholding the true odds at w p0/(1−p0)w\,p_0/(1-p_0). Setting this equal to the odds of p⋆p^\star gives the factor:

Predict before you look

A false negative costs 4, a false positive 1, correct decisions nothing, and the learner thresholds at p0=12p_0=\tfrac12. By what factor should the number of negatives in the training set be multiplied?

Show the answer

0.25

p⋆=1/(1+4)=0.2p^\star=1/(1+4)=0.2, so the factor is 0.20.8⋅0.50.5=0.25\frac{0.2}{0.8}\cdot\frac{0.5}{0.5}=0.25: 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 10710^7 examples, which leaves 10,000 positives to learn from, and crippling with 10410^4, 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 β\beta (or the classes weighted in ratio 1/β1/\beta), the correction is p=βps/(βps−ps+1)p=\beta p_s/(\beta p_s-p_s+1) (Dal Pozzolo, Caelen, Johnson & Bontempi, 2015). For logistic regression it touches only the intercept: King & Zeng (2001) subtract log⁡[1−ττ⋅yˉ1−yˉ]\log\big[\tfrac{1-\tau}{\tau}\cdot\tfrac{\bar y}{1-\bar y}\big] from it, where τ\tau is the population fraction of positives and yˉ\bar y the fraction in the sample.

The same algebra handles label shift at deployment. If the class-conditional distributions p(x∣y)p(\mathbf x\mid y) stay fixed while the priors move from πy\pi_y to πy′\pi'_y, a calibrated model can be adapted without retraining (Saerens, Latinne & Decaestecker, 2002).

DerivationAdjusting to new priors, known or unknown
  1. p′(y∣x)=p(x∣y) πy′∑kp(x∣k) πk′=πy′πy p(y∣x)∑kπk′πk p(k∣x)p'(y\mid\mathbf x)=\frac{p(\mathbf x\mid y)\,\pi'_y}{\sum_kp(\mathbf x\mid k)\,\pi'_k}=\frac{\frac{\pi'_y}{\pi_y}\,p(y\mid\mathbf x)}{\sum_k\frac{\pi'_k}{\pi_k}\,p(k\mid\mathbf x)}

    Bayes' rule with unchanged p(x∣y)p(\mathbf x\mid y): the new posterior reweights the old one by the ratio of priors and renormalizes:

  2. πy(s+1)=1N∑i=1Np(s)(y∣xi)\pi^{(s+1)}_y=\frac1N\sum_{i=1}^Np^{(s)}(y\mid\mathbf x_i)

    If the new priors are unknown, estimate them from unlabeled deployment inputs x1,…,xN\mathbf x_1,\dots,\mathbf x_N by EM. E-step: adjust every posterior with the current guess π(s)\pi^{(s)}, using the formula above. M-step: the new prior estimate is the average adjusted posterior:

  3. π′ ↦ ∑i=1Nlog⁡∑yπy′ p(xi∣y)is non-decreasing along the iterations\pi'\ \mapsto\ \sum_{i=1}^N\log\sum_y\pi'_y\,p(\mathbf x_i\mid y)\quad\text{is non-decreasing along the iterations}

    Each iteration does not decrease the likelihood of the unlabeled inputs as a function of π′\pi', so the procedure converges to a maximum-likelihood estimate of the new priors. It relies on calibrated training posteriors and on p(x∣y)p(\mathbf x\mid y) really staying fixed; Covariate, Label & Concept Shift covers alternatives that tolerate miscalibration.

Check your understanding

A calibrated model trained on balanced data (π=0.5\pi=0.5) outputs p(y=1∣x)=0.5p(y=1\mid\mathbf x)=0.5 for a case. At deployment, positives are 10% of cases, and p(x∣y)p(\mathbf x\mid y) is unchanged. What is the adjusted probability?

  1. 0.5
  2. 0.05
  3. 0.1
  4. 0.9
Show the answer

C. 0.1

The reweighting factors are 0.1/0.5=0.20.1/0.5=0.2 for positives and 0.9/0.5=1.80.9/0.5=1.8 for negatives, so p′=0.2⋅0.50.2⋅0.5+1.8⋅0.5=0.1p'=\frac{0.2\cdot0.5}{0.2\cdot0.5+1.8\cdot0.5}=0.1. A case the balanced model considered a coin flip carries only the new base rate's worth of evidence: the likelihood ratio at this x\mathbf x 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 x\mathbf x, pick one of its kk nearest minority neighbors xnn\mathbf x_{\text{nn}} (k=5k=5 in the original paper) and create x+u(xnn−x)\mathbf x+u(\mathbf x_{\text{nn}}-\mathbf x) with u∼Uniform(0,1)u\sim\mathrm{Uniform}(0,1). 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 ∑iwyi ℓ(f(xi),yi)\sum_iw_{y_i}\,\ell(f(\mathbf x_i),y_i), 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.

FL(pt)=−αt (1−pt)γlog⁡pt,pt={p^y=11−p^y=0\mathrm{FL}(p_t)=-\alpha_t\,(1-p_t)^\gamma\log p_t,\qquad p_t=\begin{cases}\hat p&y=1\\1-\hat p&y=0\end{cases}
The focal loss of Lin, Goyal, Girshick, He & Dollár (2017) multiplies the log loss by (1−pt)γ(1-p_t)^\gamma, shrinking the contribution of examples that are already classified confidently, so that the vast number of easy background examples in dense object detection does not swamp training; αt\alpha_t is an optional class weight. They found γ=2\gamma=2 worked best for their detector.
γ\gamma00.5125
q⋆q^\star when the true probability is 0.90.9000.8330.7740.6940.597
The report q⋆q^\star that minimizes the expected focal loss, −0.9(1−q)γlog⁡q−0.1 qγlog⁡(1−q)-0.9(1-q)^\gamma\log q-0.1\,q^\gamma\log(1-q), found numerically. For γ>0\gamma>0 it is pulled toward 12\tfrac12 but stays on the correct side: focal loss is classification-calibrated yet not strictly proper, and Charoenphakdee, Vongkulbhisal, Chairatanakul & Sugiyama (2021) gave a closed-form transformation that recovers the posterior. The pull toward 12\tfrac12 is consistent with Mukhoti et al. (2020), who used focal loss to make overconfident deep networks better calibrated.

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 ny−1/4n_y^{-1/4} (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.

Check your understanding

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?

  1. It grows over training, as the rare class accumulates gradient
  2. It is exactly equivalent to moving the threshold by a factor of 10
  3. It stays constant throughout training
  4. 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

DerivationBalanced error is minimized at the prevalence
  1. BER=12(FNR+FPR),cFN=12π,cFP=12(1−π)\mathrm{BER}=\tfrac12\big(\mathrm{FNR}+\mathrm{FPR}\big),\qquad c_{\mathrm{FN}}=\frac{1}{2\pi},\qquad c_{\mathrm{FP}}=\frac{1}{2(1-\pi)}

    The balanced error rate averages the error rates of the two classes. Per case, a false negative happens with probability π FNR\pi\,\mathrm{FNR} and a false positive with (1−π) FPR(1-\pi)\,\mathrm{FPR}, so balanced error is a cost-weighted error with these per-case costs:

  2. p⋆=cFPcFP+cFN=1/(1−π)1/(1−π)+1/π=πp^\star=\frac{c_{\mathrm{FP}}}{c_{\mathrm{FP}}+c_{\mathrm{FN}}}=\frac{1/(1-\pi)}{1/(1-\pi)+1/\pi}=\pi

    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 KK classes the rule is arg max⁡yp(y∣x)/πy\argmax_yp(y\mid\mathbf x)/\pi_y: subtract log⁡πy\log\pi_y 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.

DerivationWhy the F1-optimal threshold is half the best F1
  1. Fnew=2(TP+p)2 TP+FP+FN+1F_{\text{new}}=\frac{2(\mathrm{TP}+p)}{2\,\mathrm{TP}+\mathrm{FP}+\mathrm{FN}+1}

    Write F1 with expected counts, F=2 TP/(2 TP+FP+FN)F=2\,\mathrm{TP}/(2\,\mathrm{TP}+\mathrm{FP}+\mathrm{FN}). Flagging one more case whose calibrated probability is pp adds pp to TP, 1−p1-p to FP and −p-p to FN, so the denominator grows by exactly 1:

  2. Fnew>F  ⟺  p (2 TP+FP+FN)>TP  ⟺  p>F2F_{\text{new}}>F\iff p\,(2\,\mathrm{TP}+\mathrm{FP}+\mathrm{FN})>\mathrm{TP}\iff p>\frac F2

    Flagging the case helps exactly when pp exceeds half the current F1 (and unflagging a case helps exactly when its pp 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 p=πp=\pi; flagging all of them gives F=2π/(1+π)F=2\pi/(1+\pi), and since π>F/2\pi>F/2, 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 p⋆=c(1,0)−c(0,0)c(1,0)−c(0,0)+c(0,1)−c(1,1)p^\star=\frac{c(1,0)-c(0,0)}{c(1,0)-c(0,0)+c(0,1)-c(1,1)}; Elkan's theorem gives the rebalancing factor that makes a threshold-p0p_0 learner act at p⋆p^\star.
  • Resampling and class weights multiply the learned odds by a constant; undo it with p=βps/(βps−ps+1)p=\beta p_s/(\beta p_s-p_s+1) 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.

Question 1

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?

  1. 0.75
  2. 0.5
  3. 0.33
  4. 0.25
Show the answer

D. 0.25

p⋆=c(1,0)c(1,0)+c(0,1)=11+3=0.25p^\star=\frac{c(1,0)}{c(1,0)+c(0,1)}=\frac1{1+3}=0.25. Predicting positive at probability pp costs 1−p1-p in expectation, predicting negative costs 3p3p; they balance at p=0.25p=0.25.

Question 2

To minimize the balanced error rate, 12(FNR+FPR)\tfrac12(\mathrm{FNR}+\mathrm{FPR}), at what calibrated probability should you threshold, if positives make up a fraction π\pi of the population?

  1. At 12\tfrac12
  2. At π\pi
  3. At 1−π1-\pi
  4. At π/2\pi/2
Show the answer

B. At π\pi

Balanced error charges each false negative 1/(2π)1/(2\pi) and each false positive 1/(2(1−π))1/(2(1-\pi)) per case, so p⋆=1/(1−π)1/(1−π)+1/π=πp^\star=\frac{1/(1-\pi)}{1/(1-\pi)+1/\pi}=\pi. 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 arg max⁡yp(y∣x)/πy\argmax_y p(y\mid\mathbf x)/\pi_y, which logit adjustment implements.

Question 3

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?

  1. They are too high: the learned odds are 10 times the true odds
  2. They are correct, because each class's distribution is unchanged
  3. They are too low: the learned odds are a tenth of the true odds
  4. 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 β=0.1\beta=0.1 multiplies the posterior odds by 1/β=101/\beta=10. Correct with p=βps/(βps−ps+1)p=\beta p_s/(\beta p_s-p_s+1), or shift the logit by log⁡β\log\beta; the ranking, and so the AUC, is unaffected.

Question 4

Which statement about the focal loss −(1−pt)γlog⁡pt-(1-p_t)^\gamma\log p_t with γ>0\gamma>0 is correct?

  1. It is strictly proper, like log loss
  2. It changes which class the Bayes-optimal classifier predicts
  3. It is classification-calibrated but not strictly proper: its minimizer is a distorted version of the true posterior
  4. 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 12\tfrac12, so the induced classifier is Bayes-optimal, but it is not the true probability: with γ=2\gamma=2 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).