Class imbalance: weights and focal loss

Fraud is a few out of 1,000 payments. Broken parts are a few out of thousands. When the thing you want to find is rare, a model can learn only the common class and still get a high score. Move the γ slider to see how much the loss of easy examples shrinks, then step through how the focal loss formula is built.

Short answer. When one class is much more common, common, easy examples fill up the total loss and the model learns less about the rare class. There are four fixes: give the rare class's loss more weight, oversample the rare class or undersample the common one, use focal loss −α·(1 − p)^γ·log p to shrink the loss of easy examples, or keep the model and move the decision threshold. Measure with precision, recall and the PR curve, not accuracy.

p is the probability the model gave the right class. Near 1 means an easy example it already gets right. Near 0 means a hard example it gets wrong. Change γ with the slider or the number box (0 to 5) and only the blue focal loss curve moves. The green cross-entropy does not depend on γ. Losses above 3 are cut off at the top. This is a small stand-in that draws the formulas only, with no real model.

Try this. ① At the start, γ = 2. The easy example's loss goes from 0.105 to 0.00105, one hundredth. The hard example goes from 2.3 to 1.87, 0.81 times. Hard ÷ easy goes from 21.9 times to 1,770 times. ② Set γ to 0 and the two curves lie on top of each other: focal loss becomes cross-entropy. ③ At γ = 1 the ratio is 197 times, and with 990 easy and 10 hard examples, the hard ones are 66.5% of the total (18.1% at γ = 0, 94.7% at γ = 2). ④ Push γ to 5 and the share reaches 100.0%, but the hard example's loss also drops from 2.3 to 1.36. A large γ makes the whole learning signal smaller.

Definitions

The text below explains with pictures and experiments. The textbook definitions are as follows. The rare side is positive (answer y = 1), the common side is negative (y = 0), p is the probability of positive that the model gives, and log is the natural log.

class imbalance
A state of the data where one class has far more examples than another. The larger side is the majority class and the smaller side is the minority class.
class weight
A method that multiplies each example's loss by a weight wc set for that example's answer class, so the minority class's loss counts more. Used with cross-entropy, it is weighted cross-entropy. The common balanced choice uses the total number of examples N, the number of classes C, and the number of examples in class c, Nc, to give the weight below.

wc=NCNc

oversampling, undersampling
Oversampling grows the minority class in the training data by putting its examples in again or making new ones. Undersampling shrinks the majority class by using only part of its examples. Both only change the class ratio of the training data, and are done only on the training data after splitting into training and test.
focal loss
Cross-entropy multiplied by (1 − pt)^γ and by a class weight αt. pt is the probability given to the answer class (p if positive, 1 − p if negative), αt is α if positive and 1 − α if negative, and γ ≥ 0. It cuts the loss of examples already answered well (pt near 1), and with γ = 0 and αt = 1 it is the same as cross-entropy −log pt.

FL(pt)=−αt(1−pt)γlogpt

threshold moving
Keeping the trained model as it is and changing the threshold (usually 0.5) above which p is judged positive. The threshold is chosen on validation data.
precision, recall, F1 score
TP is the number of positives judged positive, FP the number of negatives wrongly judged positive, and FN the number of positives missed as negative. Precision P is the share of real positives among those judged positive, recall R is the share judged positive among the real positives, and F1 is their harmonic mean.

P=TPTP+FP,R=TPTP+FN,F1=2PRP+R

1. What happens when one class is much more common

Class imbalance means one kind of answer (class) shows up far more often than another. For example, 990 normal payments and 10 fraud cases. Two things go wrong.

The loss is cross-entropy, −log p, where p is the probability the model gave the right class. Here are the two examples from the lab above.

ExampleProbability p given to the right classCross-entropy −log p
Easy (already right)0.90.105
Hard (wrong)0.12.3

One hard example costs 21.9 times as much as one easy example. But if there are 99 times more easy ones, the easy side has the bigger sum. Section 3 counts it out.

2. How the formula is built

Focal loss is cross-entropy multiplied by two extra pieces. Press "Next" and the formula gains one piece at a time (the orange background marks the new piece), and the curves in the picture change to match. The easy (p = 0.9) and hard (p = 0.1) examples are the same as in the lab above, and γ is fixed at 2.

  1. Start: −log p. This is cross-entropy. It goes to 0 as the model gets it right (p → 1) and grows without limit as it gets it wrong (p → 0). Even an easy example has a loss above 0 (0.105), so many of them can fill up the sum.
  2. Shrink the easy ones: (1 − p)^γ · (−log p). 1 − p says "how wrong is it". For a well-classified example it is close to 0, so raising it to the power γ and multiplying almost wipes out the loss. For a wrong example it is close to 1, so the loss stays almost the same. Why: the more the easy ones shrink, the more the hard ones make up the sum, so training focuses on the hard ones. In the paper's words, with p = 0.9 and γ = 2 the loss is 100 times smaller, and for p of 0.5 or less it is at most 4 times smaller.
  3. Class weight: α · (1 − p)^γ · (−log p). Multiply the rare class's loss by α and the common class's loss by 1 − α. The picture uses α = 0.75. Why: (1 − p)^γ only looks at whether an example is easy or hard, not at its class. α handles the balance between classes. Using α alone (γ = 0) is weighted cross-entropy, in other words class weights.
  4. Done: FL(p_t) = −α_t · (1 − p_t)^γ · log p_t. p is the probability of "positive", so when the right answer is negative, the probability given to the right class is 1 − p. Wrap that up as p_t (p for a positive, 1 − p for a negative) and both classes fit one formula. α_t is α for a positive and 1 − α for a negative. With γ = 0 and α_t = 1 it is cross-entropy again.

Try this. Watch "the share of the hard examples" in the text under the picture at each step. With 990 easy and 10 hard examples it climbs ① 18.1% → ② 94.7% → ③ 98.2%. At ③, the rare class's hard example is 1.4 and the common class's easy example is 0.000263.

The value of α can surprise you. In the paper's experiments, with γ = 0 (cross-entropy with α only), α = 0.75 for the rare class (objects) worked best. With γ = 2, α = 0.25 worked best. The paper says α should go down a little as γ goes up. γ and α affect each other, so pick them together. torchvision's sigmoid_focal_loss also defaults to α = 0.25 (for the positive class) and γ = 2.

3. Work it out by hand: 990 and 10

Say the 990 examples of the common class are all easy (the model already gives them p = 0.9) and the 10 examples of the rare class are all hard (p = 0.1).

  1. Accuracy. Always answering "common" gives 990 ÷ 1000 = 99%. Rare examples found: 0.
  2. Sum of cross-entropy. Common side 990 × 0.105 = 104, rare side 10 × 2.3 = 23. The rare side's share is 23 ÷ (104 + 23) = 18.1%.
  3. Class weights (scikit-learn's balanced). Weight = total count ÷ (number of classes × count of that class). Common: 1000 ÷ (2 × 990) = 0.505. Rare: 1000 ÷ (2 × 10) = 50. Now each class's weights add up to the same amount: 990 × 0.505 = 500 and 10 × 50 = 500. The loss sums are 52.7 for the common side and about 1,151 for the rare side, a 95.6% share.
  4. Focal loss (γ = 2). Common 990 × 0.00105 = 1.04, rare 10 × 1.87 = 18.7. Share 94.7%. Add α = 0.75 and it is 0.261 and 14, so 98.2%.
MethodSum over the 990 commonSum over the 10 rareRare share
Cross-entropy1042318.1%
Class weights (balanced)52.71,15195.6%
Cross-entropy + α = 0.75 only26.117.339.8%
Focal loss (γ = 2)1.0418.794.7%
Focal loss (γ = 2, α = 0.75)0.2611498.2%

Weights look at the class and shrink the whole common side. Focal loss looks at how easy an example is and shrinks the ones already right. Here every common example is easy, so the results look alike. If the common class has hard examples too, focal loss does not shrink those.

4. Properties to know

PropertyIn plain wordsWhere to see it
γ = 0 gives cross-entropyFocal loss is a wider version of cross-entropy. γ sets how much it shrinksLab ① at γ = 0
The easier, the more it shrinksWith γ = 2: one hundredth at p = 0.9, at most one quarter for p ≤ 0.5Lab ① at γ = 2
A large γ shrinks hard examples tooAt p = 0.1 with γ = 5: 2.3 → 1.36. Too large and the learning signal gets weakLab ① at γ = 5
α only changes the heightIt keeps the shape of the curve and only sets the balance between classesSection 2, step ③
Weights and resampling inflate probabilitiesA model trained with weights, oversampling or undersampling gives the rare class a higher probability than the real rate. Be careful if you use the probabilities as they areSection 5

5. Four fixes

# scikit-learn: class weights
LogisticRegression(class_weight="balanced")

# PyTorch: one weight per class (common, rare)
loss_fn = torch.nn.CrossEntropyLoss(weight=torch.tensor([0.505, 50.0]))
# two classes (positive and negative): a number to multiply the positive loss by, e.g. 990 / 10
loss_fn = torch.nn.BCEWithLogitsLoss(pos_weight=torch.tensor([99.0]))

# torchvision: focal loss (defaults alpha=0.25, gamma=2)
loss = torchvision.ops.sigmoid_focal_loss(logits, targets, alpha=0.25, gamma=2, reduction="mean")

6. When to use what

OptionGoodBadUse it when
Move the thresholdNo retraining. Probabilities stay the same, only the decision changesCannot help if the model barely learned the rare class. Needs a validation set to pick itTry it first. When a false alarm and a miss cost different amounts (screening, fraud)
Class weightsOne line to turn on. No data added or thrown awayRare class probabilities get inflated. Very large weights let a few rare examples shake trainingModerate imbalance and you can choose the loss. A default thing to try for most models
OversamplingNo change to the model or loss. Works with tools whose loss you cannot changeRepeating the same examples makes it easy to overfit them. Training takes longer. Probabilities get inflatedSmall data with very few rare examples
UndersamplingLess data, so training is fasterThrows away information about the common class. Probabilities get inflatedSo many common examples that using them all is too heavy
Focal lossWorks better the more easy examples there are. Looks at easy versus hard, not just the classγ and α must be tuned together. Does not shrink hard examples of the common classEasy examples fill up the loss. Object detection, where most candidates are background

7. What to measure instead of accuracy

Call the rare class "positive" and compare what the model called positive with the truth.

MeasureMeaningFormula
RecallOf the real positives, how many were found. Few misses?positives found ÷ real positives
PrecisionOf the ones called positive, how many were right. Few false alarms?positives found ÷ number called positive
F1Precision and recall in one number (harmonic mean)2 × precision × recall ÷ (precision + recall)
PR curve, average precisionPrecision and recall across every threshold, not tied to one thresholdAverage precision measures the area under the curve

Example. The model finds 8 of the 10 rare examples and wrongly calls 50 of the 990 common ones positive. Recall is 8 ÷ 10 = 80.0% and the false positive rate is 50 ÷ 990 = 5.1%, but precision is 8 ÷ 58 = 13.8%. The false positive rate, the across axis of the ROC curve, divides by the whole common class, so 50 false alarms look small. Precision shows plainly that 50 of the 58 alarms are false. That is why, with heavy imbalance, the PR curve tells you more than the ROC curve (Saito and Rehmsmeier). Keep the test set at its real class mix: do not oversample or undersample it.

Where it is used

Frequently asked questions

Accuracy is 99%. Why is the model bad?

If the rare class is only 1% of the data, a model that always answers with the common class is 99% accurate. It never finds a single rare example (recall 0). Accuracy is decided almost entirely by the common class, so measure the rare class on its own with precision, recall and the PR curve.

How are class weights different from oversampling?

Putting a rare example in k times and multiplying its loss by k give the same total loss. The difference: oversampling makes the data bigger, so each pass takes longer and the model sees the same examples again and again. Weights keep the data as it is and only change the loss. Both push the model's probabilities up for the rare class.

When should I use focal loss?

Use it when there are so many easy, already-correct examples that they fill up the total loss. The original paper made it for object detection, where most candidate spots are background. γ and α have to be tuned together. In the paper's experiments, α = 0.25 worked best with γ = 2.

Words

Words used hereTextbook terms
one class is much more commonclass imbalance, imbalanced data
common class, rare classmajority class, minority class
a number multiplied into each class's lossclass weight, weighted cross-entropy
putting in more, using feweroversampling, undersampling, SMOTE
a loss that shrinks easy examplesfocal loss. (1 − p_t)^γ is the modulating factor, γ the focusing parameter
probability given to the right classp_t
moving the decision thresholdthreshold moving, threshold tuning
few misses, few false alarmsrecall, precision, F1 score
the precision and recall curve and its areaprecision-recall (PR) curve, average precision
share of negatives called positivefalse positive rate

Sources

← Regression lossesDropout →